babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformNormal = function (vector, transformation) {
  680. var result = Vector3.Zero();
  681. Vector3.TransformNormalToRef(vector, transformation, result);
  682. return result;
  683. };
  684. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  685. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  686. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  687. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  688. };
  689. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  690. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  691. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  692. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  693. };
  694. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  695. var squared = amount * amount;
  696. var cubed = amount * squared;
  697. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  698. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  699. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  700. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  701. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  702. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  703. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  704. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  705. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Clamp = function (value, min, max) {
  709. var x = value.x;
  710. x = (x > max.x) ? max.x : x;
  711. x = (x < min.x) ? min.x : x;
  712. var y = value.y;
  713. y = (y > max.y) ? max.y : y;
  714. y = (y < min.y) ? min.y : y;
  715. var z = value.z;
  716. z = (z > max.z) ? max.z : z;
  717. z = (z < min.z) ? min.z : z;
  718. return new Vector3(x, y, z);
  719. };
  720. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  721. var squared = amount * amount;
  722. var cubed = amount * squared;
  723. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  724. var part2 = (-2.0 * cubed) + (3.0 * squared);
  725. var part3 = (cubed - (2.0 * squared)) + amount;
  726. var part4 = cubed - squared;
  727. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  728. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  729. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Lerp = function (start, end, amount) {
  733. var x = start.x + ((end.x - start.x) * amount);
  734. var y = start.y + ((end.y - start.y) * amount);
  735. var z = start.z + ((end.z - start.z) * amount);
  736. return new Vector3(x, y, z);
  737. };
  738. Vector3.Dot = function (left, right) {
  739. return (left.x * right.x + left.y * right.y + left.z * right.z);
  740. };
  741. Vector3.Cross = function (left, right) {
  742. var result = Vector3.Zero();
  743. Vector3.CrossToRef(left, right, result);
  744. return result;
  745. };
  746. Vector3.CrossToRef = function (left, right, result) {
  747. result.x = left.y * right.z - left.z * right.y;
  748. result.y = left.z * right.x - left.x * right.z;
  749. result.z = left.x * right.y - left.y * right.x;
  750. };
  751. Vector3.Normalize = function (vector) {
  752. var result = Vector3.Zero();
  753. Vector3.NormalizeToRef(vector, result);
  754. return result;
  755. };
  756. Vector3.NormalizeToRef = function (vector, result) {
  757. result.copyFrom(vector);
  758. result.normalize();
  759. };
  760. Vector3.Project = function (vector, world, transform, viewport) {
  761. var cw = viewport.width;
  762. var ch = viewport.height;
  763. var cx = viewport.x;
  764. var cy = viewport.y;
  765. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  766. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  767. return Vector3.TransformCoordinates(vector, finalMatrix);
  768. };
  769. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  770. var matrix = world.multiply(transform);
  771. matrix.invert();
  772. source.x = source.x / viewportWidth * 2 - 1;
  773. source.y = -(source.y / viewportHeight * 2 - 1);
  774. var vector = Vector3.TransformCoordinates(source, matrix);
  775. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  776. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  777. vector = vector.scale(1.0 / num);
  778. }
  779. return vector;
  780. };
  781. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  782. var matrix = world.multiply(view).multiply(projection);
  783. matrix.invert();
  784. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  785. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  786. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  787. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  788. vector = vector.scale(1.0 / num);
  789. }
  790. return vector;
  791. };
  792. Vector3.Minimize = function (left, right) {
  793. var min = left.clone();
  794. min.MinimizeInPlace(right);
  795. return min;
  796. };
  797. Vector3.Maximize = function (left, right) {
  798. var max = left.clone();
  799. max.MaximizeInPlace(right);
  800. return max;
  801. };
  802. Vector3.Distance = function (value1, value2) {
  803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  804. };
  805. Vector3.DistanceSquared = function (value1, value2) {
  806. var x = value1.x - value2.x;
  807. var y = value1.y - value2.y;
  808. var z = value1.z - value2.z;
  809. return (x * x) + (y * y) + (z * z);
  810. };
  811. Vector3.Center = function (value1, value2) {
  812. var center = value1.add(value2);
  813. center.scaleInPlace(0.5);
  814. return center;
  815. };
  816. /**
  817. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  819. * to something in order to rotate it from its local system to the given target system.
  820. */
  821. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  822. var rotation = Vector3.Zero();
  823. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  824. return rotation;
  825. };
  826. /**
  827. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  828. */
  829. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  830. var u = Vector3.Normalize(axis1);
  831. var w = Vector3.Normalize(axis3);
  832. // world axis
  833. var X = Axis.X;
  834. var Y = Axis.Y;
  835. // equation unknowns and vars
  836. var yaw = 0.0;
  837. var pitch = 0.0;
  838. var roll = 0.0;
  839. var x = 0.0;
  840. var y = 0.0;
  841. var z = 0.0;
  842. var t = 0.0;
  843. var sign = -1.0;
  844. var nbRevert = 0;
  845. var cross;
  846. var dot = 0.0;
  847. // step 1 : rotation around w
  848. // Rv3(u) = u1, and u1 belongs to plane xOz
  849. // Rv3(w) = w1 = w invariant
  850. var u1;
  851. var v1;
  852. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  853. z = 1.0;
  854. }
  855. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  856. x = 1.0;
  857. }
  858. else {
  859. t = w.z / w.x;
  860. x = -t * Math.sqrt(1 / (1 + t * t));
  861. z = Math.sqrt(1 / (1 + t * t));
  862. }
  863. u1 = new Vector3(x, y, z);
  864. u1.normalize();
  865. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  866. v1.normalize();
  867. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  868. cross.normalize();
  869. if (Vector3.Dot(w, cross) < 0) {
  870. sign = 1.0;
  871. }
  872. dot = Vector3.Dot(u, u1);
  873. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  874. roll = Math.acos(dot) * sign;
  875. if (Vector3.Dot(u1, X) < 0) {
  876. roll = Math.PI + roll;
  877. u1 = u1.scaleInPlace(-1);
  878. v1 = v1.scaleInPlace(-1);
  879. nbRevert++;
  880. }
  881. // step 2 : rotate around u1
  882. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  883. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  884. var w2;
  885. var v2;
  886. x = 0.0;
  887. y = 0.0;
  888. z = 0.0;
  889. sign = -1;
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. x = 1.0;
  892. }
  893. else {
  894. t = u1.z / u1.x;
  895. x = -t * Math.sqrt(1 / (1 + t * t));
  896. z = Math.sqrt(1 / (1 + t * t));
  897. }
  898. w2 = new Vector3(x, y, z);
  899. w2.normalize();
  900. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  901. v2.normalize();
  902. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  903. cross.normalize();
  904. if (Vector3.Dot(u1, cross) < 0) {
  905. sign = 1.0;
  906. }
  907. dot = Vector3.Dot(w, w2);
  908. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  909. pitch = Math.acos(dot) * sign;
  910. if (Vector3.Dot(v2, Y) < 0) {
  911. pitch = Math.PI + pitch;
  912. v2 = v2.scaleInPlace(-1);
  913. w2 = w2.scaleInPlace(-1);
  914. nbRevert++;
  915. }
  916. // step 3 : rotate around v2
  917. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  918. sign = -1;
  919. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  920. cross.normalize();
  921. if (Vector3.Dot(cross, Y) < 0) {
  922. sign = 1.0;
  923. }
  924. dot = Vector3.Dot(u1, X);
  925. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  926. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  927. if (dot < 0 && nbRevert < 2) {
  928. yaw = Math.PI + yaw;
  929. }
  930. ref.x = pitch;
  931. ref.y = yaw;
  932. ref.z = roll;
  933. };
  934. return Vector3;
  935. })();
  936. BABYLON.Vector3 = Vector3;
  937. //Vector4 class created for EulerAngle class conversion to Quaternion
  938. var Vector4 = (function () {
  939. function Vector4(x, y, z, w) {
  940. this.x = x;
  941. this.y = y;
  942. this.z = z;
  943. this.w = w;
  944. }
  945. Vector4.prototype.toString = function () {
  946. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  947. };
  948. // Operators
  949. Vector4.prototype.asArray = function () {
  950. var result = [];
  951. this.toArray(result, 0);
  952. return result;
  953. };
  954. Vector4.prototype.toArray = function (array, index) {
  955. if (index === undefined) {
  956. index = 0;
  957. }
  958. array[index] = this.x;
  959. array[index + 1] = this.y;
  960. array[index + 2] = this.z;
  961. array[index + 3] = this.w;
  962. return this;
  963. };
  964. Vector4.prototype.addInPlace = function (otherVector) {
  965. this.x += otherVector.x;
  966. this.y += otherVector.y;
  967. this.z += otherVector.z;
  968. this.w += otherVector.w;
  969. return this;
  970. };
  971. Vector4.prototype.add = function (otherVector) {
  972. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  973. };
  974. Vector4.prototype.addToRef = function (otherVector, result) {
  975. result.x = this.x + otherVector.x;
  976. result.y = this.y + otherVector.y;
  977. result.z = this.z + otherVector.z;
  978. result.w = this.w + otherVector.w;
  979. return this;
  980. };
  981. Vector4.prototype.subtractInPlace = function (otherVector) {
  982. this.x -= otherVector.x;
  983. this.y -= otherVector.y;
  984. this.z -= otherVector.z;
  985. this.w -= otherVector.w;
  986. return this;
  987. };
  988. Vector4.prototype.subtract = function (otherVector) {
  989. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  990. };
  991. Vector4.prototype.subtractToRef = function (otherVector, result) {
  992. result.x = this.x - otherVector.x;
  993. result.y = this.y - otherVector.y;
  994. result.z = this.z - otherVector.z;
  995. result.w = this.w - otherVector.w;
  996. return this;
  997. };
  998. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  999. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1000. };
  1001. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = this.x - x;
  1003. result.y = this.y - y;
  1004. result.z = this.z - z;
  1005. result.w = this.w - w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.negate = function () {
  1009. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1010. };
  1011. Vector4.prototype.scaleInPlace = function (scale) {
  1012. this.x *= scale;
  1013. this.y *= scale;
  1014. this.z *= scale;
  1015. this.w *= scale;
  1016. return this;
  1017. };
  1018. Vector4.prototype.scale = function (scale) {
  1019. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1020. };
  1021. Vector4.prototype.scaleToRef = function (scale, result) {
  1022. result.x = this.x * scale;
  1023. result.y = this.y * scale;
  1024. result.z = this.z * scale;
  1025. result.w = this.w * scale;
  1026. };
  1027. Vector4.prototype.equals = function (otherVector) {
  1028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1029. };
  1030. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1031. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1032. return otherVector
  1033. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1034. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1035. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1036. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1037. };
  1038. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1039. return this.x === x && this.y === y && this.z === z && this.w === w;
  1040. };
  1041. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1042. this.x *= otherVector.x;
  1043. this.y *= otherVector.y;
  1044. this.z *= otherVector.z;
  1045. this.w *= otherVector.w;
  1046. return this;
  1047. };
  1048. Vector4.prototype.multiply = function (otherVector) {
  1049. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1050. };
  1051. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1052. result.x = this.x * otherVector.x;
  1053. result.y = this.y * otherVector.y;
  1054. result.z = this.z * otherVector.z;
  1055. result.w = this.w * otherVector.w;
  1056. return this;
  1057. };
  1058. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1059. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1060. };
  1061. Vector4.prototype.divide = function (otherVector) {
  1062. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1063. };
  1064. Vector4.prototype.divideToRef = function (otherVector, result) {
  1065. result.x = this.x / otherVector.x;
  1066. result.y = this.y / otherVector.y;
  1067. result.z = this.z / otherVector.z;
  1068. result.w = this.w / otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.MinimizeInPlace = function (other) {
  1072. if (other.x < this.x)
  1073. this.x = other.x;
  1074. if (other.y < this.y)
  1075. this.y = other.y;
  1076. if (other.z < this.z)
  1077. this.z = other.z;
  1078. if (other.w < this.w)
  1079. this.w = other.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.MaximizeInPlace = function (other) {
  1083. if (other.x > this.x)
  1084. this.x = other.x;
  1085. if (other.y > this.y)
  1086. this.y = other.y;
  1087. if (other.z > this.z)
  1088. this.z = other.z;
  1089. if (other.w > this.w)
  1090. this.w = other.w;
  1091. return this;
  1092. };
  1093. // Properties
  1094. Vector4.prototype.length = function () {
  1095. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1096. };
  1097. Vector4.prototype.lengthSquared = function () {
  1098. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1099. };
  1100. // Methods
  1101. Vector4.prototype.normalize = function () {
  1102. var len = this.length();
  1103. if (len === 0)
  1104. return this;
  1105. var num = 1.0 / len;
  1106. this.x *= num;
  1107. this.y *= num;
  1108. this.z *= num;
  1109. this.w *= num;
  1110. return this;
  1111. };
  1112. Vector4.prototype.clone = function () {
  1113. return new Vector4(this.x, this.y, this.z, this.w);
  1114. };
  1115. Vector4.prototype.copyFrom = function (source) {
  1116. this.x = source.x;
  1117. this.y = source.y;
  1118. this.z = source.z;
  1119. this.w = source.w;
  1120. return this;
  1121. };
  1122. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1123. this.x = x;
  1124. this.y = y;
  1125. this.z = z;
  1126. this.w = w;
  1127. return this;
  1128. };
  1129. // Statics
  1130. Vector4.FromArray = function (array, offset) {
  1131. if (!offset) {
  1132. offset = 0;
  1133. }
  1134. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1135. };
  1136. Vector4.FromArrayToRef = function (array, offset, result) {
  1137. result.x = array[offset];
  1138. result.y = array[offset + 1];
  1139. result.z = array[offset + 2];
  1140. result.w = array[offset + 3];
  1141. };
  1142. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1143. result.x = array[offset];
  1144. result.y = array[offset + 1];
  1145. result.z = array[offset + 2];
  1146. result.w = array[offset + 3];
  1147. };
  1148. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1149. result.x = x;
  1150. result.y = y;
  1151. result.z = z;
  1152. result.w = w;
  1153. };
  1154. Vector4.Zero = function () {
  1155. return new Vector4(0, 0, 0, 0);
  1156. };
  1157. Vector4.Normalize = function (vector) {
  1158. var result = Vector4.Zero();
  1159. Vector4.NormalizeToRef(vector, result);
  1160. return result;
  1161. };
  1162. Vector4.NormalizeToRef = function (vector, result) {
  1163. result.copyFrom(vector);
  1164. result.normalize();
  1165. };
  1166. Vector4.Minimize = function (left, right) {
  1167. var min = left.clone();
  1168. min.MinimizeInPlace(right);
  1169. return min;
  1170. };
  1171. Vector4.Maximize = function (left, right) {
  1172. var max = left.clone();
  1173. max.MaximizeInPlace(right);
  1174. return max;
  1175. };
  1176. Vector4.Distance = function (value1, value2) {
  1177. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1178. };
  1179. Vector4.DistanceSquared = function (value1, value2) {
  1180. var x = value1.x - value2.x;
  1181. var y = value1.y - value2.y;
  1182. var z = value1.z - value2.z;
  1183. var w = value1.w - value2.w;
  1184. return (x * x) + (y * y) + (z * z) + (w * w);
  1185. };
  1186. Vector4.Center = function (value1, value2) {
  1187. var center = value1.add(value2);
  1188. center.scaleInPlace(0.5);
  1189. return center;
  1190. };
  1191. return Vector4;
  1192. })();
  1193. BABYLON.Vector4 = Vector4;
  1194. var Quaternion = (function () {
  1195. function Quaternion(x, y, z, w) {
  1196. if (x === void 0) { x = 0; }
  1197. if (y === void 0) { y = 0; }
  1198. if (z === void 0) { z = 0; }
  1199. if (w === void 0) { w = 1; }
  1200. this.x = x;
  1201. this.y = y;
  1202. this.z = z;
  1203. this.w = w;
  1204. }
  1205. Quaternion.prototype.toString = function () {
  1206. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1207. };
  1208. Quaternion.prototype.asArray = function () {
  1209. return [this.x, this.y, this.z, this.w];
  1210. };
  1211. Quaternion.prototype.equals = function (otherQuaternion) {
  1212. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1213. };
  1214. Quaternion.prototype.clone = function () {
  1215. return new Quaternion(this.x, this.y, this.z, this.w);
  1216. };
  1217. Quaternion.prototype.copyFrom = function (other) {
  1218. this.x = other.x;
  1219. this.y = other.y;
  1220. this.z = other.z;
  1221. this.w = other.w;
  1222. return this;
  1223. };
  1224. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1225. this.x = x;
  1226. this.y = y;
  1227. this.z = z;
  1228. this.w = w;
  1229. return this;
  1230. };
  1231. Quaternion.prototype.add = function (other) {
  1232. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1233. };
  1234. Quaternion.prototype.subtract = function (other) {
  1235. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1236. };
  1237. Quaternion.prototype.scale = function (value) {
  1238. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1239. };
  1240. Quaternion.prototype.multiply = function (q1) {
  1241. var result = new Quaternion(0, 0, 0, 1.0);
  1242. this.multiplyToRef(q1, result);
  1243. return result;
  1244. };
  1245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1250. result.copyFromFloats(x, y, z, w);
  1251. return this;
  1252. };
  1253. Quaternion.prototype.multiplyInPlace = function (q1) {
  1254. this.multiplyToRef(q1, this);
  1255. return this;
  1256. };
  1257. Quaternion.prototype.length = function () {
  1258. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1259. };
  1260. Quaternion.prototype.normalize = function () {
  1261. var length = 1.0 / this.length();
  1262. this.x *= length;
  1263. this.y *= length;
  1264. this.z *= length;
  1265. this.w *= length;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.toEulerAngles = function () {
  1269. var result = Vector3.Zero();
  1270. this.toEulerAnglesToRef(result);
  1271. return result;
  1272. };
  1273. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1274. //result is an EulerAngles in the in the z-x-z convention
  1275. var qx = this.x;
  1276. var qy = this.y;
  1277. var qz = this.z;
  1278. var qw = this.w;
  1279. var qxy = qx * qy;
  1280. var qxz = qx * qz;
  1281. var qwy = qw * qy;
  1282. var qwz = qw * qz;
  1283. var qwx = qw * qx;
  1284. var qyz = qy * qz;
  1285. var sqx = qx * qx;
  1286. var sqy = qy * qy;
  1287. var determinant = sqx + sqy;
  1288. if (determinant !== 0.000 && determinant !== 1.000) {
  1289. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1290. result.y = Math.acos(1 - 2 * determinant);
  1291. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1292. }
  1293. else {
  1294. if (determinant === 0.0) {
  1295. result.x = 0.0;
  1296. result.y = 0.0;
  1297. 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)
  1298. }
  1299. else {
  1300. 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)
  1301. result.y = Math.PI;
  1302. result.z = 0.0;
  1303. }
  1304. }
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toRotationMatrix = function (result) {
  1308. var xx = this.x * this.x;
  1309. var yy = this.y * this.y;
  1310. var zz = this.z * this.z;
  1311. var xy = this.x * this.y;
  1312. var zw = this.z * this.w;
  1313. var zx = this.z * this.x;
  1314. var yw = this.y * this.w;
  1315. var yz = this.y * this.z;
  1316. var xw = this.x * this.w;
  1317. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1318. result.m[1] = 2.0 * (xy + zw);
  1319. result.m[2] = 2.0 * (zx - yw);
  1320. result.m[3] = 0;
  1321. result.m[4] = 2.0 * (xy - zw);
  1322. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1323. result.m[6] = 2.0 * (yz + xw);
  1324. result.m[7] = 0;
  1325. result.m[8] = 2.0 * (zx + yw);
  1326. result.m[9] = 2.0 * (yz - xw);
  1327. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1328. result.m[11] = 0;
  1329. result.m[12] = 0;
  1330. result.m[13] = 0;
  1331. result.m[14] = 0;
  1332. result.m[15] = 1.0;
  1333. return this;
  1334. };
  1335. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1336. Quaternion.FromRotationMatrixToRef(matrix, this);
  1337. return this;
  1338. };
  1339. // Statics
  1340. Quaternion.FromRotationMatrix = function (matrix) {
  1341. var result = new Quaternion();
  1342. Quaternion.FromRotationMatrixToRef(matrix, result);
  1343. return result;
  1344. };
  1345. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1346. var data = matrix.m;
  1347. var m11 = data[0], m12 = data[4], m13 = data[8];
  1348. var m21 = data[1], m22 = data[5], m23 = data[9];
  1349. var m31 = data[2], m32 = data[6], m33 = data[10];
  1350. var trace = m11 + m22 + m33;
  1351. var s;
  1352. if (trace > 0) {
  1353. s = 0.5 / Math.sqrt(trace + 1.0);
  1354. result.w = 0.25 / s;
  1355. result.x = (m32 - m23) * s;
  1356. result.y = (m13 - m31) * s;
  1357. result.z = (m21 - m12) * s;
  1358. }
  1359. else if (m11 > m22 && m11 > m33) {
  1360. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1361. result.w = (m32 - m23) / s;
  1362. result.x = 0.25 * s;
  1363. result.y = (m12 + m21) / s;
  1364. result.z = (m13 + m31) / s;
  1365. }
  1366. else if (m22 > m33) {
  1367. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1368. result.w = (m13 - m31) / s;
  1369. result.x = (m12 + m21) / s;
  1370. result.y = 0.25 * s;
  1371. result.z = (m23 + m32) / s;
  1372. }
  1373. else {
  1374. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1375. result.w = (m21 - m12) / s;
  1376. result.x = (m13 + m31) / s;
  1377. result.y = (m23 + m32) / s;
  1378. result.z = 0.25 * s;
  1379. }
  1380. };
  1381. Quaternion.Inverse = function (q) {
  1382. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1383. };
  1384. Quaternion.Identity = function () {
  1385. return new Quaternion(0, 0, 0, 1);
  1386. };
  1387. Quaternion.RotationAxis = function (axis, angle) {
  1388. var result = new Quaternion();
  1389. var sin = Math.sin(angle / 2);
  1390. axis.normalize();
  1391. result.w = Math.cos(angle / 2);
  1392. result.x = axis.x * sin;
  1393. result.y = axis.y * sin;
  1394. result.z = axis.z * sin;
  1395. return result;
  1396. };
  1397. Quaternion.FromArray = function (array, offset) {
  1398. if (!offset) {
  1399. offset = 0;
  1400. }
  1401. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1402. };
  1403. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1404. var result = new Quaternion();
  1405. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1406. return result;
  1407. };
  1408. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1409. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1410. var halfRoll = roll * 0.5;
  1411. var halfPitch = pitch * 0.5;
  1412. var halfYaw = yaw * 0.5;
  1413. var sinRoll = Math.sin(halfRoll);
  1414. var cosRoll = Math.cos(halfRoll);
  1415. var sinPitch = Math.sin(halfPitch);
  1416. var cosPitch = Math.cos(halfPitch);
  1417. var sinYaw = Math.sin(halfYaw);
  1418. var cosYaw = Math.cos(halfYaw);
  1419. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1420. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1421. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1422. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1423. };
  1424. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1425. var result = new Quaternion();
  1426. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1427. return result;
  1428. };
  1429. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1430. // Produces a quaternion from Euler angles in the z-x-z orientation
  1431. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1432. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1433. var halfBeta = beta * 0.5;
  1434. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1435. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1436. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1437. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1438. };
  1439. Quaternion.Slerp = function (left, right, amount) {
  1440. var num2;
  1441. var num3;
  1442. var num = amount;
  1443. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1444. var flag = false;
  1445. if (num4 < 0) {
  1446. flag = true;
  1447. num4 = -num4;
  1448. }
  1449. if (num4 > 0.999999) {
  1450. num3 = 1 - num;
  1451. num2 = flag ? -num : num;
  1452. }
  1453. else {
  1454. var num5 = Math.acos(num4);
  1455. var num6 = (1.0 / Math.sin(num5));
  1456. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1457. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1458. }
  1459. 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));
  1460. };
  1461. return Quaternion;
  1462. })();
  1463. BABYLON.Quaternion = Quaternion;
  1464. var Matrix = (function () {
  1465. function Matrix() {
  1466. this.m = new Float32Array(16);
  1467. }
  1468. // Properties
  1469. Matrix.prototype.isIdentity = function () {
  1470. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1471. return false;
  1472. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1473. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1474. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1475. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1476. return false;
  1477. return true;
  1478. };
  1479. Matrix.prototype.determinant = function () {
  1480. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1481. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1482. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1483. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1484. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1485. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1486. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1487. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1488. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1489. };
  1490. // Methods
  1491. Matrix.prototype.toArray = function () {
  1492. return this.m;
  1493. };
  1494. Matrix.prototype.asArray = function () {
  1495. return this.toArray();
  1496. };
  1497. Matrix.prototype.invert = function () {
  1498. this.invertToRef(this);
  1499. return this;
  1500. };
  1501. Matrix.prototype.reset = function () {
  1502. for (var index = 0; index < 16; index++) {
  1503. this.m[index] = 0;
  1504. }
  1505. return this;
  1506. };
  1507. Matrix.prototype.add = function (other) {
  1508. var result = new Matrix();
  1509. this.addToRef(other, result);
  1510. return result;
  1511. };
  1512. Matrix.prototype.addToRef = function (other, result) {
  1513. for (var index = 0; index < 16; index++) {
  1514. result.m[index] = this.m[index] + other.m[index];
  1515. }
  1516. return this;
  1517. };
  1518. Matrix.prototype.addToSelf = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] += other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.invertToRef = function (other) {
  1525. var l1 = this.m[0];
  1526. var l2 = this.m[1];
  1527. var l3 = this.m[2];
  1528. var l4 = this.m[3];
  1529. var l5 = this.m[4];
  1530. var l6 = this.m[5];
  1531. var l7 = this.m[6];
  1532. var l8 = this.m[7];
  1533. var l9 = this.m[8];
  1534. var l10 = this.m[9];
  1535. var l11 = this.m[10];
  1536. var l12 = this.m[11];
  1537. var l13 = this.m[12];
  1538. var l14 = this.m[13];
  1539. var l15 = this.m[14];
  1540. var l16 = this.m[15];
  1541. var l17 = (l11 * l16) - (l12 * l15);
  1542. var l18 = (l10 * l16) - (l12 * l14);
  1543. var l19 = (l10 * l15) - (l11 * l14);
  1544. var l20 = (l9 * l16) - (l12 * l13);
  1545. var l21 = (l9 * l15) - (l11 * l13);
  1546. var l22 = (l9 * l14) - (l10 * l13);
  1547. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1548. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1549. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1550. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1551. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1552. var l28 = (l7 * l16) - (l8 * l15);
  1553. var l29 = (l6 * l16) - (l8 * l14);
  1554. var l30 = (l6 * l15) - (l7 * l14);
  1555. var l31 = (l5 * l16) - (l8 * l13);
  1556. var l32 = (l5 * l15) - (l7 * l13);
  1557. var l33 = (l5 * l14) - (l6 * l13);
  1558. var l34 = (l7 * l12) - (l8 * l11);
  1559. var l35 = (l6 * l12) - (l8 * l10);
  1560. var l36 = (l6 * l11) - (l7 * l10);
  1561. var l37 = (l5 * l12) - (l8 * l9);
  1562. var l38 = (l5 * l11) - (l7 * l9);
  1563. var l39 = (l5 * l10) - (l6 * l9);
  1564. other.m[0] = l23 * l27;
  1565. other.m[4] = l24 * l27;
  1566. other.m[8] = l25 * l27;
  1567. other.m[12] = l26 * l27;
  1568. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1569. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1570. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1571. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1572. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1573. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1574. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1575. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1576. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1577. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1578. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1579. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1580. return this;
  1581. };
  1582. Matrix.prototype.setTranslation = function (vector3) {
  1583. this.m[12] = vector3.x;
  1584. this.m[13] = vector3.y;
  1585. this.m[14] = vector3.z;
  1586. return this;
  1587. };
  1588. Matrix.prototype.multiply = function (other) {
  1589. var result = new Matrix();
  1590. this.multiplyToRef(other, result);
  1591. return result;
  1592. };
  1593. Matrix.prototype.copyFrom = function (other) {
  1594. for (var index = 0; index < 16; index++) {
  1595. this.m[index] = other.m[index];
  1596. }
  1597. return this;
  1598. };
  1599. Matrix.prototype.copyToArray = function (array, offset) {
  1600. if (offset === void 0) { offset = 0; }
  1601. for (var index = 0; index < 16; index++) {
  1602. array[offset + index] = this.m[index];
  1603. }
  1604. return this;
  1605. };
  1606. Matrix.prototype.multiplyToRef = function (other, result) {
  1607. this.multiplyToArray(other, result.m, 0);
  1608. return this;
  1609. };
  1610. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1611. var tm0 = this.m[0];
  1612. var tm1 = this.m[1];
  1613. var tm2 = this.m[2];
  1614. var tm3 = this.m[3];
  1615. var tm4 = this.m[4];
  1616. var tm5 = this.m[5];
  1617. var tm6 = this.m[6];
  1618. var tm7 = this.m[7];
  1619. var tm8 = this.m[8];
  1620. var tm9 = this.m[9];
  1621. var tm10 = this.m[10];
  1622. var tm11 = this.m[11];
  1623. var tm12 = this.m[12];
  1624. var tm13 = this.m[13];
  1625. var tm14 = this.m[14];
  1626. var tm15 = this.m[15];
  1627. var om0 = other.m[0];
  1628. var om1 = other.m[1];
  1629. var om2 = other.m[2];
  1630. var om3 = other.m[3];
  1631. var om4 = other.m[4];
  1632. var om5 = other.m[5];
  1633. var om6 = other.m[6];
  1634. var om7 = other.m[7];
  1635. var om8 = other.m[8];
  1636. var om9 = other.m[9];
  1637. var om10 = other.m[10];
  1638. var om11 = other.m[11];
  1639. var om12 = other.m[12];
  1640. var om13 = other.m[13];
  1641. var om14 = other.m[14];
  1642. var om15 = other.m[15];
  1643. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1644. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1645. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1646. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1647. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1648. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1649. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1650. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1651. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1652. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1653. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1654. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1655. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1656. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1657. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1658. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1659. return this;
  1660. };
  1661. Matrix.prototype.equals = function (value) {
  1662. return value &&
  1663. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1664. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1665. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1666. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1667. };
  1668. Matrix.prototype.clone = function () {
  1669. 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]);
  1670. };
  1671. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1672. translation.x = this.m[12];
  1673. translation.y = this.m[13];
  1674. translation.z = this.m[14];
  1675. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1676. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1677. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1678. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1679. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1680. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1681. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1682. rotation.x = 0;
  1683. rotation.y = 0;
  1684. rotation.z = 0;
  1685. rotation.w = 1;
  1686. return false;
  1687. }
  1688. 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);
  1689. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1690. return true;
  1691. };
  1692. // Statics
  1693. Matrix.FromArray = function (array, offset) {
  1694. var result = new Matrix();
  1695. if (!offset) {
  1696. offset = 0;
  1697. }
  1698. Matrix.FromArrayToRef(array, offset, result);
  1699. return result;
  1700. };
  1701. Matrix.FromArrayToRef = function (array, offset, result) {
  1702. for (var index = 0; index < 16; index++) {
  1703. result.m[index] = array[index + offset];
  1704. }
  1705. };
  1706. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1707. for (var index = 0; index < 16; index++) {
  1708. result.m[index] = array[index + offset] * scale;
  1709. }
  1710. };
  1711. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1712. result.m[0] = initialM11;
  1713. result.m[1] = initialM12;
  1714. result.m[2] = initialM13;
  1715. result.m[3] = initialM14;
  1716. result.m[4] = initialM21;
  1717. result.m[5] = initialM22;
  1718. result.m[6] = initialM23;
  1719. result.m[7] = initialM24;
  1720. result.m[8] = initialM31;
  1721. result.m[9] = initialM32;
  1722. result.m[10] = initialM33;
  1723. result.m[11] = initialM34;
  1724. result.m[12] = initialM41;
  1725. result.m[13] = initialM42;
  1726. result.m[14] = initialM43;
  1727. result.m[15] = initialM44;
  1728. };
  1729. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1730. var result = new Matrix();
  1731. result.m[0] = initialM11;
  1732. result.m[1] = initialM12;
  1733. result.m[2] = initialM13;
  1734. result.m[3] = initialM14;
  1735. result.m[4] = initialM21;
  1736. result.m[5] = initialM22;
  1737. result.m[6] = initialM23;
  1738. result.m[7] = initialM24;
  1739. result.m[8] = initialM31;
  1740. result.m[9] = initialM32;
  1741. result.m[10] = initialM33;
  1742. result.m[11] = initialM34;
  1743. result.m[12] = initialM41;
  1744. result.m[13] = initialM42;
  1745. result.m[14] = initialM43;
  1746. result.m[15] = initialM44;
  1747. return result;
  1748. };
  1749. Matrix.Compose = function (scale, rotation, translation) {
  1750. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1751. var rotationMatrix = Matrix.Identity();
  1752. rotation.toRotationMatrix(rotationMatrix);
  1753. result = result.multiply(rotationMatrix);
  1754. result.setTranslation(translation);
  1755. return result;
  1756. };
  1757. Matrix.Identity = function () {
  1758. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1759. };
  1760. Matrix.IdentityToRef = function (result) {
  1761. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1762. };
  1763. Matrix.Zero = function () {
  1764. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1765. };
  1766. Matrix.RotationX = function (angle) {
  1767. var result = new Matrix();
  1768. Matrix.RotationXToRef(angle, result);
  1769. return result;
  1770. };
  1771. Matrix.Invert = function (source) {
  1772. var result = new Matrix();
  1773. source.invertToRef(result);
  1774. return result;
  1775. };
  1776. Matrix.RotationXToRef = function (angle, result) {
  1777. var s = Math.sin(angle);
  1778. var c = Math.cos(angle);
  1779. result.m[0] = 1.0;
  1780. result.m[15] = 1.0;
  1781. result.m[5] = c;
  1782. result.m[10] = c;
  1783. result.m[9] = -s;
  1784. result.m[6] = s;
  1785. result.m[1] = 0;
  1786. result.m[2] = 0;
  1787. result.m[3] = 0;
  1788. result.m[4] = 0;
  1789. result.m[7] = 0;
  1790. result.m[8] = 0;
  1791. result.m[11] = 0;
  1792. result.m[12] = 0;
  1793. result.m[13] = 0;
  1794. result.m[14] = 0;
  1795. };
  1796. Matrix.RotationY = function (angle) {
  1797. var result = new Matrix();
  1798. Matrix.RotationYToRef(angle, result);
  1799. return result;
  1800. };
  1801. Matrix.RotationYToRef = function (angle, result) {
  1802. var s = Math.sin(angle);
  1803. var c = Math.cos(angle);
  1804. result.m[5] = 1.0;
  1805. result.m[15] = 1.0;
  1806. result.m[0] = c;
  1807. result.m[2] = -s;
  1808. result.m[8] = s;
  1809. result.m[10] = c;
  1810. result.m[1] = 0;
  1811. result.m[3] = 0;
  1812. result.m[4] = 0;
  1813. result.m[6] = 0;
  1814. result.m[7] = 0;
  1815. result.m[9] = 0;
  1816. result.m[11] = 0;
  1817. result.m[12] = 0;
  1818. result.m[13] = 0;
  1819. result.m[14] = 0;
  1820. };
  1821. Matrix.RotationZ = function (angle) {
  1822. var result = new Matrix();
  1823. Matrix.RotationZToRef(angle, result);
  1824. return result;
  1825. };
  1826. Matrix.RotationZToRef = function (angle, result) {
  1827. var s = Math.sin(angle);
  1828. var c = Math.cos(angle);
  1829. result.m[10] = 1.0;
  1830. result.m[15] = 1.0;
  1831. result.m[0] = c;
  1832. result.m[1] = s;
  1833. result.m[4] = -s;
  1834. result.m[5] = c;
  1835. result.m[2] = 0;
  1836. result.m[3] = 0;
  1837. result.m[6] = 0;
  1838. result.m[7] = 0;
  1839. result.m[8] = 0;
  1840. result.m[9] = 0;
  1841. result.m[11] = 0;
  1842. result.m[12] = 0;
  1843. result.m[13] = 0;
  1844. result.m[14] = 0;
  1845. };
  1846. Matrix.RotationAxis = function (axis, angle) {
  1847. var result = Matrix.Zero();
  1848. Matrix.RotationAxisToRef(axis, angle, result);
  1849. return result;
  1850. };
  1851. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1852. var s = Math.sin(-angle);
  1853. var c = Math.cos(-angle);
  1854. var c1 = 1 - c;
  1855. axis.normalize();
  1856. result.m[0] = (axis.x * axis.x) * c1 + c;
  1857. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1858. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1859. result.m[3] = 0.0;
  1860. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1861. result.m[5] = (axis.y * axis.y) * c1 + c;
  1862. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1863. result.m[7] = 0.0;
  1864. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1865. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1866. result.m[10] = (axis.z * axis.z) * c1 + c;
  1867. result.m[11] = 0.0;
  1868. result.m[15] = 1.0;
  1869. };
  1870. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1871. var result = new Matrix();
  1872. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1876. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1877. this._tempQuaternion.toRotationMatrix(result);
  1878. };
  1879. Matrix.Scaling = function (x, y, z) {
  1880. var result = Matrix.Zero();
  1881. Matrix.ScalingToRef(x, y, z, result);
  1882. return result;
  1883. };
  1884. Matrix.ScalingToRef = function (x, y, z, result) {
  1885. result.m[0] = x;
  1886. result.m[1] = 0;
  1887. result.m[2] = 0;
  1888. result.m[3] = 0;
  1889. result.m[4] = 0;
  1890. result.m[5] = y;
  1891. result.m[6] = 0;
  1892. result.m[7] = 0;
  1893. result.m[8] = 0;
  1894. result.m[9] = 0;
  1895. result.m[10] = z;
  1896. result.m[11] = 0;
  1897. result.m[12] = 0;
  1898. result.m[13] = 0;
  1899. result.m[14] = 0;
  1900. result.m[15] = 1.0;
  1901. };
  1902. Matrix.Translation = function (x, y, z) {
  1903. var result = Matrix.Identity();
  1904. Matrix.TranslationToRef(x, y, z, result);
  1905. return result;
  1906. };
  1907. Matrix.TranslationToRef = function (x, y, z, result) {
  1908. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1909. };
  1910. Matrix.LookAtLH = function (eye, target, up) {
  1911. var result = Matrix.Zero();
  1912. Matrix.LookAtLHToRef(eye, target, up, result);
  1913. return result;
  1914. };
  1915. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1916. // Z axis
  1917. target.subtractToRef(eye, this._zAxis);
  1918. this._zAxis.normalize();
  1919. // X axis
  1920. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1921. if (this._xAxis.lengthSquared() === 0) {
  1922. this._xAxis.x = 1.0;
  1923. }
  1924. else {
  1925. this._xAxis.normalize();
  1926. }
  1927. // Y axis
  1928. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1929. this._yAxis.normalize();
  1930. // Eye angles
  1931. var ex = -Vector3.Dot(this._xAxis, eye);
  1932. var ey = -Vector3.Dot(this._yAxis, eye);
  1933. var ez = -Vector3.Dot(this._zAxis, eye);
  1934. 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);
  1935. };
  1936. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1937. var matrix = Matrix.Zero();
  1938. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1939. return matrix;
  1940. };
  1941. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1942. var hw = 2.0 / width;
  1943. var hh = 2.0 / height;
  1944. var id = 1.0 / (zfar - znear);
  1945. var nid = znear / (znear - zfar);
  1946. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1947. };
  1948. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1949. var matrix = Matrix.Zero();
  1950. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1951. return matrix;
  1952. };
  1953. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1954. result.m[0] = 2.0 / (right - left);
  1955. result.m[1] = result.m[2] = result.m[3] = 0;
  1956. result.m[5] = 2.0 / (top - bottom);
  1957. result.m[4] = result.m[6] = result.m[7] = 0;
  1958. result.m[10] = -1.0 / (znear - zfar);
  1959. result.m[8] = result.m[9] = result.m[11] = 0;
  1960. result.m[12] = (left + right) / (left - right);
  1961. result.m[13] = (top + bottom) / (bottom - top);
  1962. result.m[14] = znear / (znear - zfar);
  1963. result.m[15] = 1.0;
  1964. };
  1965. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1966. var matrix = Matrix.Zero();
  1967. matrix.m[0] = (2.0 * znear) / width;
  1968. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1969. matrix.m[5] = (2.0 * znear) / height;
  1970. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1971. matrix.m[10] = -zfar / (znear - zfar);
  1972. matrix.m[8] = matrix.m[9] = 0.0;
  1973. matrix.m[11] = 1.0;
  1974. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1975. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1976. return matrix;
  1977. };
  1978. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1979. var matrix = Matrix.Zero();
  1980. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1981. return matrix;
  1982. };
  1983. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1984. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1985. var tan = 1.0 / (Math.tan(fov * 0.5));
  1986. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1987. if (v_fixed) {
  1988. result.m[0] = tan / aspect;
  1989. }
  1990. else {
  1991. result.m[0] = tan;
  1992. }
  1993. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1994. if (v_fixed) {
  1995. result.m[5] = tan;
  1996. }
  1997. else {
  1998. result.m[5] = tan * aspect;
  1999. }
  2000. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2001. result.m[8] = result.m[9] = 0.0;
  2002. result.m[10] = -zfar / (znear - zfar);
  2003. result.m[11] = 1.0;
  2004. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2005. result.m[14] = (znear * zfar) / (znear - zfar);
  2006. };
  2007. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2008. var cw = viewport.width;
  2009. var ch = viewport.height;
  2010. var cx = viewport.x;
  2011. var cy = viewport.y;
  2012. 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);
  2013. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2014. };
  2015. Matrix.GetAsMatrix2x2 = function (matrix) {
  2016. return new Float32Array([
  2017. matrix.m[0], matrix.m[1],
  2018. matrix.m[4], matrix.m[5]
  2019. ]);
  2020. };
  2021. Matrix.GetAsMatrix3x3 = function (matrix) {
  2022. return new Float32Array([
  2023. matrix.m[0], matrix.m[1], matrix.m[2],
  2024. matrix.m[4], matrix.m[5], matrix.m[6],
  2025. matrix.m[8], matrix.m[9], matrix.m[10]
  2026. ]);
  2027. };
  2028. Matrix.Transpose = function (matrix) {
  2029. var result = new Matrix();
  2030. result.m[0] = matrix.m[0];
  2031. result.m[1] = matrix.m[4];
  2032. result.m[2] = matrix.m[8];
  2033. result.m[3] = matrix.m[12];
  2034. result.m[4] = matrix.m[1];
  2035. result.m[5] = matrix.m[5];
  2036. result.m[6] = matrix.m[9];
  2037. result.m[7] = matrix.m[13];
  2038. result.m[8] = matrix.m[2];
  2039. result.m[9] = matrix.m[6];
  2040. result.m[10] = matrix.m[10];
  2041. result.m[11] = matrix.m[14];
  2042. result.m[12] = matrix.m[3];
  2043. result.m[13] = matrix.m[7];
  2044. result.m[14] = matrix.m[11];
  2045. result.m[15] = matrix.m[15];
  2046. return result;
  2047. };
  2048. Matrix.Reflection = function (plane) {
  2049. var matrix = new Matrix();
  2050. Matrix.ReflectionToRef(plane, matrix);
  2051. return matrix;
  2052. };
  2053. Matrix.ReflectionToRef = function (plane, result) {
  2054. plane.normalize();
  2055. var x = plane.normal.x;
  2056. var y = plane.normal.y;
  2057. var z = plane.normal.z;
  2058. var temp = -2 * x;
  2059. var temp2 = -2 * y;
  2060. var temp3 = -2 * z;
  2061. result.m[0] = (temp * x) + 1;
  2062. result.m[1] = temp2 * x;
  2063. result.m[2] = temp3 * x;
  2064. result.m[3] = 0.0;
  2065. result.m[4] = temp * y;
  2066. result.m[5] = (temp2 * y) + 1;
  2067. result.m[6] = temp3 * y;
  2068. result.m[7] = 0.0;
  2069. result.m[8] = temp * z;
  2070. result.m[9] = temp2 * z;
  2071. result.m[10] = (temp3 * z) + 1;
  2072. result.m[11] = 0.0;
  2073. result.m[12] = temp * plane.d;
  2074. result.m[13] = temp2 * plane.d;
  2075. result.m[14] = temp3 * plane.d;
  2076. result.m[15] = 1.0;
  2077. };
  2078. Matrix._tempQuaternion = new Quaternion();
  2079. Matrix._xAxis = Vector3.Zero();
  2080. Matrix._yAxis = Vector3.Zero();
  2081. Matrix._zAxis = Vector3.Zero();
  2082. return Matrix;
  2083. })();
  2084. BABYLON.Matrix = Matrix;
  2085. var Plane = (function () {
  2086. function Plane(a, b, c, d) {
  2087. this.normal = new Vector3(a, b, c);
  2088. this.d = d;
  2089. }
  2090. Plane.prototype.asArray = function () {
  2091. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2092. };
  2093. // Methods
  2094. Plane.prototype.clone = function () {
  2095. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2096. };
  2097. Plane.prototype.normalize = function () {
  2098. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2099. var magnitude = 0;
  2100. if (norm !== 0) {
  2101. magnitude = 1.0 / norm;
  2102. }
  2103. this.normal.x *= magnitude;
  2104. this.normal.y *= magnitude;
  2105. this.normal.z *= magnitude;
  2106. this.d *= magnitude;
  2107. return this;
  2108. };
  2109. Plane.prototype.transform = function (transformation) {
  2110. var transposedMatrix = Matrix.Transpose(transformation);
  2111. var x = this.normal.x;
  2112. var y = this.normal.y;
  2113. var z = this.normal.z;
  2114. var d = this.d;
  2115. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2116. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2117. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2118. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2119. return new Plane(normalX, normalY, normalZ, finalD);
  2120. };
  2121. Plane.prototype.dotCoordinate = function (point) {
  2122. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2123. };
  2124. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2125. var x1 = point2.x - point1.x;
  2126. var y1 = point2.y - point1.y;
  2127. var z1 = point2.z - point1.z;
  2128. var x2 = point3.x - point1.x;
  2129. var y2 = point3.y - point1.y;
  2130. var z2 = point3.z - point1.z;
  2131. var yz = (y1 * z2) - (z1 * y2);
  2132. var xz = (z1 * x2) - (x1 * z2);
  2133. var xy = (x1 * y2) - (y1 * x2);
  2134. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2135. var invPyth;
  2136. if (pyth !== 0) {
  2137. invPyth = 1.0 / pyth;
  2138. }
  2139. else {
  2140. invPyth = 0;
  2141. }
  2142. this.normal.x = yz * invPyth;
  2143. this.normal.y = xz * invPyth;
  2144. this.normal.z = xy * invPyth;
  2145. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2146. return this;
  2147. };
  2148. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2149. var dot = Vector3.Dot(this.normal, direction);
  2150. return (dot <= epsilon);
  2151. };
  2152. Plane.prototype.signedDistanceTo = function (point) {
  2153. return Vector3.Dot(point, this.normal) + this.d;
  2154. };
  2155. // Statics
  2156. Plane.FromArray = function (array) {
  2157. return new Plane(array[0], array[1], array[2], array[3]);
  2158. };
  2159. Plane.FromPoints = function (point1, point2, point3) {
  2160. var result = new Plane(0, 0, 0, 0);
  2161. result.copyFromPoints(point1, point2, point3);
  2162. return result;
  2163. };
  2164. Plane.FromPositionAndNormal = function (origin, normal) {
  2165. var result = new Plane(0, 0, 0, 0);
  2166. normal.normalize();
  2167. result.normal = normal;
  2168. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2169. return result;
  2170. };
  2171. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2172. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2173. return Vector3.Dot(point, normal) + d;
  2174. };
  2175. return Plane;
  2176. })();
  2177. BABYLON.Plane = Plane;
  2178. var Viewport = (function () {
  2179. function Viewport(x, y, width, height) {
  2180. this.x = x;
  2181. this.y = y;
  2182. this.width = width;
  2183. this.height = height;
  2184. }
  2185. Viewport.prototype.toGlobal = function (engine) {
  2186. var width = engine.getRenderWidth();
  2187. var height = engine.getRenderHeight();
  2188. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2189. };
  2190. return Viewport;
  2191. })();
  2192. BABYLON.Viewport = Viewport;
  2193. var Frustum = (function () {
  2194. function Frustum() {
  2195. }
  2196. Frustum.GetPlanes = function (transform) {
  2197. var frustumPlanes = [];
  2198. for (var index = 0; index < 6; index++) {
  2199. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2200. }
  2201. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2202. return frustumPlanes;
  2203. };
  2204. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2205. // Near
  2206. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2207. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2208. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2209. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2210. frustumPlanes[0].normalize();
  2211. // Far
  2212. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2213. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2214. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2215. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2216. frustumPlanes[1].normalize();
  2217. // Left
  2218. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2219. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2220. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2221. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2222. frustumPlanes[2].normalize();
  2223. // Right
  2224. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2225. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2226. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2227. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2228. frustumPlanes[3].normalize();
  2229. // Top
  2230. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2231. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2232. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2233. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2234. frustumPlanes[4].normalize();
  2235. // Bottom
  2236. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2237. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2238. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2239. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2240. frustumPlanes[5].normalize();
  2241. };
  2242. return Frustum;
  2243. })();
  2244. BABYLON.Frustum = Frustum;
  2245. var Ray = (function () {
  2246. function Ray(origin, direction, length) {
  2247. if (length === void 0) { length = Number.MAX_VALUE; }
  2248. this.origin = origin;
  2249. this.direction = direction;
  2250. this.length = length;
  2251. }
  2252. // Methods
  2253. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2254. var d = 0.0;
  2255. var maxValue = Number.MAX_VALUE;
  2256. var inv;
  2257. var min;
  2258. var max;
  2259. var temp;
  2260. if (Math.abs(this.direction.x) < 0.0000001) {
  2261. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2262. return false;
  2263. }
  2264. }
  2265. else {
  2266. inv = 1.0 / this.direction.x;
  2267. min = (minimum.x - this.origin.x) * inv;
  2268. max = (maximum.x - this.origin.x) * inv;
  2269. if (max === -Infinity) {
  2270. max = Infinity;
  2271. }
  2272. if (min > max) {
  2273. temp = min;
  2274. min = max;
  2275. max = temp;
  2276. }
  2277. d = Math.max(min, d);
  2278. maxValue = Math.min(max, maxValue);
  2279. if (d > maxValue) {
  2280. return false;
  2281. }
  2282. }
  2283. if (Math.abs(this.direction.y) < 0.0000001) {
  2284. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2285. return false;
  2286. }
  2287. }
  2288. else {
  2289. inv = 1.0 / this.direction.y;
  2290. min = (minimum.y - this.origin.y) * inv;
  2291. max = (maximum.y - this.origin.y) * inv;
  2292. if (max === -Infinity) {
  2293. max = Infinity;
  2294. }
  2295. if (min > max) {
  2296. temp = min;
  2297. min = max;
  2298. max = temp;
  2299. }
  2300. d = Math.max(min, d);
  2301. maxValue = Math.min(max, maxValue);
  2302. if (d > maxValue) {
  2303. return false;
  2304. }
  2305. }
  2306. if (Math.abs(this.direction.z) < 0.0000001) {
  2307. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2308. return false;
  2309. }
  2310. }
  2311. else {
  2312. inv = 1.0 / this.direction.z;
  2313. min = (minimum.z - this.origin.z) * inv;
  2314. max = (maximum.z - this.origin.z) * inv;
  2315. if (max === -Infinity) {
  2316. max = Infinity;
  2317. }
  2318. if (min > max) {
  2319. temp = min;
  2320. min = max;
  2321. max = temp;
  2322. }
  2323. d = Math.max(min, d);
  2324. maxValue = Math.min(max, maxValue);
  2325. if (d > maxValue) {
  2326. return false;
  2327. }
  2328. }
  2329. return true;
  2330. };
  2331. Ray.prototype.intersectsBox = function (box) {
  2332. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2333. };
  2334. Ray.prototype.intersectsSphere = function (sphere) {
  2335. var x = sphere.center.x - this.origin.x;
  2336. var y = sphere.center.y - this.origin.y;
  2337. var z = sphere.center.z - this.origin.z;
  2338. var pyth = (x * x) + (y * y) + (z * z);
  2339. var rr = sphere.radius * sphere.radius;
  2340. if (pyth <= rr) {
  2341. return true;
  2342. }
  2343. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2344. if (dot < 0.0) {
  2345. return false;
  2346. }
  2347. var temp = pyth - (dot * dot);
  2348. return temp <= rr;
  2349. };
  2350. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2351. if (!this._edge1) {
  2352. this._edge1 = Vector3.Zero();
  2353. this._edge2 = Vector3.Zero();
  2354. this._pvec = Vector3.Zero();
  2355. this._tvec = Vector3.Zero();
  2356. this._qvec = Vector3.Zero();
  2357. }
  2358. vertex1.subtractToRef(vertex0, this._edge1);
  2359. vertex2.subtractToRef(vertex0, this._edge2);
  2360. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2361. var det = Vector3.Dot(this._edge1, this._pvec);
  2362. if (det === 0) {
  2363. return null;
  2364. }
  2365. var invdet = 1 / det;
  2366. this.origin.subtractToRef(vertex0, this._tvec);
  2367. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2368. if (bu < 0 || bu > 1.0) {
  2369. return null;
  2370. }
  2371. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2372. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2373. if (bv < 0 || bu + bv > 1.0) {
  2374. return null;
  2375. }
  2376. //check if the distance is longer than the predefined length.
  2377. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2378. if (distance > this.length) {
  2379. return null;
  2380. }
  2381. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2382. };
  2383. // Statics
  2384. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2385. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2386. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2387. var direction = end.subtract(start);
  2388. direction.normalize();
  2389. return new Ray(start, direction);
  2390. };
  2391. /**
  2392. * 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
  2393. * transformed to the given world matrix.
  2394. * @param origin The origin point
  2395. * @param end The end point
  2396. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2397. */
  2398. Ray.CreateNewFromTo = function (origin, end, world) {
  2399. if (world === void 0) { world = Matrix.Identity(); }
  2400. var direction = end.subtract(origin);
  2401. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2402. direction.normalize();
  2403. return Ray.Transform(new Ray(origin, direction, length), world);
  2404. };
  2405. Ray.Transform = function (ray, matrix) {
  2406. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2407. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2408. return new Ray(newOrigin, newDirection, ray.length);
  2409. };
  2410. return Ray;
  2411. })();
  2412. BABYLON.Ray = Ray;
  2413. (function (Space) {
  2414. Space[Space["LOCAL"] = 0] = "LOCAL";
  2415. Space[Space["WORLD"] = 1] = "WORLD";
  2416. })(BABYLON.Space || (BABYLON.Space = {}));
  2417. var Space = BABYLON.Space;
  2418. var Axis = (function () {
  2419. function Axis() {
  2420. }
  2421. Axis.X = new Vector3(1, 0, 0);
  2422. Axis.Y = new Vector3(0, 1, 0);
  2423. Axis.Z = new Vector3(0, 0, 1);
  2424. return Axis;
  2425. })();
  2426. BABYLON.Axis = Axis;
  2427. ;
  2428. var BezierCurve = (function () {
  2429. function BezierCurve() {
  2430. }
  2431. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2432. // Extract X (which is equal to time here)
  2433. var f0 = 1 - 3 * x2 + 3 * x1;
  2434. var f1 = 3 * x2 - 6 * x1;
  2435. var f2 = 3 * x1;
  2436. var refinedT = t;
  2437. for (var i = 0; i < 5; i++) {
  2438. var refinedT2 = refinedT * refinedT;
  2439. var refinedT3 = refinedT2 * refinedT;
  2440. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2441. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2442. refinedT -= (x - t) * slope;
  2443. refinedT = Math.min(1, Math.max(0, refinedT));
  2444. }
  2445. // Resolve cubic bezier for the given x
  2446. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2447. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2448. Math.pow(refinedT, 3);
  2449. };
  2450. return BezierCurve;
  2451. })();
  2452. BABYLON.BezierCurve = BezierCurve;
  2453. (function (Orientation) {
  2454. Orientation[Orientation["CW"] = 0] = "CW";
  2455. Orientation[Orientation["CCW"] = 1] = "CCW";
  2456. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2457. var Orientation = BABYLON.Orientation;
  2458. var Angle = (function () {
  2459. function Angle(radians) {
  2460. var _this = this;
  2461. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2462. this.radians = function () { return _this._radians; };
  2463. this._radians = radians;
  2464. if (this._radians < 0)
  2465. this._radians += (2 * Math.PI);
  2466. }
  2467. Angle.BetweenTwoPoints = function (a, b) {
  2468. var delta = b.subtract(a);
  2469. var theta = Math.atan2(delta.y, delta.x);
  2470. return new Angle(theta);
  2471. };
  2472. Angle.FromRadians = function (radians) {
  2473. return new Angle(radians);
  2474. };
  2475. Angle.FromDegrees = function (degrees) {
  2476. return new Angle(degrees * Math.PI / 180);
  2477. };
  2478. return Angle;
  2479. })();
  2480. BABYLON.Angle = Angle;
  2481. var Arc2 = (function () {
  2482. function Arc2(startPoint, midPoint, endPoint) {
  2483. this.startPoint = startPoint;
  2484. this.midPoint = midPoint;
  2485. this.endPoint = endPoint;
  2486. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2487. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2488. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2489. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2490. 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);
  2491. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2492. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2493. var a1 = this.startAngle.degrees();
  2494. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2495. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2496. // angles correction
  2497. if (a2 - a1 > +180.0)
  2498. a2 -= 360.0;
  2499. if (a2 - a1 < -180.0)
  2500. a2 += 360.0;
  2501. if (a3 - a2 > +180.0)
  2502. a3 -= 360.0;
  2503. if (a3 - a2 < -180.0)
  2504. a3 += 360.0;
  2505. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2506. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2507. }
  2508. return Arc2;
  2509. })();
  2510. BABYLON.Arc2 = Arc2;
  2511. var PathCursor = (function () {
  2512. function PathCursor(path) {
  2513. this.path = path;
  2514. this._onchange = new Array();
  2515. this.value = 0;
  2516. this.animations = new Array();
  2517. }
  2518. PathCursor.prototype.getPoint = function () {
  2519. var point = this.path.getPointAtLengthPosition(this.value);
  2520. return new Vector3(point.x, 0, point.y);
  2521. };
  2522. PathCursor.prototype.moveAhead = function (step) {
  2523. if (step === void 0) { step = 0.002; }
  2524. this.move(step);
  2525. return this;
  2526. };
  2527. PathCursor.prototype.moveBack = function (step) {
  2528. if (step === void 0) { step = 0.002; }
  2529. this.move(-step);
  2530. return this;
  2531. };
  2532. PathCursor.prototype.move = function (step) {
  2533. if (Math.abs(step) > 1) {
  2534. throw "step size should be less than 1.";
  2535. }
  2536. this.value += step;
  2537. this.ensureLimits();
  2538. this.raiseOnChange();
  2539. return this;
  2540. };
  2541. PathCursor.prototype.ensureLimits = function () {
  2542. while (this.value > 1) {
  2543. this.value -= 1;
  2544. }
  2545. while (this.value < 0) {
  2546. this.value += 1;
  2547. }
  2548. return this;
  2549. };
  2550. // used by animation engine
  2551. PathCursor.prototype.markAsDirty = function (propertyName) {
  2552. this.ensureLimits();
  2553. this.raiseOnChange();
  2554. return this;
  2555. };
  2556. PathCursor.prototype.raiseOnChange = function () {
  2557. var _this = this;
  2558. this._onchange.forEach(function (f) { return f(_this); });
  2559. return this;
  2560. };
  2561. PathCursor.prototype.onchange = function (f) {
  2562. this._onchange.push(f);
  2563. return this;
  2564. };
  2565. return PathCursor;
  2566. })();
  2567. BABYLON.PathCursor = PathCursor;
  2568. var Path2 = (function () {
  2569. function Path2(x, y) {
  2570. this._points = new Array();
  2571. this._length = 0;
  2572. this.closed = false;
  2573. this._points.push(new Vector2(x, y));
  2574. }
  2575. Path2.prototype.addLineTo = function (x, y) {
  2576. if (closed) {
  2577. BABYLON.Tools.Error("cannot add lines to closed paths");
  2578. return this;
  2579. }
  2580. var newPoint = new Vector2(x, y);
  2581. var previousPoint = this._points[this._points.length - 1];
  2582. this._points.push(newPoint);
  2583. this._length += newPoint.subtract(previousPoint).length();
  2584. return this;
  2585. };
  2586. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2587. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2588. if (closed) {
  2589. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2590. return this;
  2591. }
  2592. var startPoint = this._points[this._points.length - 1];
  2593. var midPoint = new Vector2(midX, midY);
  2594. var endPoint = new Vector2(endX, endY);
  2595. var arc = new Arc2(startPoint, midPoint, endPoint);
  2596. var increment = arc.angle.radians() / numberOfSegments;
  2597. if (arc.orientation === Orientation.CW)
  2598. increment *= -1;
  2599. var currentAngle = arc.startAngle.radians() + increment;
  2600. for (var i = 0; i < numberOfSegments; i++) {
  2601. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2602. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2603. this.addLineTo(x, y);
  2604. currentAngle += increment;
  2605. }
  2606. return this;
  2607. };
  2608. Path2.prototype.close = function () {
  2609. this.closed = true;
  2610. return this;
  2611. };
  2612. Path2.prototype.length = function () {
  2613. var result = this._length;
  2614. if (!this.closed) {
  2615. var lastPoint = this._points[this._points.length - 1];
  2616. var firstPoint = this._points[0];
  2617. result += (firstPoint.subtract(lastPoint).length());
  2618. }
  2619. return result;
  2620. };
  2621. Path2.prototype.getPoints = function () {
  2622. return this._points;
  2623. };
  2624. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2625. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2626. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2627. return Vector2.Zero();
  2628. }
  2629. var lengthPosition = normalizedLengthPosition * this.length();
  2630. var previousOffset = 0;
  2631. for (var i = 0; i < this._points.length; i++) {
  2632. var j = (i + 1) % this._points.length;
  2633. var a = this._points[i];
  2634. var b = this._points[j];
  2635. var bToA = b.subtract(a);
  2636. var nextOffset = (bToA.length() + previousOffset);
  2637. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2638. var dir = bToA.normalize();
  2639. var localOffset = lengthPosition - previousOffset;
  2640. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2641. }
  2642. previousOffset = nextOffset;
  2643. }
  2644. BABYLON.Tools.Error("internal error");
  2645. return Vector2.Zero();
  2646. };
  2647. Path2.StartingAt = function (x, y) {
  2648. return new Path2(x, y);
  2649. };
  2650. return Path2;
  2651. })();
  2652. BABYLON.Path2 = Path2;
  2653. var Path3D = (function () {
  2654. /**
  2655. * new Path3D(path, normal, raw)
  2656. * path : an array of Vector3, the curve axis of the Path3D
  2657. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2658. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2659. */
  2660. function Path3D(path, firstNormal, raw) {
  2661. this.path = path;
  2662. this._curve = new Array();
  2663. this._distances = new Array();
  2664. this._tangents = new Array();
  2665. this._normals = new Array();
  2666. this._binormals = new Array();
  2667. for (var p = 0; p < path.length; p++) {
  2668. this._curve[p] = path[p].clone(); // hard copy
  2669. }
  2670. this._raw = raw || false;
  2671. this._compute(firstNormal);
  2672. }
  2673. Path3D.prototype.getCurve = function () {
  2674. return this._curve;
  2675. };
  2676. Path3D.prototype.getTangents = function () {
  2677. return this._tangents;
  2678. };
  2679. Path3D.prototype.getNormals = function () {
  2680. return this._normals;
  2681. };
  2682. Path3D.prototype.getBinormals = function () {
  2683. return this._binormals;
  2684. };
  2685. Path3D.prototype.getDistances = function () {
  2686. return this._distances;
  2687. };
  2688. Path3D.prototype.update = function (path, firstNormal) {
  2689. for (var p = 0; p < path.length; p++) {
  2690. this._curve[p].x = path[p].x;
  2691. this._curve[p].y = path[p].y;
  2692. this._curve[p].z = path[p].z;
  2693. }
  2694. this._compute(firstNormal);
  2695. return this;
  2696. };
  2697. // private function compute() : computes tangents, normals and binormals
  2698. Path3D.prototype._compute = function (firstNormal) {
  2699. var l = this._curve.length;
  2700. // first and last tangents
  2701. this._tangents[0] = this._getFirstNonNullVector(0);
  2702. if (!this._raw) {
  2703. this._tangents[0].normalize();
  2704. }
  2705. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2706. if (!this._raw) {
  2707. this._tangents[l - 1].normalize();
  2708. }
  2709. // normals and binormals at first point : arbitrary vector with _normalVector()
  2710. var tg0 = this._tangents[0];
  2711. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2712. this._normals[0] = pp0;
  2713. if (!this._raw) {
  2714. this._normals[0].normalize();
  2715. }
  2716. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2717. if (!this._raw) {
  2718. this._binormals[0].normalize();
  2719. }
  2720. this._distances[0] = 0;
  2721. // normals and binormals : next points
  2722. var prev; // previous vector (segment)
  2723. var cur; // current vector (segment)
  2724. var curTang; // current tangent
  2725. // previous normal
  2726. var prevBinor; // previous binormal
  2727. for (var i = 1; i < l; i++) {
  2728. // tangents
  2729. prev = this._getLastNonNullVector(i);
  2730. if (i < l - 1) {
  2731. cur = this._getFirstNonNullVector(i);
  2732. this._tangents[i] = prev.add(cur);
  2733. this._tangents[i].normalize();
  2734. }
  2735. this._distances[i] = this._distances[i - 1] + prev.length();
  2736. // normals and binormals
  2737. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2738. curTang = this._tangents[i];
  2739. prevBinor = this._binormals[i - 1];
  2740. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2741. if (!this._raw) {
  2742. this._normals[i].normalize();
  2743. }
  2744. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2745. if (!this._raw) {
  2746. this._binormals[i].normalize();
  2747. }
  2748. }
  2749. };
  2750. // private function getFirstNonNullVector(index)
  2751. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2752. Path3D.prototype._getFirstNonNullVector = function (index) {
  2753. var i = 1;
  2754. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2755. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2756. i++;
  2757. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2758. }
  2759. return nNVector;
  2760. };
  2761. // private function getLastNonNullVector(index)
  2762. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2763. Path3D.prototype._getLastNonNullVector = function (index) {
  2764. var i = 1;
  2765. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2766. while (nLVector.length() === 0 && index > i + 1) {
  2767. i++;
  2768. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2769. }
  2770. return nLVector;
  2771. };
  2772. // private function normalVector(v0, vt, va) :
  2773. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2774. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2775. Path3D.prototype._normalVector = function (v0, vt, va) {
  2776. var normal0;
  2777. if (va === undefined || va === null) {
  2778. var point;
  2779. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2780. point = new Vector3(0, -1, 0);
  2781. }
  2782. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2783. point = new Vector3(1, 0, 0);
  2784. }
  2785. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2786. point = new Vector3(0, 0, 1);
  2787. }
  2788. normal0 = Vector3.Cross(vt, point);
  2789. }
  2790. else {
  2791. normal0 = Vector3.Cross(vt, va);
  2792. Vector3.CrossToRef(normal0, vt, normal0);
  2793. }
  2794. normal0.normalize();
  2795. return normal0;
  2796. };
  2797. return Path3D;
  2798. })();
  2799. BABYLON.Path3D = Path3D;
  2800. var Curve3 = (function () {
  2801. function Curve3(points) {
  2802. this._length = 0;
  2803. this._points = points;
  2804. this._length = this._computeLength(points);
  2805. }
  2806. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2807. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2808. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2809. var bez = new Array();
  2810. var equation = function (t, val0, val1, val2) {
  2811. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2812. return res;
  2813. };
  2814. for (var i = 0; i <= nbPoints; i++) {
  2815. 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)));
  2816. }
  2817. return new Curve3(bez);
  2818. };
  2819. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2820. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2821. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2822. var bez = new Array();
  2823. var equation = function (t, val0, val1, val2, val3) {
  2824. 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;
  2825. return res;
  2826. };
  2827. for (var i = 0; i <= nbPoints; i++) {
  2828. 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)));
  2829. }
  2830. return new Curve3(bez);
  2831. };
  2832. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2833. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2834. var hermite = new Array();
  2835. var step = 1 / nbPoints;
  2836. for (var i = 0; i <= nbPoints; i++) {
  2837. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2838. }
  2839. return new Curve3(hermite);
  2840. };
  2841. Curve3.prototype.getPoints = function () {
  2842. return this._points;
  2843. };
  2844. Curve3.prototype.length = function () {
  2845. return this._length;
  2846. };
  2847. Curve3.prototype.continue = function (curve) {
  2848. var lastPoint = this._points[this._points.length - 1];
  2849. var continuedPoints = this._points.slice();
  2850. var curvePoints = curve.getPoints();
  2851. for (var i = 1; i < curvePoints.length; i++) {
  2852. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2853. }
  2854. var continuedCurve = new Curve3(continuedPoints);
  2855. return continuedCurve;
  2856. };
  2857. Curve3.prototype._computeLength = function (path) {
  2858. var l = 0;
  2859. for (var i = 1; i < path.length; i++) {
  2860. l += (path[i].subtract(path[i - 1])).length();
  2861. }
  2862. return l;
  2863. };
  2864. return Curve3;
  2865. })();
  2866. BABYLON.Curve3 = Curve3;
  2867. // Vertex formats
  2868. var PositionNormalVertex = (function () {
  2869. function PositionNormalVertex(position, normal) {
  2870. if (position === void 0) { position = Vector3.Zero(); }
  2871. if (normal === void 0) { normal = Vector3.Up(); }
  2872. this.position = position;
  2873. this.normal = normal;
  2874. }
  2875. PositionNormalVertex.prototype.clone = function () {
  2876. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2877. };
  2878. return PositionNormalVertex;
  2879. })();
  2880. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2881. var PositionNormalTextureVertex = (function () {
  2882. function PositionNormalTextureVertex(position, normal, uv) {
  2883. if (position === void 0) { position = Vector3.Zero(); }
  2884. if (normal === void 0) { normal = Vector3.Up(); }
  2885. if (uv === void 0) { uv = Vector2.Zero(); }
  2886. this.position = position;
  2887. this.normal = normal;
  2888. this.uv = uv;
  2889. }
  2890. PositionNormalTextureVertex.prototype.clone = function () {
  2891. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2892. };
  2893. return PositionNormalTextureVertex;
  2894. })();
  2895. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2896. })(BABYLON || (BABYLON = {}));
  2897. var BABYLON;
  2898. (function (BABYLON) {
  2899. var Database = (function () {
  2900. function Database(urlToScene, callbackManifestChecked) {
  2901. // Handling various flavors of prefixed version of IndexedDB
  2902. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2903. this.callbackManifestChecked = callbackManifestChecked;
  2904. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2905. this.db = null;
  2906. this.enableSceneOffline = false;
  2907. this.enableTexturesOffline = false;
  2908. this.manifestVersionFound = 0;
  2909. this.mustUpdateRessources = false;
  2910. this.hasReachedQuota = false;
  2911. if (!Database.IDBStorageEnabled) {
  2912. this.callbackManifestChecked(true);
  2913. }
  2914. else {
  2915. this.checkManifestFile();
  2916. }
  2917. }
  2918. Database.prototype.checkManifestFile = function () {
  2919. var _this = this;
  2920. function noManifestFile() {
  2921. that.enableSceneOffline = false;
  2922. that.enableTexturesOffline = false;
  2923. that.callbackManifestChecked(false);
  2924. }
  2925. var that = this;
  2926. var manifestURL = this.currentSceneUrl + ".manifest";
  2927. var xhr = new XMLHttpRequest();
  2928. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2929. xhr.open("GET", manifestURLTimeStamped, true);
  2930. xhr.addEventListener("load", function () {
  2931. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2932. try {
  2933. var manifestFile = JSON.parse(xhr.response);
  2934. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2935. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2936. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2937. _this.manifestVersionFound = manifestFile.version;
  2938. }
  2939. if (_this.callbackManifestChecked) {
  2940. _this.callbackManifestChecked(true);
  2941. }
  2942. }
  2943. catch (ex) {
  2944. noManifestFile();
  2945. }
  2946. }
  2947. else {
  2948. noManifestFile();
  2949. }
  2950. }, false);
  2951. xhr.addEventListener("error", function (event) {
  2952. noManifestFile();
  2953. }, false);
  2954. try {
  2955. xhr.send();
  2956. }
  2957. catch (ex) {
  2958. BABYLON.Tools.Error("Error on XHR send request.");
  2959. that.callbackManifestChecked(false);
  2960. }
  2961. };
  2962. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2963. var _this = this;
  2964. function handleError() {
  2965. that.isSupported = false;
  2966. if (errorCallback)
  2967. errorCallback();
  2968. }
  2969. var that = this;
  2970. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2971. // Your browser doesn't support IndexedDB
  2972. this.isSupported = false;
  2973. if (errorCallback)
  2974. errorCallback();
  2975. }
  2976. else {
  2977. // If the DB hasn't been opened or created yet
  2978. if (!this.db) {
  2979. this.hasReachedQuota = false;
  2980. this.isSupported = true;
  2981. var request = this.idbFactory.open("babylonjs", 1);
  2982. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2983. request.onerror = function (event) {
  2984. handleError();
  2985. };
  2986. // executes when a version change transaction cannot complete due to other active transactions
  2987. request.onblocked = function (event) {
  2988. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2989. handleError();
  2990. };
  2991. // DB has been opened successfully
  2992. request.onsuccess = function (event) {
  2993. _this.db = request.result;
  2994. successCallback();
  2995. };
  2996. // Initialization of the DB. Creating Scenes & Textures stores
  2997. request.onupgradeneeded = function (event) {
  2998. _this.db = (event.target).result;
  2999. try {
  3000. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3001. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3002. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3003. }
  3004. catch (ex) {
  3005. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3006. handleError();
  3007. }
  3008. };
  3009. }
  3010. else {
  3011. if (successCallback)
  3012. successCallback();
  3013. }
  3014. }
  3015. };
  3016. Database.prototype.loadImageFromDB = function (url, image) {
  3017. var _this = this;
  3018. var completeURL = Database.ReturnFullUrlLocation(url);
  3019. var saveAndLoadImage = function () {
  3020. if (!_this.hasReachedQuota && _this.db !== null) {
  3021. // the texture is not yet in the DB, let's try to save it
  3022. _this._saveImageIntoDBAsync(completeURL, image);
  3023. }
  3024. else {
  3025. image.src = url;
  3026. }
  3027. };
  3028. if (!this.mustUpdateRessources) {
  3029. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3030. }
  3031. else {
  3032. saveAndLoadImage();
  3033. }
  3034. };
  3035. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3036. if (this.isSupported && this.db !== null) {
  3037. var texture;
  3038. var transaction = this.db.transaction(["textures"]);
  3039. transaction.onabort = function (event) {
  3040. image.src = url;
  3041. };
  3042. transaction.oncomplete = function (event) {
  3043. var blobTextureURL;
  3044. if (texture) {
  3045. var URL = window.URL || window.webkitURL;
  3046. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3047. image.onerror = function () {
  3048. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3049. image.src = url;
  3050. };
  3051. image.src = blobTextureURL;
  3052. }
  3053. else {
  3054. notInDBCallback();
  3055. }
  3056. };
  3057. var getRequest = transaction.objectStore("textures").get(url);
  3058. getRequest.onsuccess = function (event) {
  3059. texture = (event.target).result;
  3060. };
  3061. getRequest.onerror = function (event) {
  3062. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3063. image.src = url;
  3064. };
  3065. }
  3066. else {
  3067. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3068. image.src = url;
  3069. }
  3070. };
  3071. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3072. var _this = this;
  3073. if (this.isSupported) {
  3074. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3075. var generateBlobUrl = function () {
  3076. var blobTextureURL;
  3077. if (blob) {
  3078. var URL = window.URL || window.webkitURL;
  3079. try {
  3080. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3081. }
  3082. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3083. catch (ex) {
  3084. blobTextureURL = URL.createObjectURL(blob);
  3085. }
  3086. }
  3087. image.src = blobTextureURL;
  3088. };
  3089. if (Database.IsUASupportingBlobStorage) {
  3090. var xhr = new XMLHttpRequest(), blob;
  3091. xhr.open("GET", url, true);
  3092. xhr.responseType = "blob";
  3093. xhr.addEventListener("load", function () {
  3094. if (xhr.status === 200) {
  3095. // Blob as response (XHR2)
  3096. blob = xhr.response;
  3097. var transaction = _this.db.transaction(["textures"], "readwrite");
  3098. // the transaction could abort because of a QuotaExceededError error
  3099. transaction.onabort = function (event) {
  3100. try {
  3101. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3102. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3103. this.hasReachedQuota = true;
  3104. }
  3105. }
  3106. catch (ex) { }
  3107. generateBlobUrl();
  3108. };
  3109. transaction.oncomplete = function (event) {
  3110. generateBlobUrl();
  3111. };
  3112. var newTexture = { textureUrl: url, data: blob };
  3113. try {
  3114. // Put the blob into the dabase
  3115. var addRequest = transaction.objectStore("textures").put(newTexture);
  3116. addRequest.onsuccess = function (event) {
  3117. };
  3118. addRequest.onerror = function (event) {
  3119. generateBlobUrl();
  3120. };
  3121. }
  3122. catch (ex) {
  3123. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3124. if (ex.code === 25) {
  3125. Database.IsUASupportingBlobStorage = false;
  3126. }
  3127. image.src = url;
  3128. }
  3129. }
  3130. else {
  3131. image.src = url;
  3132. }
  3133. }, false);
  3134. xhr.addEventListener("error", function (event) {
  3135. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3136. image.src = url;
  3137. }, false);
  3138. xhr.send();
  3139. }
  3140. else {
  3141. image.src = url;
  3142. }
  3143. }
  3144. else {
  3145. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3146. image.src = url;
  3147. }
  3148. };
  3149. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3150. var _this = this;
  3151. var updateVersion = function (event) {
  3152. // the version is not yet in the DB or we need to update it
  3153. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3154. };
  3155. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3156. };
  3157. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3158. var _this = this;
  3159. if (this.isSupported) {
  3160. var version;
  3161. try {
  3162. var transaction = this.db.transaction(["versions"]);
  3163. transaction.oncomplete = function (event) {
  3164. if (version) {
  3165. // If the version in the JSON file is > than the version in DB
  3166. if (_this.manifestVersionFound > version.data) {
  3167. _this.mustUpdateRessources = true;
  3168. updateInDBCallback();
  3169. }
  3170. else {
  3171. callback(version.data);
  3172. }
  3173. }
  3174. else {
  3175. _this.mustUpdateRessources = true;
  3176. updateInDBCallback();
  3177. }
  3178. };
  3179. transaction.onabort = function (event) {
  3180. callback(-1);
  3181. };
  3182. var getRequest = transaction.objectStore("versions").get(url);
  3183. getRequest.onsuccess = function (event) {
  3184. version = (event.target).result;
  3185. };
  3186. getRequest.onerror = function (event) {
  3187. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3188. callback(-1);
  3189. };
  3190. }
  3191. catch (ex) {
  3192. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3193. callback(-1);
  3194. }
  3195. }
  3196. else {
  3197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3198. callback(-1);
  3199. }
  3200. };
  3201. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3202. var _this = this;
  3203. if (this.isSupported && !this.hasReachedQuota) {
  3204. try {
  3205. // Open a transaction to the database
  3206. var transaction = this.db.transaction(["versions"], "readwrite");
  3207. // the transaction could abort because of a QuotaExceededError error
  3208. transaction.onabort = function (event) {
  3209. try {
  3210. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3211. _this.hasReachedQuota = true;
  3212. }
  3213. }
  3214. catch (ex) { }
  3215. callback(-1);
  3216. };
  3217. transaction.oncomplete = function (event) {
  3218. callback(_this.manifestVersionFound);
  3219. };
  3220. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3221. // Put the scene into the database
  3222. var addRequest = transaction.objectStore("versions").put(newVersion);
  3223. addRequest.onsuccess = function (event) {
  3224. };
  3225. addRequest.onerror = function (event) {
  3226. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3227. };
  3228. }
  3229. catch (ex) {
  3230. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3231. callback(-1);
  3232. }
  3233. }
  3234. else {
  3235. callback(-1);
  3236. }
  3237. };
  3238. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3239. var _this = this;
  3240. var completeUrl = Database.ReturnFullUrlLocation(url);
  3241. var saveAndLoadFile = function (event) {
  3242. // the scene is not yet in the DB, let's try to save it
  3243. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3244. };
  3245. this._checkVersionFromDB(completeUrl, function (version) {
  3246. if (version !== -1) {
  3247. if (!_this.mustUpdateRessources) {
  3248. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3249. }
  3250. else {
  3251. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3252. }
  3253. }
  3254. else {
  3255. errorCallback();
  3256. }
  3257. });
  3258. };
  3259. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3260. if (this.isSupported) {
  3261. var targetStore;
  3262. if (url.indexOf(".babylon") !== -1) {
  3263. targetStore = "scenes";
  3264. }
  3265. else {
  3266. targetStore = "textures";
  3267. }
  3268. var file;
  3269. var transaction = this.db.transaction([targetStore]);
  3270. transaction.oncomplete = function (event) {
  3271. if (file) {
  3272. callback(file.data);
  3273. }
  3274. else {
  3275. notInDBCallback();
  3276. }
  3277. };
  3278. transaction.onabort = function (event) {
  3279. notInDBCallback();
  3280. };
  3281. var getRequest = transaction.objectStore(targetStore).get(url);
  3282. getRequest.onsuccess = function (event) {
  3283. file = (event.target).result;
  3284. };
  3285. getRequest.onerror = function (event) {
  3286. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3287. notInDBCallback();
  3288. };
  3289. }
  3290. else {
  3291. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3292. callback();
  3293. }
  3294. };
  3295. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3296. var _this = this;
  3297. if (this.isSupported) {
  3298. var targetStore;
  3299. if (url.indexOf(".babylon") !== -1) {
  3300. targetStore = "scenes";
  3301. }
  3302. else {
  3303. targetStore = "textures";
  3304. }
  3305. // Create XHR
  3306. var xhr = new XMLHttpRequest(), fileData;
  3307. xhr.open("GET", url, true);
  3308. if (useArrayBuffer) {
  3309. xhr.responseType = "arraybuffer";
  3310. }
  3311. xhr.onprogress = progressCallback;
  3312. xhr.addEventListener("load", function () {
  3313. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3314. // Blob as response (XHR2)
  3315. //fileData = xhr.responseText;
  3316. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3317. if (!_this.hasReachedQuota) {
  3318. // Open a transaction to the database
  3319. var transaction = _this.db.transaction([targetStore], "readwrite");
  3320. // the transaction could abort because of a QuotaExceededError error
  3321. transaction.onabort = function (event) {
  3322. try {
  3323. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3324. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3325. this.hasReachedQuota = true;
  3326. }
  3327. }
  3328. catch (ex) { }
  3329. callback(fileData);
  3330. };
  3331. transaction.oncomplete = function (event) {
  3332. callback(fileData);
  3333. };
  3334. var newFile;
  3335. if (targetStore === "scenes") {
  3336. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3337. }
  3338. else {
  3339. newFile = { textureUrl: url, data: fileData };
  3340. }
  3341. try {
  3342. // Put the scene into the database
  3343. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3344. addRequest.onsuccess = function (event) {
  3345. };
  3346. addRequest.onerror = function (event) {
  3347. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3348. };
  3349. }
  3350. catch (ex) {
  3351. callback(fileData);
  3352. }
  3353. }
  3354. else {
  3355. callback(fileData);
  3356. }
  3357. }
  3358. else {
  3359. callback();
  3360. }
  3361. }, false);
  3362. xhr.addEventListener("error", function (event) {
  3363. BABYLON.Tools.Error("error on XHR request.");
  3364. callback();
  3365. }, false);
  3366. xhr.send();
  3367. }
  3368. else {
  3369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3370. callback();
  3371. }
  3372. };
  3373. Database.IsUASupportingBlobStorage = true;
  3374. Database.IDBStorageEnabled = true;
  3375. Database.parseURL = function (url) {
  3376. var a = document.createElement('a');
  3377. a.href = url;
  3378. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3379. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3380. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3381. return absLocation;
  3382. };
  3383. Database.ReturnFullUrlLocation = function (url) {
  3384. if (url.indexOf("http:/") === -1) {
  3385. return (Database.parseURL(window.location.href) + url);
  3386. }
  3387. else {
  3388. return url;
  3389. }
  3390. };
  3391. return Database;
  3392. })();
  3393. BABYLON.Database = Database;
  3394. })(BABYLON || (BABYLON = {}));
  3395. var BABYLON;
  3396. (function (BABYLON) {
  3397. var Internals;
  3398. (function (Internals) {
  3399. /*
  3400. * Based on jsTGALoader - Javascript loader for TGA file
  3401. * By Vincent Thibault
  3402. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3403. */
  3404. var TGATools = (function () {
  3405. function TGATools() {
  3406. }
  3407. TGATools.GetTGAHeader = function (data) {
  3408. var offset = 0;
  3409. var header = {
  3410. id_length: data[offset++],
  3411. colormap_type: data[offset++],
  3412. image_type: data[offset++],
  3413. colormap_index: data[offset++] | data[offset++] << 8,
  3414. colormap_length: data[offset++] | data[offset++] << 8,
  3415. colormap_size: data[offset++],
  3416. origin: [
  3417. data[offset++] | data[offset++] << 8,
  3418. data[offset++] | data[offset++] << 8
  3419. ],
  3420. width: data[offset++] | data[offset++] << 8,
  3421. height: data[offset++] | data[offset++] << 8,
  3422. pixel_size: data[offset++],
  3423. flags: data[offset++]
  3424. };
  3425. return header;
  3426. };
  3427. TGATools.UploadContent = function (gl, data) {
  3428. // Not enough data to contain header ?
  3429. if (data.length < 19) {
  3430. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3431. return;
  3432. }
  3433. // Read Header
  3434. var offset = 18;
  3435. var header = TGATools.GetTGAHeader(data);
  3436. // Assume it's a valid Targa file.
  3437. if (header.id_length + offset > data.length) {
  3438. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3439. return;
  3440. }
  3441. // Skip not needed data
  3442. offset += header.id_length;
  3443. var use_rle = false;
  3444. var use_pal = false;
  3445. var use_rgb = false;
  3446. var use_grey = false;
  3447. // Get some informations.
  3448. switch (header.image_type) {
  3449. case TGATools._TYPE_RLE_INDEXED:
  3450. use_rle = true;
  3451. case TGATools._TYPE_INDEXED:
  3452. use_pal = true;
  3453. break;
  3454. case TGATools._TYPE_RLE_RGB:
  3455. use_rle = true;
  3456. case TGATools._TYPE_RGB:
  3457. use_rgb = true;
  3458. break;
  3459. case TGATools._TYPE_RLE_GREY:
  3460. use_rle = true;
  3461. case TGATools._TYPE_GREY:
  3462. use_grey = true;
  3463. break;
  3464. }
  3465. var pixel_data;
  3466. var numAlphaBits = header.flags & 0xf;
  3467. var pixel_size = header.pixel_size >> 3;
  3468. var pixel_total = header.width * header.height * pixel_size;
  3469. // Read palettes
  3470. var palettes;
  3471. if (use_pal) {
  3472. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3473. }
  3474. // Read LRE
  3475. if (use_rle) {
  3476. pixel_data = new Uint8Array(pixel_total);
  3477. var c, count, i;
  3478. var localOffset = 0;
  3479. var pixels = new Uint8Array(pixel_size);
  3480. while (offset < pixel_total && localOffset < pixel_total) {
  3481. c = data[offset++];
  3482. count = (c & 0x7f) + 1;
  3483. // RLE pixels
  3484. if (c & 0x80) {
  3485. // Bind pixel tmp array
  3486. for (i = 0; i < pixel_size; ++i) {
  3487. pixels[i] = data[offset++];
  3488. }
  3489. // Copy pixel array
  3490. for (i = 0; i < count; ++i) {
  3491. pixel_data.set(pixels, localOffset + i * pixel_size);
  3492. }
  3493. localOffset += pixel_size * count;
  3494. }
  3495. else {
  3496. count *= pixel_size;
  3497. for (i = 0; i < count; ++i) {
  3498. pixel_data[localOffset + i] = data[offset++];
  3499. }
  3500. localOffset += count;
  3501. }
  3502. }
  3503. }
  3504. else {
  3505. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3506. }
  3507. // Load to texture
  3508. var x_start, y_start, x_step, y_step, y_end, x_end;
  3509. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3510. default:
  3511. case TGATools._ORIGIN_UL:
  3512. x_start = 0;
  3513. x_step = 1;
  3514. x_end = header.width;
  3515. y_start = 0;
  3516. y_step = 1;
  3517. y_end = header.height;
  3518. break;
  3519. case TGATools._ORIGIN_BL:
  3520. x_start = 0;
  3521. x_step = 1;
  3522. x_end = header.width;
  3523. y_start = header.height - 1;
  3524. y_step = -1;
  3525. y_end = -1;
  3526. break;
  3527. case TGATools._ORIGIN_UR:
  3528. x_start = header.width - 1;
  3529. x_step = -1;
  3530. x_end = -1;
  3531. y_start = 0;
  3532. y_step = 1;
  3533. y_end = header.height;
  3534. break;
  3535. case TGATools._ORIGIN_BR:
  3536. x_start = header.width - 1;
  3537. x_step = -1;
  3538. x_end = -1;
  3539. y_start = header.height - 1;
  3540. y_step = -1;
  3541. y_end = -1;
  3542. break;
  3543. }
  3544. // Load the specify method
  3545. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3546. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3548. };
  3549. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3550. var image = pixel_data, colormap = palettes;
  3551. var width = header.width, height = header.height;
  3552. var color, i = 0, x, y;
  3553. var imageData = new Uint8Array(width * height * 4);
  3554. for (y = y_start; y !== y_end; y += y_step) {
  3555. for (x = x_start; x !== x_end; x += x_step, i++) {
  3556. color = image[i];
  3557. imageData[(x + width * y) * 4 + 3] = 255;
  3558. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3559. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3560. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3561. }
  3562. }
  3563. return imageData;
  3564. };
  3565. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3566. var image = pixel_data;
  3567. var width = header.width, height = header.height;
  3568. var color, i = 0, x, y;
  3569. var imageData = new Uint8Array(width * height * 4);
  3570. for (y = y_start; y !== y_end; y += y_step) {
  3571. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3572. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3573. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3574. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3575. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3576. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3577. }
  3578. }
  3579. return imageData;
  3580. };
  3581. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3582. var image = pixel_data;
  3583. var width = header.width, height = header.height;
  3584. var i = 0, x, y;
  3585. var imageData = new Uint8Array(width * height * 4);
  3586. for (y = y_start; y !== y_end; y += y_step) {
  3587. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3588. imageData[(x + width * y) * 4 + 3] = 255;
  3589. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3590. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3591. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3592. }
  3593. }
  3594. return imageData;
  3595. };
  3596. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3597. var image = pixel_data;
  3598. var width = header.width, height = header.height;
  3599. var i = 0, x, y;
  3600. var imageData = new Uint8Array(width * height * 4);
  3601. for (y = y_start; y !== y_end; y += y_step) {
  3602. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3603. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3604. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3605. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3606. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3607. }
  3608. }
  3609. return imageData;
  3610. };
  3611. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3612. var image = pixel_data;
  3613. var width = header.width, height = header.height;
  3614. var color, i = 0, x, y;
  3615. var imageData = new Uint8Array(width * height * 4);
  3616. for (y = y_start; y !== y_end; y += y_step) {
  3617. for (x = x_start; x !== x_end; x += x_step, i++) {
  3618. color = image[i];
  3619. imageData[(x + width * y) * 4 + 0] = color;
  3620. imageData[(x + width * y) * 4 + 1] = color;
  3621. imageData[(x + width * y) * 4 + 2] = color;
  3622. imageData[(x + width * y) * 4 + 3] = 255;
  3623. }
  3624. }
  3625. return imageData;
  3626. };
  3627. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3628. var image = pixel_data;
  3629. var width = header.width, height = header.height;
  3630. var i = 0, x, y;
  3631. var imageData = new Uint8Array(width * height * 4);
  3632. for (y = y_start; y !== y_end; y += y_step) {
  3633. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3634. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3635. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3636. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3637. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3638. }
  3639. }
  3640. return imageData;
  3641. };
  3642. TGATools._TYPE_NO_DATA = 0;
  3643. TGATools._TYPE_INDEXED = 1;
  3644. TGATools._TYPE_RGB = 2;
  3645. TGATools._TYPE_GREY = 3;
  3646. TGATools._TYPE_RLE_INDEXED = 9;
  3647. TGATools._TYPE_RLE_RGB = 10;
  3648. TGATools._TYPE_RLE_GREY = 11;
  3649. TGATools._ORIGIN_MASK = 0x30;
  3650. TGATools._ORIGIN_SHIFT = 0x04;
  3651. TGATools._ORIGIN_BL = 0x00;
  3652. TGATools._ORIGIN_BR = 0x01;
  3653. TGATools._ORIGIN_UL = 0x02;
  3654. TGATools._ORIGIN_UR = 0x03;
  3655. return TGATools;
  3656. })();
  3657. Internals.TGATools = TGATools;
  3658. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3659. })(BABYLON || (BABYLON = {}));
  3660. var BABYLON;
  3661. (function (BABYLON) {
  3662. var SmartArray = (function () {
  3663. function SmartArray(capacity) {
  3664. this.length = 0;
  3665. this._duplicateId = 0;
  3666. this.data = new Array(capacity);
  3667. this._id = SmartArray._GlobalId++;
  3668. }
  3669. SmartArray.prototype.push = function (value) {
  3670. this.data[this.length++] = value;
  3671. if (this.length > this.data.length) {
  3672. this.data.length *= 2;
  3673. }
  3674. if (!value.__smartArrayFlags) {
  3675. value.__smartArrayFlags = {};
  3676. }
  3677. value.__smartArrayFlags[this._id] = this._duplicateId;
  3678. };
  3679. SmartArray.prototype.pushNoDuplicate = function (value) {
  3680. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3681. return;
  3682. }
  3683. this.push(value);
  3684. };
  3685. SmartArray.prototype.sort = function (compareFn) {
  3686. this.data.sort(compareFn);
  3687. };
  3688. SmartArray.prototype.reset = function () {
  3689. this.length = 0;
  3690. this._duplicateId++;
  3691. };
  3692. SmartArray.prototype.concat = function (array) {
  3693. if (array.length === 0) {
  3694. return;
  3695. }
  3696. if (this.length + array.length > this.data.length) {
  3697. this.data.length = (this.length + array.length) * 2;
  3698. }
  3699. for (var index = 0; index < array.length; index++) {
  3700. this.data[this.length++] = (array.data || array)[index];
  3701. }
  3702. };
  3703. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3704. if (array.length === 0) {
  3705. return;
  3706. }
  3707. if (this.length + array.length > this.data.length) {
  3708. this.data.length = (this.length + array.length) * 2;
  3709. }
  3710. for (var index = 0; index < array.length; index++) {
  3711. var item = (array.data || array)[index];
  3712. this.pushNoDuplicate(item);
  3713. }
  3714. };
  3715. SmartArray.prototype.indexOf = function (value) {
  3716. var position = this.data.indexOf(value);
  3717. if (position >= this.length) {
  3718. return -1;
  3719. }
  3720. return position;
  3721. };
  3722. // Statics
  3723. SmartArray._GlobalId = 0;
  3724. return SmartArray;
  3725. })();
  3726. BABYLON.SmartArray = SmartArray;
  3727. })(BABYLON || (BABYLON = {}));
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var SmartCollection = (function () {
  3731. function SmartCollection(capacity) {
  3732. if (capacity === void 0) { capacity = 10; }
  3733. this.count = 0;
  3734. this._initialCapacity = capacity;
  3735. this.items = {};
  3736. this._keys = new Array(this._initialCapacity);
  3737. }
  3738. SmartCollection.prototype.add = function (key, item) {
  3739. if (this.items[key] != undefined) {
  3740. return -1;
  3741. }
  3742. this.items[key] = item;
  3743. //literal keys are always strings, but we keep source type of key in _keys array
  3744. this._keys[this.count++] = key;
  3745. if (this.count > this._keys.length) {
  3746. this._keys.length *= 2;
  3747. }
  3748. return this.count;
  3749. };
  3750. SmartCollection.prototype.remove = function (key) {
  3751. if (this.items[key] == undefined) {
  3752. return -1;
  3753. }
  3754. return this.removeItemOfIndex(this.indexOf(key));
  3755. };
  3756. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3757. if (index < this.count && index > -1) {
  3758. delete this.items[this._keys[index]];
  3759. //here, shifting by hand is better optimised than .splice
  3760. while (index < this.count) {
  3761. this._keys[index] = this._keys[index + 1];
  3762. index++;
  3763. }
  3764. }
  3765. else {
  3766. return -1;
  3767. }
  3768. return --this.count;
  3769. };
  3770. SmartCollection.prototype.indexOf = function (key) {
  3771. for (var i = 0; i !== this.count; i++) {
  3772. if (this._keys[i] === key) {
  3773. return i;
  3774. }
  3775. }
  3776. return -1;
  3777. };
  3778. SmartCollection.prototype.item = function (key) {
  3779. return this.items[key];
  3780. };
  3781. SmartCollection.prototype.getAllKeys = function () {
  3782. if (this.count > 0) {
  3783. var keys = new Array(this.count);
  3784. for (var i = 0; i < this.count; i++) {
  3785. keys[i] = this._keys[i];
  3786. }
  3787. return keys;
  3788. }
  3789. else {
  3790. return undefined;
  3791. }
  3792. };
  3793. SmartCollection.prototype.getKeyByIndex = function (index) {
  3794. if (index < this.count && index > -1) {
  3795. return this._keys[index];
  3796. }
  3797. else {
  3798. return undefined;
  3799. }
  3800. };
  3801. SmartCollection.prototype.getItemByIndex = function (index) {
  3802. if (index < this.count && index > -1) {
  3803. return this.items[this._keys[index]];
  3804. }
  3805. else {
  3806. return undefined;
  3807. }
  3808. };
  3809. SmartCollection.prototype.empty = function () {
  3810. if (this.count > 0) {
  3811. this.count = 0;
  3812. this.items = {};
  3813. this._keys = new Array(this._initialCapacity);
  3814. }
  3815. };
  3816. SmartCollection.prototype.forEach = function (block) {
  3817. var key;
  3818. for (key in this.items) {
  3819. if (this.items.hasOwnProperty(key)) {
  3820. block(this.items[key]);
  3821. }
  3822. }
  3823. };
  3824. return SmartCollection;
  3825. })();
  3826. BABYLON.SmartCollection = SmartCollection;
  3827. })(BABYLON || (BABYLON = {}));
  3828. var BABYLON;
  3829. (function (BABYLON) {
  3830. // Screenshots
  3831. var screenshotCanvas;
  3832. var cloneValue = function (source, destinationObject) {
  3833. if (!source)
  3834. return null;
  3835. if (source instanceof BABYLON.Mesh) {
  3836. return null;
  3837. }
  3838. if (source instanceof BABYLON.SubMesh) {
  3839. return source.clone(destinationObject);
  3840. }
  3841. else if (source.clone) {
  3842. return source.clone();
  3843. }
  3844. return null;
  3845. };
  3846. var Tools = (function () {
  3847. function Tools() {
  3848. }
  3849. Tools.ToHex = function (i) {
  3850. var str = i.toString(16);
  3851. if (i <= 15) {
  3852. return ("0" + str).toUpperCase();
  3853. }
  3854. return str.toUpperCase();
  3855. };
  3856. Tools.SetImmediate = function (action) {
  3857. if (window.setImmediate) {
  3858. window.setImmediate(action);
  3859. }
  3860. else {
  3861. setTimeout(action, 1);
  3862. }
  3863. };
  3864. Tools.IsExponentOfTwo = function (value) {
  3865. var count = 1;
  3866. do {
  3867. count *= 2;
  3868. } while (count < value);
  3869. return count === value;
  3870. };
  3871. Tools.GetExponentOfTwo = function (value, max) {
  3872. var count = 1;
  3873. do {
  3874. count *= 2;
  3875. } while (count < value);
  3876. if (count > max)
  3877. count = max;
  3878. return count;
  3879. };
  3880. Tools.GetFilename = function (path) {
  3881. var index = path.lastIndexOf("/");
  3882. if (index < 0)
  3883. return path;
  3884. return path.substring(index + 1);
  3885. };
  3886. Tools.GetDOMTextContent = function (element) {
  3887. var result = "";
  3888. var child = element.firstChild;
  3889. while (child) {
  3890. if (child.nodeType === 3) {
  3891. result += child.textContent;
  3892. }
  3893. child = child.nextSibling;
  3894. }
  3895. return result;
  3896. };
  3897. Tools.ToDegrees = function (angle) {
  3898. return angle * 180 / Math.PI;
  3899. };
  3900. Tools.ToRadians = function (angle) {
  3901. return angle * Math.PI / 180;
  3902. };
  3903. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3904. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3905. var output = "";
  3906. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3907. var i = 0;
  3908. var bytes = new Uint8Array(buffer);
  3909. while (i < bytes.length) {
  3910. chr1 = bytes[i++];
  3911. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3912. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3913. enc1 = chr1 >> 2;
  3914. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3915. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3916. enc4 = chr3 & 63;
  3917. if (isNaN(chr2)) {
  3918. enc3 = enc4 = 64;
  3919. }
  3920. else if (isNaN(chr3)) {
  3921. enc4 = 64;
  3922. }
  3923. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3924. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3925. }
  3926. return "data:image/png;base64," + output;
  3927. };
  3928. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3929. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3930. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3931. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3932. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3933. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3934. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3935. }
  3936. return {
  3937. minimum: minimum,
  3938. maximum: maximum
  3939. };
  3940. };
  3941. Tools.ExtractMinAndMax = function (positions, start, count) {
  3942. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3943. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3944. for (var index = start; index < start + count; index++) {
  3945. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3946. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3947. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3948. }
  3949. return {
  3950. minimum: minimum,
  3951. maximum: maximum
  3952. };
  3953. };
  3954. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3955. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3956. return undefined;
  3957. return Array.isArray(obj) ? obj : [obj];
  3958. };
  3959. // Misc.
  3960. Tools.GetPointerPrefix = function () {
  3961. var eventPrefix = "pointer";
  3962. // Check if hand.js is referenced or if the browser natively supports pointer events
  3963. if (!navigator.pointerEnabled) {
  3964. eventPrefix = "mouse";
  3965. }
  3966. return eventPrefix;
  3967. };
  3968. Tools.QueueNewFrame = function (func) {
  3969. if (window.requestAnimationFrame)
  3970. window.requestAnimationFrame(func);
  3971. else if (window.msRequestAnimationFrame)
  3972. window.msRequestAnimationFrame(func);
  3973. else if (window.webkitRequestAnimationFrame)
  3974. window.webkitRequestAnimationFrame(func);
  3975. else if (window.mozRequestAnimationFrame)
  3976. window.mozRequestAnimationFrame(func);
  3977. else if (window.oRequestAnimationFrame)
  3978. window.oRequestAnimationFrame(func);
  3979. else {
  3980. window.setTimeout(func, 16);
  3981. }
  3982. };
  3983. Tools.RequestFullscreen = function (element) {
  3984. if (element.requestFullscreen)
  3985. element.requestFullscreen();
  3986. else if (element.msRequestFullscreen)
  3987. element.msRequestFullscreen();
  3988. else if (element.webkitRequestFullscreen)
  3989. element.webkitRequestFullscreen();
  3990. else if (element.mozRequestFullScreen)
  3991. element.mozRequestFullScreen();
  3992. };
  3993. Tools.ExitFullscreen = function () {
  3994. if (document.exitFullscreen) {
  3995. document.exitFullscreen();
  3996. }
  3997. else if (document.mozCancelFullScreen) {
  3998. document.mozCancelFullScreen();
  3999. }
  4000. else if (document.webkitCancelFullScreen) {
  4001. document.webkitCancelFullScreen();
  4002. }
  4003. else if (document.msCancelFullScreen) {
  4004. document.msCancelFullScreen();
  4005. }
  4006. };
  4007. // External files
  4008. Tools.CleanUrl = function (url) {
  4009. url = url.replace(/#/mg, "%23");
  4010. return url;
  4011. };
  4012. Tools.LoadImage = function (url, onload, onerror, database) {
  4013. if (url instanceof ArrayBuffer) {
  4014. url = Tools.EncodeArrayBufferTobase64(url);
  4015. }
  4016. url = Tools.CleanUrl(url);
  4017. var img = new Image();
  4018. if (url.substr(0, 5) !== "data:") {
  4019. if (Tools.CorsBehavior) {
  4020. switch (typeof (Tools.CorsBehavior)) {
  4021. case "function":
  4022. var result = Tools.CorsBehavior(url);
  4023. if (result) {
  4024. img.crossOrigin = result;
  4025. }
  4026. break;
  4027. case "string":
  4028. default:
  4029. img.crossOrigin = Tools.CorsBehavior;
  4030. break;
  4031. }
  4032. }
  4033. }
  4034. img.onload = function () {
  4035. onload(img);
  4036. };
  4037. img.onerror = function (err) {
  4038. Tools.Error("Error while trying to load texture: " + url);
  4039. 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";
  4040. onload(img);
  4041. };
  4042. var noIndexedDB = function () {
  4043. img.src = url;
  4044. };
  4045. var loadFromIndexedDB = function () {
  4046. database.loadImageFromDB(url, img);
  4047. };
  4048. //ANY database to do!
  4049. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4050. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4051. }
  4052. else {
  4053. if (url.indexOf("file:") === -1) {
  4054. noIndexedDB();
  4055. }
  4056. else {
  4057. try {
  4058. var textureName = url.substring(5);
  4059. var blobURL;
  4060. try {
  4061. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4062. }
  4063. catch (ex) {
  4064. // Chrome doesn't support oneTimeOnly parameter
  4065. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4066. }
  4067. img.src = blobURL;
  4068. }
  4069. catch (e) {
  4070. img.src = null;
  4071. }
  4072. }
  4073. }
  4074. return img;
  4075. };
  4076. //ANY
  4077. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4078. url = Tools.CleanUrl(url);
  4079. var noIndexedDB = function () {
  4080. var request = new XMLHttpRequest();
  4081. var loadUrl = Tools.BaseUrl + url;
  4082. request.open('GET', loadUrl, true);
  4083. if (useArrayBuffer) {
  4084. request.responseType = "arraybuffer";
  4085. }
  4086. request.onprogress = progressCallBack;
  4087. request.onreadystatechange = function () {
  4088. if (request.readyState === 4) {
  4089. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4090. callback(!useArrayBuffer ? request.responseText : request.response);
  4091. }
  4092. else {
  4093. if (onError) {
  4094. onError();
  4095. }
  4096. else {
  4097. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4098. }
  4099. }
  4100. }
  4101. };
  4102. request.send(null);
  4103. };
  4104. var loadFromIndexedDB = function () {
  4105. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4106. };
  4107. if (url.indexOf("file:") !== -1) {
  4108. var fileName = url.substring(5);
  4109. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4110. }
  4111. else {
  4112. // Caching all files
  4113. if (database && database.enableSceneOffline) {
  4114. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4115. }
  4116. else {
  4117. noIndexedDB();
  4118. }
  4119. }
  4120. };
  4121. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4122. var reader = new FileReader();
  4123. reader.onload = function (e) {
  4124. //target doesn't have result from ts 1.3
  4125. callback(e.target['result']);
  4126. };
  4127. reader.onprogress = progressCallback;
  4128. reader.readAsDataURL(fileToLoad);
  4129. };
  4130. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4131. var reader = new FileReader();
  4132. reader.onerror = function (e) {
  4133. Tools.Log("Error while reading file: " + fileToLoad.name);
  4134. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4135. };
  4136. reader.onload = function (e) {
  4137. //target doesn't have result from ts 1.3
  4138. callback(e.target['result']);
  4139. };
  4140. reader.onprogress = progressCallBack;
  4141. if (!useArrayBuffer) {
  4142. // Asynchronous read
  4143. reader.readAsText(fileToLoad);
  4144. }
  4145. else {
  4146. reader.readAsArrayBuffer(fileToLoad);
  4147. }
  4148. };
  4149. //returns a downloadable url to a file content.
  4150. Tools.FileAsURL = function (content) {
  4151. var fileBlob = new Blob([content]);
  4152. var url = window.URL || window.webkitURL;
  4153. var link = url.createObjectURL(fileBlob);
  4154. return link;
  4155. };
  4156. // Misc.
  4157. Tools.Clamp = function (value, min, max) {
  4158. if (min === void 0) { min = 0; }
  4159. if (max === void 0) { max = 1; }
  4160. return Math.min(max, Math.max(min, value));
  4161. };
  4162. // Returns -1 when value is a negative number and
  4163. // +1 when value is a positive number.
  4164. Tools.Sign = function (value) {
  4165. value = +value; // convert to a number
  4166. if (value === 0 || isNaN(value))
  4167. return value;
  4168. return value > 0 ? 1 : -1;
  4169. };
  4170. Tools.Format = function (value, decimals) {
  4171. if (decimals === void 0) { decimals = 2; }
  4172. return value.toFixed(decimals);
  4173. };
  4174. Tools.CheckExtends = function (v, min, max) {
  4175. if (v.x < min.x)
  4176. min.x = v.x;
  4177. if (v.y < min.y)
  4178. min.y = v.y;
  4179. if (v.z < min.z)
  4180. min.z = v.z;
  4181. if (v.x > max.x)
  4182. max.x = v.x;
  4183. if (v.y > max.y)
  4184. max.y = v.y;
  4185. if (v.z > max.z)
  4186. max.z = v.z;
  4187. };
  4188. Tools.WithinEpsilon = function (a, b, epsilon) {
  4189. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4190. var num = a - b;
  4191. return -epsilon <= num && num <= epsilon;
  4192. };
  4193. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4194. for (var prop in source) {
  4195. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4196. continue;
  4197. }
  4198. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4199. continue;
  4200. }
  4201. var sourceValue = source[prop];
  4202. var typeOfSourceValue = typeof sourceValue;
  4203. if (typeOfSourceValue === "function") {
  4204. continue;
  4205. }
  4206. if (typeOfSourceValue === "object") {
  4207. if (sourceValue instanceof Array) {
  4208. destination[prop] = [];
  4209. if (sourceValue.length > 0) {
  4210. if (typeof sourceValue[0] == "object") {
  4211. for (var index = 0; index < sourceValue.length; index++) {
  4212. var clonedValue = cloneValue(sourceValue[index], destination);
  4213. if (destination[prop].indexOf(clonedValue) === -1) {
  4214. destination[prop].push(clonedValue);
  4215. }
  4216. }
  4217. }
  4218. else {
  4219. destination[prop] = sourceValue.slice(0);
  4220. }
  4221. }
  4222. }
  4223. else {
  4224. destination[prop] = cloneValue(sourceValue, destination);
  4225. }
  4226. }
  4227. else {
  4228. destination[prop] = sourceValue;
  4229. }
  4230. }
  4231. };
  4232. Tools.IsEmpty = function (obj) {
  4233. for (var i in obj) {
  4234. return false;
  4235. }
  4236. return true;
  4237. };
  4238. Tools.RegisterTopRootEvents = function (events) {
  4239. for (var index = 0; index < events.length; index++) {
  4240. var event = events[index];
  4241. window.addEventListener(event.name, event.handler, false);
  4242. try {
  4243. if (window.parent) {
  4244. window.parent.addEventListener(event.name, event.handler, false);
  4245. }
  4246. }
  4247. catch (e) {
  4248. }
  4249. }
  4250. };
  4251. Tools.UnregisterTopRootEvents = function (events) {
  4252. for (var index = 0; index < events.length; index++) {
  4253. var event = events[index];
  4254. window.removeEventListener(event.name, event.handler);
  4255. try {
  4256. if (window.parent) {
  4257. window.parent.removeEventListener(event.name, event.handler);
  4258. }
  4259. }
  4260. catch (e) {
  4261. }
  4262. }
  4263. };
  4264. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4265. // Read the contents of the framebuffer
  4266. var numberOfChannelsByLine = width * 4;
  4267. var halfHeight = height / 2;
  4268. //Reading datas from WebGL
  4269. var data = engine.readPixels(0, 0, width, height);
  4270. //To flip image on Y axis.
  4271. for (var i = 0; i < halfHeight; i++) {
  4272. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4273. var currentCell = j + i * numberOfChannelsByLine;
  4274. var targetLine = height - i - 1;
  4275. var targetCell = j + targetLine * numberOfChannelsByLine;
  4276. var temp = data[currentCell];
  4277. data[currentCell] = data[targetCell];
  4278. data[targetCell] = temp;
  4279. }
  4280. }
  4281. // Create a 2D canvas to store the result
  4282. if (!screenshotCanvas) {
  4283. screenshotCanvas = document.createElement('canvas');
  4284. }
  4285. screenshotCanvas.width = width;
  4286. screenshotCanvas.height = height;
  4287. var context = screenshotCanvas.getContext('2d');
  4288. // Copy the pixels to a 2D canvas
  4289. var imageData = context.createImageData(width, height);
  4290. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4291. var castData = imageData.data;
  4292. castData.set(data);
  4293. context.putImageData(imageData, 0, 0);
  4294. var base64Image = screenshotCanvas.toDataURL();
  4295. if (successCallback) {
  4296. successCallback(base64Image);
  4297. }
  4298. else {
  4299. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4300. if (("download" in document.createElement("a"))) {
  4301. var a = window.document.createElement("a");
  4302. a.href = base64Image;
  4303. var date = new Date();
  4304. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4305. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4306. window.document.body.appendChild(a);
  4307. a.addEventListener("click", function () {
  4308. a.parentElement.removeChild(a);
  4309. });
  4310. a.click();
  4311. }
  4312. else {
  4313. var newWindow = window.open("");
  4314. var img = newWindow.document.createElement("img");
  4315. img.src = base64Image;
  4316. newWindow.document.body.appendChild(img);
  4317. }
  4318. }
  4319. };
  4320. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4321. var width;
  4322. var height;
  4323. //If a precision value is specified
  4324. if (size.precision) {
  4325. width = Math.round(engine.getRenderWidth() * size.precision);
  4326. height = Math.round(width / engine.getAspectRatio(camera));
  4327. size = { width: width, height: height };
  4328. }
  4329. else if (size.width && size.height) {
  4330. width = size.width;
  4331. height = size.height;
  4332. }
  4333. else if (size.width && !size.height) {
  4334. width = size.width;
  4335. height = Math.round(width / engine.getAspectRatio(camera));
  4336. size = { width: width, height: height };
  4337. }
  4338. else if (size.height && !size.width) {
  4339. height = size.height;
  4340. width = Math.round(height * engine.getAspectRatio(camera));
  4341. size = { width: width, height: height };
  4342. }
  4343. else if (!isNaN(size)) {
  4344. height = size;
  4345. width = size;
  4346. }
  4347. else {
  4348. Tools.Error("Invalid 'size' parameter !");
  4349. return;
  4350. }
  4351. var scene = camera.getScene();
  4352. var previousCamera = null;
  4353. if (scene.activeCamera !== camera) {
  4354. previousCamera = scene.activeCamera;
  4355. scene.activeCamera = camera;
  4356. }
  4357. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4358. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4359. texture.renderList = scene.meshes;
  4360. texture.onAfterRender = function () {
  4361. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4362. };
  4363. scene.incrementRenderId();
  4364. texture.render(true);
  4365. texture.dispose();
  4366. if (previousCamera) {
  4367. scene.activeCamera = previousCamera;
  4368. }
  4369. };
  4370. // XHR response validator for local file scenario
  4371. Tools.ValidateXHRData = function (xhr, dataType) {
  4372. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4373. if (dataType === void 0) { dataType = 7; }
  4374. try {
  4375. if (dataType & 1) {
  4376. if (xhr.responseText && xhr.responseText.length > 0) {
  4377. return true;
  4378. }
  4379. else if (dataType === 1) {
  4380. return false;
  4381. }
  4382. }
  4383. if (dataType & 2) {
  4384. // Check header width and height since there is no "TGA" magic number
  4385. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4386. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4387. return true;
  4388. }
  4389. else if (dataType === 2) {
  4390. return false;
  4391. }
  4392. }
  4393. if (dataType & 4) {
  4394. // Check for the "DDS" magic number
  4395. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4396. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4397. return true;
  4398. }
  4399. else {
  4400. return false;
  4401. }
  4402. }
  4403. }
  4404. catch (e) {
  4405. }
  4406. return false;
  4407. };
  4408. Object.defineProperty(Tools, "NoneLogLevel", {
  4409. get: function () {
  4410. return Tools._NoneLogLevel;
  4411. },
  4412. enumerable: true,
  4413. configurable: true
  4414. });
  4415. Object.defineProperty(Tools, "MessageLogLevel", {
  4416. get: function () {
  4417. return Tools._MessageLogLevel;
  4418. },
  4419. enumerable: true,
  4420. configurable: true
  4421. });
  4422. Object.defineProperty(Tools, "WarningLogLevel", {
  4423. get: function () {
  4424. return Tools._WarningLogLevel;
  4425. },
  4426. enumerable: true,
  4427. configurable: true
  4428. });
  4429. Object.defineProperty(Tools, "ErrorLogLevel", {
  4430. get: function () {
  4431. return Tools._ErrorLogLevel;
  4432. },
  4433. enumerable: true,
  4434. configurable: true
  4435. });
  4436. Object.defineProperty(Tools, "AllLogLevel", {
  4437. get: function () {
  4438. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4439. },
  4440. enumerable: true,
  4441. configurable: true
  4442. });
  4443. Tools._AddLogEntry = function (entry) {
  4444. Tools._LogCache = entry + Tools._LogCache;
  4445. if (Tools.OnNewCacheEntry) {
  4446. Tools.OnNewCacheEntry(entry);
  4447. }
  4448. };
  4449. Tools._FormatMessage = function (message) {
  4450. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4451. var date = new Date();
  4452. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4453. };
  4454. Tools._LogDisabled = function (message) {
  4455. // nothing to do
  4456. };
  4457. Tools._LogEnabled = function (message) {
  4458. var formattedMessage = Tools._FormatMessage(message);
  4459. console.log("BJS - " + formattedMessage);
  4460. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4461. Tools._AddLogEntry(entry);
  4462. };
  4463. Tools._WarnDisabled = function (message) {
  4464. // nothing to do
  4465. };
  4466. Tools._WarnEnabled = function (message) {
  4467. var formattedMessage = Tools._FormatMessage(message);
  4468. console.warn("BJS - " + formattedMessage);
  4469. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4470. Tools._AddLogEntry(entry);
  4471. };
  4472. Tools._ErrorDisabled = function (message) {
  4473. // nothing to do
  4474. };
  4475. Tools._ErrorEnabled = function (message) {
  4476. Tools.errorsCount++;
  4477. var formattedMessage = Tools._FormatMessage(message);
  4478. console.error("BJS - " + formattedMessage);
  4479. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4480. Tools._AddLogEntry(entry);
  4481. };
  4482. Object.defineProperty(Tools, "LogCache", {
  4483. get: function () {
  4484. return Tools._LogCache;
  4485. },
  4486. enumerable: true,
  4487. configurable: true
  4488. });
  4489. Tools.ClearLogCache = function () {
  4490. Tools._LogCache = "";
  4491. Tools.errorsCount = 0;
  4492. };
  4493. Object.defineProperty(Tools, "LogLevels", {
  4494. set: function (level) {
  4495. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4496. Tools.Log = Tools._LogEnabled;
  4497. }
  4498. else {
  4499. Tools.Log = Tools._LogDisabled;
  4500. }
  4501. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4502. Tools.Warn = Tools._WarnEnabled;
  4503. }
  4504. else {
  4505. Tools.Warn = Tools._WarnDisabled;
  4506. }
  4507. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4508. Tools.Error = Tools._ErrorEnabled;
  4509. }
  4510. else {
  4511. Tools.Error = Tools._ErrorDisabled;
  4512. }
  4513. },
  4514. enumerable: true,
  4515. configurable: true
  4516. });
  4517. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4518. get: function () {
  4519. return Tools._PerformanceNoneLogLevel;
  4520. },
  4521. enumerable: true,
  4522. configurable: true
  4523. });
  4524. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4525. get: function () {
  4526. return Tools._PerformanceUserMarkLogLevel;
  4527. },
  4528. enumerable: true,
  4529. configurable: true
  4530. });
  4531. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4532. get: function () {
  4533. return Tools._PerformanceConsoleLogLevel;
  4534. },
  4535. enumerable: true,
  4536. configurable: true
  4537. });
  4538. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4539. set: function (level) {
  4540. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4541. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4542. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4543. return;
  4544. }
  4545. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4546. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4547. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4548. return;
  4549. }
  4550. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4551. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4552. },
  4553. enumerable: true,
  4554. configurable: true
  4555. });
  4556. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4557. };
  4558. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4559. };
  4560. Tools._StartUserMark = function (counterName, condition) {
  4561. if (condition === void 0) { condition = true; }
  4562. if (!condition || !Tools._performance.mark) {
  4563. return;
  4564. }
  4565. Tools._performance.mark(counterName + "-Begin");
  4566. };
  4567. Tools._EndUserMark = function (counterName, condition) {
  4568. if (condition === void 0) { condition = true; }
  4569. if (!condition || !Tools._performance.mark) {
  4570. return;
  4571. }
  4572. Tools._performance.mark(counterName + "-End");
  4573. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4574. };
  4575. Tools._StartPerformanceConsole = function (counterName, condition) {
  4576. if (condition === void 0) { condition = true; }
  4577. if (!condition) {
  4578. return;
  4579. }
  4580. Tools._StartUserMark(counterName, condition);
  4581. if (console.time) {
  4582. console.time(counterName);
  4583. }
  4584. };
  4585. Tools._EndPerformanceConsole = function (counterName, condition) {
  4586. if (condition === void 0) { condition = true; }
  4587. if (!condition) {
  4588. return;
  4589. }
  4590. Tools._EndUserMark(counterName, condition);
  4591. if (console.time) {
  4592. console.timeEnd(counterName);
  4593. }
  4594. };
  4595. Object.defineProperty(Tools, "Now", {
  4596. get: function () {
  4597. if (window.performance && window.performance.now) {
  4598. return window.performance.now();
  4599. }
  4600. return new Date().getTime();
  4601. },
  4602. enumerable: true,
  4603. configurable: true
  4604. });
  4605. Tools.BaseUrl = "";
  4606. Tools.CorsBehavior = "anonymous";
  4607. // Logs
  4608. Tools._NoneLogLevel = 0;
  4609. Tools._MessageLogLevel = 1;
  4610. Tools._WarningLogLevel = 2;
  4611. Tools._ErrorLogLevel = 4;
  4612. Tools._LogCache = "";
  4613. Tools.errorsCount = 0;
  4614. Tools.Log = Tools._LogEnabled;
  4615. Tools.Warn = Tools._WarnEnabled;
  4616. Tools.Error = Tools._ErrorEnabled;
  4617. // Performances
  4618. Tools._PerformanceNoneLogLevel = 0;
  4619. Tools._PerformanceUserMarkLogLevel = 1;
  4620. Tools._PerformanceConsoleLogLevel = 2;
  4621. Tools._performance = window.performance;
  4622. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4623. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4624. return Tools;
  4625. })();
  4626. BABYLON.Tools = Tools;
  4627. /**
  4628. * An implementation of a loop for asynchronous functions.
  4629. */
  4630. var AsyncLoop = (function () {
  4631. /**
  4632. * Constroctor.
  4633. * @param iterations the number of iterations.
  4634. * @param _fn the function to run each iteration
  4635. * @param _successCallback the callback that will be called upon succesful execution
  4636. * @param offset starting offset.
  4637. */
  4638. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4639. if (offset === void 0) { offset = 0; }
  4640. this.iterations = iterations;
  4641. this._fn = _fn;
  4642. this._successCallback = _successCallback;
  4643. this.index = offset - 1;
  4644. this._done = false;
  4645. }
  4646. /**
  4647. * Execute the next iteration. Must be called after the last iteration was finished.
  4648. */
  4649. AsyncLoop.prototype.executeNext = function () {
  4650. if (!this._done) {
  4651. if (this.index + 1 < this.iterations) {
  4652. ++this.index;
  4653. this._fn(this);
  4654. }
  4655. else {
  4656. this.breakLoop();
  4657. }
  4658. }
  4659. };
  4660. /**
  4661. * Break the loop and run the success callback.
  4662. */
  4663. AsyncLoop.prototype.breakLoop = function () {
  4664. this._done = true;
  4665. this._successCallback();
  4666. };
  4667. /**
  4668. * Helper function
  4669. */
  4670. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4671. if (offset === void 0) { offset = 0; }
  4672. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4673. loop.executeNext();
  4674. return loop;
  4675. };
  4676. /**
  4677. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4678. * @param iterations total number of iterations
  4679. * @param syncedIterations number of synchronous iterations in each async iteration.
  4680. * @param fn the function to call each iteration.
  4681. * @param callback a success call back that will be called when iterating stops.
  4682. * @param breakFunction a break condition (optional)
  4683. * @param timeout timeout settings for the setTimeout function. default - 0.
  4684. * @constructor
  4685. */
  4686. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4687. if (timeout === void 0) { timeout = 0; }
  4688. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4689. if (breakFunction && breakFunction())
  4690. loop.breakLoop();
  4691. else {
  4692. setTimeout(function () {
  4693. for (var i = 0; i < syncedIterations; ++i) {
  4694. var iteration = (loop.index * syncedIterations) + i;
  4695. if (iteration >= iterations)
  4696. break;
  4697. fn(iteration);
  4698. if (breakFunction && breakFunction()) {
  4699. loop.breakLoop();
  4700. break;
  4701. }
  4702. }
  4703. loop.executeNext();
  4704. }, timeout);
  4705. }
  4706. }, callback);
  4707. };
  4708. return AsyncLoop;
  4709. })();
  4710. BABYLON.AsyncLoop = AsyncLoop;
  4711. })(BABYLON || (BABYLON = {}));
  4712. var BABYLON;
  4713. (function (BABYLON) {
  4714. var _DepthCullingState = (function () {
  4715. function _DepthCullingState() {
  4716. this._isDepthTestDirty = false;
  4717. this._isDepthMaskDirty = false;
  4718. this._isDepthFuncDirty = false;
  4719. this._isCullFaceDirty = false;
  4720. this._isCullDirty = false;
  4721. this._isZOffsetDirty = false;
  4722. }
  4723. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4724. get: function () {
  4725. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4726. },
  4727. enumerable: true,
  4728. configurable: true
  4729. });
  4730. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4731. get: function () {
  4732. return this._zOffset;
  4733. },
  4734. set: function (value) {
  4735. if (this._zOffset === value) {
  4736. return;
  4737. }
  4738. this._zOffset = value;
  4739. this._isZOffsetDirty = true;
  4740. },
  4741. enumerable: true,
  4742. configurable: true
  4743. });
  4744. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4745. get: function () {
  4746. return this._cullFace;
  4747. },
  4748. set: function (value) {
  4749. if (this._cullFace === value) {
  4750. return;
  4751. }
  4752. this._cullFace = value;
  4753. this._isCullFaceDirty = true;
  4754. },
  4755. enumerable: true,
  4756. configurable: true
  4757. });
  4758. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4759. get: function () {
  4760. return this._cull;
  4761. },
  4762. set: function (value) {
  4763. if (this._cull === value) {
  4764. return;
  4765. }
  4766. this._cull = value;
  4767. this._isCullDirty = true;
  4768. },
  4769. enumerable: true,
  4770. configurable: true
  4771. });
  4772. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4773. get: function () {
  4774. return this._depthFunc;
  4775. },
  4776. set: function (value) {
  4777. if (this._depthFunc === value) {
  4778. return;
  4779. }
  4780. this._depthFunc = value;
  4781. this._isDepthFuncDirty = true;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4787. get: function () {
  4788. return this._depthMask;
  4789. },
  4790. set: function (value) {
  4791. if (this._depthMask === value) {
  4792. return;
  4793. }
  4794. this._depthMask = value;
  4795. this._isDepthMaskDirty = true;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4801. get: function () {
  4802. return this._depthTest;
  4803. },
  4804. set: function (value) {
  4805. if (this._depthTest === value) {
  4806. return;
  4807. }
  4808. this._depthTest = value;
  4809. this._isDepthTestDirty = true;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. _DepthCullingState.prototype.reset = function () {
  4815. this._depthMask = true;
  4816. this._depthTest = true;
  4817. this._depthFunc = null;
  4818. this._cull = null;
  4819. this._cullFace = null;
  4820. this._zOffset = 0;
  4821. this._isDepthTestDirty = true;
  4822. this._isDepthMaskDirty = true;
  4823. this._isDepthFuncDirty = false;
  4824. this._isCullFaceDirty = false;
  4825. this._isCullDirty = false;
  4826. this._isZOffsetDirty = false;
  4827. };
  4828. _DepthCullingState.prototype.apply = function (gl) {
  4829. if (!this.isDirty) {
  4830. return;
  4831. }
  4832. // Cull
  4833. if (this._isCullDirty) {
  4834. if (this.cull) {
  4835. gl.enable(gl.CULL_FACE);
  4836. }
  4837. else {
  4838. gl.disable(gl.CULL_FACE);
  4839. }
  4840. this._isCullDirty = false;
  4841. }
  4842. // Cull face
  4843. if (this._isCullFaceDirty) {
  4844. gl.cullFace(this.cullFace);
  4845. this._isCullFaceDirty = false;
  4846. }
  4847. // Depth mask
  4848. if (this._isDepthMaskDirty) {
  4849. gl.depthMask(this.depthMask);
  4850. this._isDepthMaskDirty = false;
  4851. }
  4852. // Depth test
  4853. if (this._isDepthTestDirty) {
  4854. if (this.depthTest) {
  4855. gl.enable(gl.DEPTH_TEST);
  4856. }
  4857. else {
  4858. gl.disable(gl.DEPTH_TEST);
  4859. }
  4860. this._isDepthTestDirty = false;
  4861. }
  4862. // Depth func
  4863. if (this._isDepthFuncDirty) {
  4864. gl.depthFunc(this.depthFunc);
  4865. this._isDepthFuncDirty = false;
  4866. }
  4867. // zOffset
  4868. if (this._isZOffsetDirty) {
  4869. if (this.zOffset) {
  4870. gl.enable(gl.POLYGON_OFFSET_FILL);
  4871. gl.polygonOffset(this.zOffset, 0);
  4872. }
  4873. else {
  4874. gl.disable(gl.POLYGON_OFFSET_FILL);
  4875. }
  4876. this._isZOffsetDirty = false;
  4877. }
  4878. };
  4879. return _DepthCullingState;
  4880. })();
  4881. BABYLON._DepthCullingState = _DepthCullingState;
  4882. var _AlphaState = (function () {
  4883. function _AlphaState() {
  4884. this._isAlphaBlendDirty = false;
  4885. this._isBlendFunctionParametersDirty = false;
  4886. this._alphaBlend = false;
  4887. this._blendFunctionParameters = new Array(4);
  4888. }
  4889. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4890. get: function () {
  4891. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4892. },
  4893. enumerable: true,
  4894. configurable: true
  4895. });
  4896. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4897. get: function () {
  4898. return this._alphaBlend;
  4899. },
  4900. set: function (value) {
  4901. if (this._alphaBlend === value) {
  4902. return;
  4903. }
  4904. this._alphaBlend = value;
  4905. this._isAlphaBlendDirty = true;
  4906. },
  4907. enumerable: true,
  4908. configurable: true
  4909. });
  4910. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4911. if (this._blendFunctionParameters[0] === value0 &&
  4912. this._blendFunctionParameters[1] === value1 &&
  4913. this._blendFunctionParameters[2] === value2 &&
  4914. this._blendFunctionParameters[3] === value3) {
  4915. return;
  4916. }
  4917. this._blendFunctionParameters[0] = value0;
  4918. this._blendFunctionParameters[1] = value1;
  4919. this._blendFunctionParameters[2] = value2;
  4920. this._blendFunctionParameters[3] = value3;
  4921. this._isBlendFunctionParametersDirty = true;
  4922. };
  4923. _AlphaState.prototype.reset = function () {
  4924. this._alphaBlend = false;
  4925. this._blendFunctionParameters[0] = null;
  4926. this._blendFunctionParameters[1] = null;
  4927. this._blendFunctionParameters[2] = null;
  4928. this._blendFunctionParameters[3] = null;
  4929. this._isAlphaBlendDirty = true;
  4930. this._isBlendFunctionParametersDirty = false;
  4931. };
  4932. _AlphaState.prototype.apply = function (gl) {
  4933. if (!this.isDirty) {
  4934. return;
  4935. }
  4936. // Alpha blend
  4937. if (this._isAlphaBlendDirty) {
  4938. if (this._alphaBlend) {
  4939. gl.enable(gl.BLEND);
  4940. }
  4941. else {
  4942. gl.disable(gl.BLEND);
  4943. }
  4944. this._isAlphaBlendDirty = false;
  4945. }
  4946. // Alpha function
  4947. if (this._isBlendFunctionParametersDirty) {
  4948. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4949. this._isBlendFunctionParametersDirty = false;
  4950. }
  4951. };
  4952. return _AlphaState;
  4953. })();
  4954. BABYLON._AlphaState = _AlphaState;
  4955. var compileShader = function (gl, source, type, defines) {
  4956. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4957. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4958. gl.compileShader(shader);
  4959. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4960. throw new Error(gl.getShaderInfoLog(shader));
  4961. }
  4962. return shader;
  4963. };
  4964. var getWebGLTextureType = function (gl, type) {
  4965. var textureType = gl.UNSIGNED_BYTE;
  4966. if (type === Engine.TEXTURETYPE_FLOAT)
  4967. textureType = gl.FLOAT;
  4968. return textureType;
  4969. };
  4970. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4971. var magFilter = gl.NEAREST;
  4972. var minFilter = gl.NEAREST;
  4973. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4974. magFilter = gl.LINEAR;
  4975. if (generateMipMaps) {
  4976. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  4977. }
  4978. else {
  4979. minFilter = gl.LINEAR;
  4980. }
  4981. }
  4982. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4983. magFilter = gl.LINEAR;
  4984. if (generateMipMaps) {
  4985. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4986. }
  4987. else {
  4988. minFilter = gl.LINEAR;
  4989. }
  4990. }
  4991. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4992. magFilter = gl.NEAREST;
  4993. if (generateMipMaps) {
  4994. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  4995. }
  4996. else {
  4997. minFilter = gl.NEAREST;
  4998. }
  4999. }
  5000. return {
  5001. min: minFilter,
  5002. mag: magFilter
  5003. };
  5004. };
  5005. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5007. var engine = scene.getEngine();
  5008. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5009. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5010. gl.bindTexture(gl.TEXTURE_2D, texture);
  5011. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5012. texture._baseWidth = width;
  5013. texture._baseHeight = height;
  5014. texture._width = potWidth;
  5015. texture._height = potHeight;
  5016. texture.isReady = true;
  5017. processFunction(potWidth, potHeight);
  5018. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5021. if (!noMipmap && !isCompressed) {
  5022. gl.generateMipmap(gl.TEXTURE_2D);
  5023. }
  5024. gl.bindTexture(gl.TEXTURE_2D, null);
  5025. engine.resetTextureCache();
  5026. scene._removePendingData(texture);
  5027. };
  5028. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5029. var onload = function () {
  5030. loadedImages[index] = img;
  5031. loadedImages._internalCount++;
  5032. scene._removePendingData(img);
  5033. if (loadedImages._internalCount === 6) {
  5034. onfinish(loadedImages);
  5035. }
  5036. };
  5037. var onerror = function () {
  5038. scene._removePendingData(img);
  5039. };
  5040. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5041. scene._addPendingData(img);
  5042. };
  5043. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5044. var loadedImages = [];
  5045. loadedImages._internalCount = 0;
  5046. for (var index = 0; index < 6; index++) {
  5047. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5048. }
  5049. };
  5050. var EngineCapabilities = (function () {
  5051. function EngineCapabilities() {
  5052. }
  5053. return EngineCapabilities;
  5054. })();
  5055. BABYLON.EngineCapabilities = EngineCapabilities;
  5056. /**
  5057. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5058. */
  5059. var Engine = (function () {
  5060. /**
  5061. * @constructor
  5062. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5063. * @param {boolean} [antialias] - enable antialias
  5064. * @param options - further options to be sent to the getContext function
  5065. */
  5066. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5067. var _this = this;
  5068. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5069. // Public members
  5070. this.isFullscreen = false;
  5071. this.isPointerLock = false;
  5072. this.cullBackFaces = true;
  5073. this.renderEvenInBackground = true;
  5074. // To enable/disable IDB support and avoid XHR on .manifest
  5075. this.enableOfflineSupport = true;
  5076. this.scenes = new Array();
  5077. this._windowIsBackground = false;
  5078. this._drawCalls = 0;
  5079. this._renderingQueueLaunched = false;
  5080. this._activeRenderLoops = [];
  5081. // FPS
  5082. this.fpsRange = 60;
  5083. this.previousFramesDuration = [];
  5084. this.fps = 60;
  5085. this.deltaTime = 0;
  5086. // States
  5087. this._depthCullingState = new _DepthCullingState();
  5088. this._alphaState = new _AlphaState();
  5089. this._alphaMode = Engine.ALPHA_DISABLE;
  5090. // Cache
  5091. this._loadedTexturesCache = new Array();
  5092. this._maxTextureChannels = 16;
  5093. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5094. this._compiledEffects = {};
  5095. this._uintIndicesCurrentlySet = false;
  5096. this._renderingCanvas = canvas;
  5097. options = options || {};
  5098. options.antialias = antialias;
  5099. if (options.preserveDrawingBuffer === undefined) {
  5100. options.preserveDrawingBuffer = false;
  5101. }
  5102. // GL
  5103. try {
  5104. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5105. }
  5106. catch (e) {
  5107. throw new Error("WebGL not supported");
  5108. }
  5109. if (!this._gl) {
  5110. throw new Error("WebGL not supported");
  5111. }
  5112. this._onBlur = function () {
  5113. _this._windowIsBackground = true;
  5114. };
  5115. this._onFocus = function () {
  5116. _this._windowIsBackground = false;
  5117. };
  5118. window.addEventListener("blur", this._onBlur);
  5119. window.addEventListener("focus", this._onFocus);
  5120. // Viewport
  5121. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5122. this.resize();
  5123. // Caps
  5124. this._caps = new EngineCapabilities();
  5125. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5126. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5127. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5128. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5129. // Infos
  5130. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5131. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5132. if (rendererInfo != null) {
  5133. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5134. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5135. }
  5136. if (!this._glVendor) {
  5137. this._glVendor = "Unknown vendor";
  5138. }
  5139. if (!this._glRenderer) {
  5140. this._glRenderer = "Unknown renderer";
  5141. }
  5142. // Extensions
  5143. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5144. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5145. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5146. 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');
  5147. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5148. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5149. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5150. this._caps.highPrecisionShaderSupported = true;
  5151. if (this._gl.getShaderPrecisionFormat) {
  5152. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5153. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5154. }
  5155. // Depth buffer
  5156. this.setDepthBuffer(true);
  5157. this.setDepthFunctionToLessOrEqual();
  5158. this.setDepthWrite(true);
  5159. // Fullscreen
  5160. this._onFullscreenChange = function () {
  5161. if (document.fullscreen !== undefined) {
  5162. _this.isFullscreen = document.fullscreen;
  5163. }
  5164. else if (document.mozFullScreen !== undefined) {
  5165. _this.isFullscreen = document.mozFullScreen;
  5166. }
  5167. else if (document.webkitIsFullScreen !== undefined) {
  5168. _this.isFullscreen = document.webkitIsFullScreen;
  5169. }
  5170. else if (document.msIsFullScreen !== undefined) {
  5171. _this.isFullscreen = document.msIsFullScreen;
  5172. }
  5173. // Pointer lock
  5174. if (_this.isFullscreen && _this._pointerLockRequested) {
  5175. canvas.requestPointerLock = canvas.requestPointerLock ||
  5176. canvas.msRequestPointerLock ||
  5177. canvas.mozRequestPointerLock ||
  5178. canvas.webkitRequestPointerLock;
  5179. if (canvas.requestPointerLock) {
  5180. canvas.requestPointerLock();
  5181. }
  5182. }
  5183. };
  5184. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5185. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5186. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5187. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5188. // Pointer lock
  5189. this._onPointerLockChange = function () {
  5190. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5191. document.webkitPointerLockElement === canvas ||
  5192. document.msPointerLockElement === canvas ||
  5193. document.pointerLockElement === canvas);
  5194. };
  5195. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5196. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5197. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5198. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5199. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5200. Engine.audioEngine = new BABYLON.AudioEngine();
  5201. }
  5202. //default loading screen
  5203. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5204. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5205. }
  5206. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5207. get: function () {
  5208. return Engine._ALPHA_DISABLE;
  5209. },
  5210. enumerable: true,
  5211. configurable: true
  5212. });
  5213. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5214. get: function () {
  5215. return Engine._ALPHA_ONEONE;
  5216. },
  5217. enumerable: true,
  5218. configurable: true
  5219. });
  5220. Object.defineProperty(Engine, "ALPHA_ADD", {
  5221. get: function () {
  5222. return Engine._ALPHA_ADD;
  5223. },
  5224. enumerable: true,
  5225. configurable: true
  5226. });
  5227. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5228. get: function () {
  5229. return Engine._ALPHA_COMBINE;
  5230. },
  5231. enumerable: true,
  5232. configurable: true
  5233. });
  5234. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5235. get: function () {
  5236. return Engine._ALPHA_SUBTRACT;
  5237. },
  5238. enumerable: true,
  5239. configurable: true
  5240. });
  5241. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5242. get: function () {
  5243. return Engine._ALPHA_MULTIPLY;
  5244. },
  5245. enumerable: true,
  5246. configurable: true
  5247. });
  5248. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5249. get: function () {
  5250. return Engine._ALPHA_MAXIMIZED;
  5251. },
  5252. enumerable: true,
  5253. configurable: true
  5254. });
  5255. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5256. get: function () {
  5257. return Engine._DELAYLOADSTATE_NONE;
  5258. },
  5259. enumerable: true,
  5260. configurable: true
  5261. });
  5262. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5263. get: function () {
  5264. return Engine._DELAYLOADSTATE_LOADED;
  5265. },
  5266. enumerable: true,
  5267. configurable: true
  5268. });
  5269. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5270. get: function () {
  5271. return Engine._DELAYLOADSTATE_LOADING;
  5272. },
  5273. enumerable: true,
  5274. configurable: true
  5275. });
  5276. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5277. get: function () {
  5278. return Engine._DELAYLOADSTATE_NOTLOADED;
  5279. },
  5280. enumerable: true,
  5281. configurable: true
  5282. });
  5283. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5284. get: function () {
  5285. return Engine._TEXTUREFORMAT_ALPHA;
  5286. },
  5287. enumerable: true,
  5288. configurable: true
  5289. });
  5290. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5291. get: function () {
  5292. return Engine._TEXTUREFORMAT_LUMINANCE;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5298. get: function () {
  5299. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5300. },
  5301. enumerable: true,
  5302. configurable: true
  5303. });
  5304. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5305. get: function () {
  5306. return Engine._TEXTUREFORMAT_RGB;
  5307. },
  5308. enumerable: true,
  5309. configurable: true
  5310. });
  5311. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5312. get: function () {
  5313. return Engine._TEXTUREFORMAT_RGBA;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5319. get: function () {
  5320. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5321. },
  5322. enumerable: true,
  5323. configurable: true
  5324. });
  5325. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5326. get: function () {
  5327. return Engine._TEXTURETYPE_FLOAT;
  5328. },
  5329. enumerable: true,
  5330. configurable: true
  5331. });
  5332. Object.defineProperty(Engine, "Version", {
  5333. get: function () {
  5334. return "2.3.0-alpha";
  5335. },
  5336. enumerable: true,
  5337. configurable: true
  5338. });
  5339. Engine.prototype._prepareWorkingCanvas = function () {
  5340. if (this._workingCanvas) {
  5341. return;
  5342. }
  5343. this._workingCanvas = document.createElement("canvas");
  5344. this._workingContext = this._workingCanvas.getContext("2d");
  5345. };
  5346. Engine.prototype.resetTextureCache = function () {
  5347. for (var index = 0; index < this._maxTextureChannels; index++) {
  5348. this._activeTexturesCache[index] = null;
  5349. }
  5350. };
  5351. Engine.prototype.getGlInfo = function () {
  5352. return {
  5353. vendor: this._glVendor,
  5354. renderer: this._glRenderer,
  5355. version: this._glVersion
  5356. };
  5357. };
  5358. Engine.prototype.getAspectRatio = function (camera) {
  5359. var viewport = camera.viewport;
  5360. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5361. };
  5362. Engine.prototype.getRenderWidth = function () {
  5363. if (this._currentRenderTarget) {
  5364. return this._currentRenderTarget._width;
  5365. }
  5366. return this._renderingCanvas.width;
  5367. };
  5368. Engine.prototype.getRenderHeight = function () {
  5369. if (this._currentRenderTarget) {
  5370. return this._currentRenderTarget._height;
  5371. }
  5372. return this._renderingCanvas.height;
  5373. };
  5374. Engine.prototype.getRenderingCanvas = function () {
  5375. return this._renderingCanvas;
  5376. };
  5377. Engine.prototype.getRenderingCanvasClientRect = function () {
  5378. return this._renderingCanvas.getBoundingClientRect();
  5379. };
  5380. Engine.prototype.setHardwareScalingLevel = function (level) {
  5381. this._hardwareScalingLevel = level;
  5382. this.resize();
  5383. };
  5384. Engine.prototype.getHardwareScalingLevel = function () {
  5385. return this._hardwareScalingLevel;
  5386. };
  5387. Engine.prototype.getLoadedTexturesCache = function () {
  5388. return this._loadedTexturesCache;
  5389. };
  5390. Engine.prototype.getCaps = function () {
  5391. return this._caps;
  5392. };
  5393. Object.defineProperty(Engine.prototype, "drawCalls", {
  5394. get: function () {
  5395. return this._drawCalls;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. // Methods
  5401. Engine.prototype.resetDrawCalls = function () {
  5402. this._drawCalls = 0;
  5403. };
  5404. Engine.prototype.setDepthFunctionToGreater = function () {
  5405. this._depthCullingState.depthFunc = this._gl.GREATER;
  5406. };
  5407. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5408. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5409. };
  5410. Engine.prototype.setDepthFunctionToLess = function () {
  5411. this._depthCullingState.depthFunc = this._gl.LESS;
  5412. };
  5413. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5414. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5415. };
  5416. /**
  5417. * stop executing a render loop function and remove it from the execution array
  5418. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5419. */
  5420. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5421. if (!renderFunction) {
  5422. this._activeRenderLoops = [];
  5423. return;
  5424. }
  5425. var index = this._activeRenderLoops.indexOf(renderFunction);
  5426. if (index >= 0) {
  5427. this._activeRenderLoops.splice(index, 1);
  5428. }
  5429. };
  5430. Engine.prototype._renderLoop = function () {
  5431. var shouldRender = true;
  5432. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5433. shouldRender = false;
  5434. }
  5435. if (shouldRender) {
  5436. // Start new frame
  5437. this.beginFrame();
  5438. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5439. var renderFunction = this._activeRenderLoops[index];
  5440. renderFunction();
  5441. }
  5442. // Present
  5443. this.endFrame();
  5444. }
  5445. if (this._activeRenderLoops.length > 0) {
  5446. // Register new frame
  5447. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5448. }
  5449. else {
  5450. this._renderingQueueLaunched = false;
  5451. }
  5452. };
  5453. /**
  5454. * Register and execute a render loop. The engine can have more than one render function.
  5455. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5456. * @example
  5457. * engine.runRenderLoop(function () {
  5458. * scene.render()
  5459. * })
  5460. */
  5461. Engine.prototype.runRenderLoop = function (renderFunction) {
  5462. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5463. return;
  5464. }
  5465. this._activeRenderLoops.push(renderFunction);
  5466. if (!this._renderingQueueLaunched) {
  5467. this._renderingQueueLaunched = true;
  5468. this._bindedRenderFunction = this._renderLoop.bind(this);
  5469. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5470. }
  5471. };
  5472. /**
  5473. * Toggle full screen mode.
  5474. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5475. */
  5476. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5477. if (this.isFullscreen) {
  5478. BABYLON.Tools.ExitFullscreen();
  5479. }
  5480. else {
  5481. this._pointerLockRequested = requestPointerLock;
  5482. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5483. }
  5484. };
  5485. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5486. this.applyStates();
  5487. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5488. if (this._depthCullingState.depthMask) {
  5489. this._gl.clearDepth(1.0);
  5490. }
  5491. var mode = 0;
  5492. if (backBuffer)
  5493. mode |= this._gl.COLOR_BUFFER_BIT;
  5494. if (depthStencil && this._depthCullingState.depthMask)
  5495. mode |= this._gl.DEPTH_BUFFER_BIT;
  5496. this._gl.clear(mode);
  5497. };
  5498. /**
  5499. * Set the WebGL's viewport
  5500. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5501. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5502. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5503. */
  5504. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5505. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5506. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5507. var x = viewport.x || 0;
  5508. var y = viewport.y || 0;
  5509. this._cachedViewport = viewport;
  5510. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5511. };
  5512. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5513. this._cachedViewport = null;
  5514. this._gl.viewport(x, y, width, height);
  5515. };
  5516. Engine.prototype.beginFrame = function () {
  5517. this._measureFps();
  5518. };
  5519. Engine.prototype.endFrame = function () {
  5520. //this.flushFramebuffer();
  5521. };
  5522. /**
  5523. * resize the view according to the canvas' size.
  5524. * @example
  5525. * window.addEventListener("resize", function () {
  5526. * engine.resize();
  5527. * });
  5528. */
  5529. Engine.prototype.resize = function () {
  5530. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5531. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5532. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5533. for (var index = 0; index < this.scenes.length; index++) {
  5534. var scene = this.scenes[index];
  5535. if (scene.debugLayer.isVisible()) {
  5536. scene.debugLayer._syncPositions();
  5537. }
  5538. }
  5539. };
  5540. /**
  5541. * force a specific size of the canvas
  5542. * @param {number} width - the new canvas' width
  5543. * @param {number} height - the new canvas' height
  5544. */
  5545. Engine.prototype.setSize = function (width, height) {
  5546. this._renderingCanvas.width = width;
  5547. this._renderingCanvas.height = height;
  5548. for (var index = 0; index < this.scenes.length; index++) {
  5549. var scene = this.scenes[index];
  5550. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5551. var cam = scene.cameras[camIndex];
  5552. cam._currentRenderId = 0;
  5553. }
  5554. }
  5555. };
  5556. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5557. this._currentRenderTarget = texture;
  5558. var gl = this._gl;
  5559. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5560. if (texture.isCube) {
  5561. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5562. }
  5563. else {
  5564. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5565. }
  5566. this._gl.viewport(0, 0, texture._width, texture._height);
  5567. this.wipeCaches();
  5568. };
  5569. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5570. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5571. this._currentRenderTarget = null;
  5572. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5573. var gl = this._gl;
  5574. gl.bindTexture(gl.TEXTURE_2D, texture);
  5575. gl.generateMipmap(gl.TEXTURE_2D);
  5576. gl.bindTexture(gl.TEXTURE_2D, null);
  5577. }
  5578. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5579. };
  5580. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5581. if (texture.generateMipMaps) {
  5582. var gl = this._gl;
  5583. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5584. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5585. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5586. }
  5587. };
  5588. Engine.prototype.flushFramebuffer = function () {
  5589. this._gl.flush();
  5590. };
  5591. Engine.prototype.restoreDefaultFramebuffer = function () {
  5592. this._currentRenderTarget = null;
  5593. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5594. this.setViewport(this._cachedViewport);
  5595. this.wipeCaches();
  5596. };
  5597. // VBOs
  5598. Engine.prototype._resetVertexBufferBinding = function () {
  5599. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5600. this._cachedVertexBuffers = null;
  5601. };
  5602. Engine.prototype.createVertexBuffer = function (vertices) {
  5603. var vbo = this._gl.createBuffer();
  5604. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5605. if (vertices instanceof Float32Array) {
  5606. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5607. }
  5608. else {
  5609. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5610. }
  5611. this._resetVertexBufferBinding();
  5612. vbo.references = 1;
  5613. return vbo;
  5614. };
  5615. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5616. var vbo = this._gl.createBuffer();
  5617. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5619. this._resetVertexBufferBinding();
  5620. vbo.references = 1;
  5621. return vbo;
  5622. };
  5623. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5624. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5625. if (offset === undefined) {
  5626. offset = 0;
  5627. }
  5628. if (vertices instanceof Float32Array) {
  5629. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5630. }
  5631. else {
  5632. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5633. }
  5634. this._resetVertexBufferBinding();
  5635. };
  5636. Engine.prototype._resetIndexBufferBinding = function () {
  5637. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5638. this._cachedIndexBuffer = null;
  5639. };
  5640. Engine.prototype.createIndexBuffer = function (indices) {
  5641. var vbo = this._gl.createBuffer();
  5642. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5643. // Check for 32 bits indices
  5644. var arrayBuffer;
  5645. var need32Bits = false;
  5646. if (this._caps.uintIndices) {
  5647. for (var index = 0; index < indices.length; index++) {
  5648. if (indices[index] > 65535) {
  5649. need32Bits = true;
  5650. break;
  5651. }
  5652. }
  5653. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5654. }
  5655. else {
  5656. arrayBuffer = new Uint16Array(indices);
  5657. }
  5658. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5659. this._resetIndexBufferBinding();
  5660. vbo.references = 1;
  5661. vbo.is32Bits = need32Bits;
  5662. return vbo;
  5663. };
  5664. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5665. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5666. this._cachedVertexBuffers = vertexBuffer;
  5667. this._cachedEffectForVertexBuffers = effect;
  5668. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5669. var offset = 0;
  5670. for (var index = 0; index < vertexDeclaration.length; index++) {
  5671. var order = effect.getAttributeLocation(index);
  5672. if (order >= 0) {
  5673. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5674. }
  5675. offset += vertexDeclaration[index] * 4;
  5676. }
  5677. }
  5678. if (this._cachedIndexBuffer !== indexBuffer) {
  5679. this._cachedIndexBuffer = indexBuffer;
  5680. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5681. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5682. }
  5683. };
  5684. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5685. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5686. this._cachedVertexBuffers = vertexBuffers;
  5687. this._cachedEffectForVertexBuffers = effect;
  5688. var attributes = effect.getAttributesNames();
  5689. for (var index = 0; index < attributes.length; index++) {
  5690. var order = effect.getAttributeLocation(index);
  5691. if (order >= 0) {
  5692. var vertexBuffer = vertexBuffers[attributes[index]];
  5693. if (!vertexBuffer) {
  5694. continue;
  5695. }
  5696. var stride = vertexBuffer.getStrideSize();
  5697. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5698. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5699. }
  5700. }
  5701. }
  5702. if (indexBuffer != null && 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._releaseBuffer = function (buffer) {
  5709. buffer.references--;
  5710. if (buffer.references === 0) {
  5711. this._gl.deleteBuffer(buffer);
  5712. return true;
  5713. }
  5714. return false;
  5715. };
  5716. Engine.prototype.createInstancesBuffer = function (capacity) {
  5717. var buffer = this._gl.createBuffer();
  5718. buffer.capacity = capacity;
  5719. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5720. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5721. return buffer;
  5722. };
  5723. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5724. this._gl.deleteBuffer(buffer);
  5725. };
  5726. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5728. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5729. for (var index = 0; index < 4; index++) {
  5730. var offsetLocation = offsetLocations[index];
  5731. this._gl.enableVertexAttribArray(offsetLocation);
  5732. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5733. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5734. }
  5735. };
  5736. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5737. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5738. for (var index = 0; index < 4; index++) {
  5739. var offsetLocation = offsetLocations[index];
  5740. this._gl.disableVertexAttribArray(offsetLocation);
  5741. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5742. }
  5743. };
  5744. Engine.prototype.applyStates = function () {
  5745. this._depthCullingState.apply(this._gl);
  5746. this._alphaState.apply(this._gl);
  5747. };
  5748. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5749. // Apply states
  5750. this.applyStates();
  5751. this._drawCalls++;
  5752. // Render
  5753. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5754. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5755. if (instancesCount) {
  5756. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5757. return;
  5758. }
  5759. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5760. };
  5761. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5762. // Apply states
  5763. this.applyStates();
  5764. this._drawCalls++;
  5765. if (instancesCount) {
  5766. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5767. return;
  5768. }
  5769. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5770. };
  5771. // Shaders
  5772. Engine.prototype._releaseEffect = function (effect) {
  5773. if (this._compiledEffects[effect._key]) {
  5774. delete this._compiledEffects[effect._key];
  5775. if (effect.getProgram()) {
  5776. this._gl.deleteProgram(effect.getProgram());
  5777. }
  5778. }
  5779. };
  5780. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5781. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5782. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5783. var name = vertex + "+" + fragment + "@" + defines;
  5784. if (this._compiledEffects[name]) {
  5785. return this._compiledEffects[name];
  5786. }
  5787. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5788. effect._key = name;
  5789. this._compiledEffects[name] = effect;
  5790. return effect;
  5791. };
  5792. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5793. if (uniformsNames === void 0) { uniformsNames = []; }
  5794. if (samplers === void 0) { samplers = []; }
  5795. if (defines === void 0) { defines = ""; }
  5796. return this.createEffect({
  5797. vertex: "particles",
  5798. fragmentElement: fragmentName
  5799. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5800. };
  5801. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5802. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5803. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5804. var shaderProgram = this._gl.createProgram();
  5805. this._gl.attachShader(shaderProgram, vertexShader);
  5806. this._gl.attachShader(shaderProgram, fragmentShader);
  5807. this._gl.linkProgram(shaderProgram);
  5808. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5809. if (!linked) {
  5810. var error = this._gl.getProgramInfoLog(shaderProgram);
  5811. if (error) {
  5812. throw new Error(error);
  5813. }
  5814. }
  5815. this._gl.deleteShader(vertexShader);
  5816. this._gl.deleteShader(fragmentShader);
  5817. return shaderProgram;
  5818. };
  5819. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5820. var results = [];
  5821. for (var index = 0; index < uniformsNames.length; index++) {
  5822. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5823. }
  5824. return results;
  5825. };
  5826. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5827. var results = [];
  5828. for (var index = 0; index < attributesNames.length; index++) {
  5829. try {
  5830. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5831. }
  5832. catch (e) {
  5833. results.push(-1);
  5834. }
  5835. }
  5836. return results;
  5837. };
  5838. Engine.prototype.enableEffect = function (effect) {
  5839. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5840. if (effect && effect.onBind) {
  5841. effect.onBind(effect);
  5842. }
  5843. return;
  5844. }
  5845. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5846. // Use program
  5847. this._gl.useProgram(effect.getProgram());
  5848. for (var i in this._vertexAttribArrays) {
  5849. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5850. continue;
  5851. }
  5852. this._vertexAttribArrays[i] = false;
  5853. this._gl.disableVertexAttribArray(i);
  5854. }
  5855. var attributesCount = effect.getAttributesCount();
  5856. for (var index = 0; index < attributesCount; index++) {
  5857. // Attributes
  5858. var order = effect.getAttributeLocation(index);
  5859. if (order >= 0) {
  5860. this._vertexAttribArrays[order] = true;
  5861. this._gl.enableVertexAttribArray(order);
  5862. }
  5863. }
  5864. this._currentEffect = effect;
  5865. if (effect.onBind) {
  5866. effect.onBind(effect);
  5867. }
  5868. };
  5869. Engine.prototype.setArray = function (uniform, array) {
  5870. if (!uniform)
  5871. return;
  5872. this._gl.uniform1fv(uniform, array);
  5873. };
  5874. Engine.prototype.setArray2 = function (uniform, array) {
  5875. if (!uniform || array.length % 2 !== 0)
  5876. return;
  5877. this._gl.uniform2fv(uniform, array);
  5878. };
  5879. Engine.prototype.setArray3 = function (uniform, array) {
  5880. if (!uniform || array.length % 3 !== 0)
  5881. return;
  5882. this._gl.uniform3fv(uniform, array);
  5883. };
  5884. Engine.prototype.setArray4 = function (uniform, array) {
  5885. if (!uniform || array.length % 4 !== 0)
  5886. return;
  5887. this._gl.uniform4fv(uniform, array);
  5888. };
  5889. Engine.prototype.setMatrices = function (uniform, matrices) {
  5890. if (!uniform)
  5891. return;
  5892. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5893. };
  5894. Engine.prototype.setMatrix = function (uniform, matrix) {
  5895. if (!uniform)
  5896. return;
  5897. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5898. };
  5899. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5900. if (!uniform)
  5901. return;
  5902. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5903. };
  5904. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5905. if (!uniform)
  5906. return;
  5907. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5908. };
  5909. Engine.prototype.setFloat = function (uniform, value) {
  5910. if (!uniform)
  5911. return;
  5912. this._gl.uniform1f(uniform, value);
  5913. };
  5914. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5915. if (!uniform)
  5916. return;
  5917. this._gl.uniform2f(uniform, x, y);
  5918. };
  5919. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5920. if (!uniform)
  5921. return;
  5922. this._gl.uniform3f(uniform, x, y, z);
  5923. };
  5924. Engine.prototype.setBool = function (uniform, bool) {
  5925. if (!uniform)
  5926. return;
  5927. this._gl.uniform1i(uniform, bool);
  5928. };
  5929. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5930. if (!uniform)
  5931. return;
  5932. this._gl.uniform4f(uniform, x, y, z, w);
  5933. };
  5934. Engine.prototype.setColor3 = function (uniform, color3) {
  5935. if (!uniform)
  5936. return;
  5937. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5938. };
  5939. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5940. if (!uniform)
  5941. return;
  5942. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5943. };
  5944. // States
  5945. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5946. if (zOffset === void 0) { zOffset = 0; }
  5947. if (reverseSide === void 0) { reverseSide = false; }
  5948. // Culling
  5949. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5950. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5951. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5952. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5953. if (culling) {
  5954. this._depthCullingState.cullFace = cullFace;
  5955. this._depthCullingState.cull = true;
  5956. }
  5957. else {
  5958. this._depthCullingState.cull = false;
  5959. }
  5960. }
  5961. // Z offset
  5962. this._depthCullingState.zOffset = zOffset;
  5963. };
  5964. Engine.prototype.setDepthBuffer = function (enable) {
  5965. this._depthCullingState.depthTest = enable;
  5966. };
  5967. Engine.prototype.getDepthWrite = function () {
  5968. return this._depthCullingState.depthMask;
  5969. };
  5970. Engine.prototype.setDepthWrite = function (enable) {
  5971. this._depthCullingState.depthMask = enable;
  5972. };
  5973. Engine.prototype.setColorWrite = function (enable) {
  5974. this._gl.colorMask(enable, enable, enable, enable);
  5975. };
  5976. Engine.prototype.setAlphaMode = function (mode) {
  5977. if (this._alphaMode === mode) {
  5978. return;
  5979. }
  5980. switch (mode) {
  5981. case Engine.ALPHA_DISABLE:
  5982. this.setDepthWrite(true);
  5983. this._alphaState.alphaBlend = false;
  5984. break;
  5985. case Engine.ALPHA_COMBINE:
  5986. this.setDepthWrite(false);
  5987. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  5988. this._alphaState.alphaBlend = true;
  5989. break;
  5990. case Engine.ALPHA_ONEONE:
  5991. this.setDepthWrite(false);
  5992. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5993. this._alphaState.alphaBlend = true;
  5994. break;
  5995. case Engine.ALPHA_ADD:
  5996. this.setDepthWrite(false);
  5997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5998. this._alphaState.alphaBlend = true;
  5999. break;
  6000. case Engine.ALPHA_SUBTRACT:
  6001. this.setDepthWrite(false);
  6002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6003. this._alphaState.alphaBlend = true;
  6004. break;
  6005. case Engine.ALPHA_MULTIPLY:
  6006. this.setDepthWrite(false);
  6007. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6008. this._alphaState.alphaBlend = true;
  6009. break;
  6010. case Engine.ALPHA_MAXIMIZED:
  6011. this.setDepthWrite(false);
  6012. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6013. this._alphaState.alphaBlend = true;
  6014. break;
  6015. }
  6016. this._alphaMode = mode;
  6017. };
  6018. Engine.prototype.getAlphaMode = function () {
  6019. return this._alphaMode;
  6020. };
  6021. Engine.prototype.setAlphaTesting = function (enable) {
  6022. this._alphaTest = enable;
  6023. };
  6024. Engine.prototype.getAlphaTesting = function () {
  6025. return this._alphaTest;
  6026. };
  6027. // Textures
  6028. Engine.prototype.wipeCaches = function () {
  6029. this.resetTextureCache();
  6030. this._currentEffect = null;
  6031. this._depthCullingState.reset();
  6032. this._alphaState.reset();
  6033. this._cachedVertexBuffers = null;
  6034. this._cachedIndexBuffer = null;
  6035. this._cachedEffectForVertexBuffers = null;
  6036. };
  6037. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6038. var gl = this._gl;
  6039. gl.bindTexture(gl.TEXTURE_2D, texture);
  6040. var magFilter = gl.NEAREST;
  6041. var minFilter = gl.NEAREST;
  6042. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6043. magFilter = gl.LINEAR;
  6044. minFilter = gl.LINEAR;
  6045. }
  6046. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6047. magFilter = gl.LINEAR;
  6048. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6049. }
  6050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6052. gl.bindTexture(gl.TEXTURE_2D, null);
  6053. texture.samplingMode = samplingMode;
  6054. };
  6055. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6056. var _this = this;
  6057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6058. if (onLoad === void 0) { onLoad = null; }
  6059. if (onError === void 0) { onError = null; }
  6060. if (buffer === void 0) { buffer = null; }
  6061. var texture = this._gl.createTexture();
  6062. var extension;
  6063. var fromData = false;
  6064. if (url.substr(0, 5) === "data:") {
  6065. fromData = true;
  6066. }
  6067. if (!fromData)
  6068. extension = url.substr(url.length - 4, 4).toLowerCase();
  6069. else {
  6070. var oldUrl = url;
  6071. fromData = oldUrl.split(':');
  6072. url = oldUrl;
  6073. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6074. }
  6075. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6076. var isTGA = (extension === ".tga");
  6077. scene._addPendingData(texture);
  6078. texture.url = url;
  6079. texture.noMipmap = noMipmap;
  6080. texture.references = 1;
  6081. texture.samplingMode = samplingMode;
  6082. this._loadedTexturesCache.push(texture);
  6083. var onerror = function () {
  6084. scene._removePendingData(texture);
  6085. if (onError) {
  6086. onError();
  6087. }
  6088. };
  6089. var callback;
  6090. if (isTGA) {
  6091. callback = function (arrayBuffer) {
  6092. var data = new Uint8Array(arrayBuffer);
  6093. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6094. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6095. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6096. if (onLoad) {
  6097. onLoad();
  6098. }
  6099. }, samplingMode);
  6100. };
  6101. if (!(fromData instanceof Array))
  6102. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6103. callback(arrayBuffer);
  6104. }, onerror, scene.database, true);
  6105. else
  6106. callback(buffer);
  6107. }
  6108. else if (isDDS) {
  6109. callback = function (data) {
  6110. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6111. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6112. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6113. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6114. if (onLoad) {
  6115. onLoad();
  6116. }
  6117. }, samplingMode);
  6118. };
  6119. if (!(fromData instanceof Array))
  6120. BABYLON.Tools.LoadFile(url, function (data) {
  6121. callback(data);
  6122. }, onerror, scene.database, true);
  6123. else
  6124. callback(buffer);
  6125. }
  6126. else {
  6127. var onload = function (img) {
  6128. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6129. var isPot = (img.width === potWidth && img.height === potHeight);
  6130. if (!isPot) {
  6131. _this._prepareWorkingCanvas();
  6132. _this._workingCanvas.width = potWidth;
  6133. _this._workingCanvas.height = potHeight;
  6134. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6135. _this._workingContext.imageSmoothingEnabled = false;
  6136. _this._workingContext.mozImageSmoothingEnabled = false;
  6137. _this._workingContext.oImageSmoothingEnabled = false;
  6138. _this._workingContext.webkitImageSmoothingEnabled = false;
  6139. _this._workingContext.msImageSmoothingEnabled = false;
  6140. }
  6141. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6142. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6143. _this._workingContext.imageSmoothingEnabled = true;
  6144. _this._workingContext.mozImageSmoothingEnabled = true;
  6145. _this._workingContext.oImageSmoothingEnabled = true;
  6146. _this._workingContext.webkitImageSmoothingEnabled = true;
  6147. _this._workingContext.msImageSmoothingEnabled = true;
  6148. }
  6149. }
  6150. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6151. if (onLoad) {
  6152. onLoad();
  6153. }
  6154. }, samplingMode);
  6155. };
  6156. if (!(fromData instanceof Array))
  6157. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6158. else
  6159. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6160. }
  6161. return texture;
  6162. };
  6163. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6164. if (compression === void 0) { compression = null; }
  6165. var internalFormat = this._gl.RGBA;
  6166. switch (format) {
  6167. case Engine.TEXTUREFORMAT_ALPHA:
  6168. internalFormat = this._gl.ALPHA;
  6169. break;
  6170. case Engine.TEXTUREFORMAT_LUMINANCE:
  6171. internalFormat = this._gl.LUMINANCE;
  6172. break;
  6173. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6174. internalFormat = this._gl.LUMINANCE_ALPHA;
  6175. break;
  6176. case Engine.TEXTUREFORMAT_RGB:
  6177. internalFormat = this._gl.RGB;
  6178. break;
  6179. case Engine.TEXTUREFORMAT_RGBA:
  6180. internalFormat = this._gl.RGBA;
  6181. break;
  6182. }
  6183. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6184. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6185. if (compression) {
  6186. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6187. }
  6188. else {
  6189. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6190. }
  6191. if (texture.generateMipMaps) {
  6192. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6193. }
  6194. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6195. this.resetTextureCache();
  6196. texture.isReady = true;
  6197. };
  6198. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6199. if (compression === void 0) { compression = null; }
  6200. var texture = this._gl.createTexture();
  6201. texture._baseWidth = width;
  6202. texture._baseHeight = height;
  6203. texture._width = width;
  6204. texture._height = height;
  6205. texture.references = 1;
  6206. this.updateRawTexture(texture, data, format, invertY, compression);
  6207. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6208. // Filters
  6209. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6211. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6212. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6213. texture.samplingMode = samplingMode;
  6214. this._loadedTexturesCache.push(texture);
  6215. return texture;
  6216. };
  6217. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6218. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6219. var texture = this._gl.createTexture();
  6220. texture._baseWidth = width;
  6221. texture._baseHeight = height;
  6222. if (forceExponantOfTwo) {
  6223. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6224. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6225. }
  6226. this.resetTextureCache();
  6227. texture._width = width;
  6228. texture._height = height;
  6229. texture.isReady = false;
  6230. texture.generateMipMaps = generateMipMaps;
  6231. texture.references = 1;
  6232. texture.samplingMode = samplingMode;
  6233. this.updateTextureSamplingMode(samplingMode, texture);
  6234. this._loadedTexturesCache.push(texture);
  6235. return texture;
  6236. };
  6237. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6238. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6239. if (texture.isCube) {
  6240. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6241. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6242. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6243. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6244. }
  6245. else {
  6246. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6248. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6249. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6250. }
  6251. };
  6252. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6253. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6254. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6255. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6256. if (texture.generateMipMaps) {
  6257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6258. }
  6259. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6260. this.resetTextureCache();
  6261. texture.isReady = true;
  6262. };
  6263. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6264. if (texture._isDisabled) {
  6265. return;
  6266. }
  6267. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6268. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6269. try {
  6270. // Testing video texture support
  6271. if (this._videoTextureSupported === undefined) {
  6272. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6273. if (this._gl.getError() !== 0) {
  6274. this._videoTextureSupported = false;
  6275. }
  6276. else {
  6277. this._videoTextureSupported = true;
  6278. }
  6279. }
  6280. // Copy video through the current working canvas if video texture is not supported
  6281. if (!this._videoTextureSupported) {
  6282. if (!texture._workingCanvas) {
  6283. texture._workingCanvas = document.createElement("canvas");
  6284. texture._workingContext = texture._workingCanvas.getContext("2d");
  6285. texture._workingCanvas.width = texture._width;
  6286. texture._workingCanvas.height = texture._height;
  6287. }
  6288. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6289. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6290. }
  6291. else {
  6292. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6293. }
  6294. if (texture.generateMipMaps) {
  6295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6296. }
  6297. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6298. this.resetTextureCache();
  6299. texture.isReady = true;
  6300. }
  6301. catch (ex) {
  6302. // Something unexpected
  6303. // Let's disable the texture
  6304. texture._isDisabled = true;
  6305. }
  6306. };
  6307. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6308. // old version had a "generateMipMaps" arg instead of options.
  6309. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6310. // in the same way, generateDepthBuffer is defaulted to true
  6311. var generateMipMaps = false;
  6312. var generateDepthBuffer = true;
  6313. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6314. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6315. if (options !== undefined) {
  6316. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6317. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6318. type = options.type === undefined ? type : options.type;
  6319. if (options.samplingMode !== undefined) {
  6320. samplingMode = options.samplingMode;
  6321. }
  6322. if (type === Engine.TEXTURETYPE_FLOAT) {
  6323. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6324. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6325. }
  6326. }
  6327. var gl = this._gl;
  6328. var texture = gl.createTexture();
  6329. gl.bindTexture(gl.TEXTURE_2D, texture);
  6330. var width = size.width || size;
  6331. var height = size.height || size;
  6332. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6333. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6334. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6335. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6336. }
  6337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6342. var depthBuffer;
  6343. // Create the depth buffer
  6344. if (generateDepthBuffer) {
  6345. depthBuffer = gl.createRenderbuffer();
  6346. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6348. }
  6349. // Create the framebuffer
  6350. var framebuffer = gl.createFramebuffer();
  6351. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6352. if (generateDepthBuffer) {
  6353. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6354. }
  6355. if (generateMipMaps) {
  6356. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6357. }
  6358. // Unbind
  6359. gl.bindTexture(gl.TEXTURE_2D, null);
  6360. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6361. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6362. texture._framebuffer = framebuffer;
  6363. if (generateDepthBuffer) {
  6364. texture._depthBuffer = depthBuffer;
  6365. }
  6366. texture._width = width;
  6367. texture._height = height;
  6368. texture.isReady = true;
  6369. texture.generateMipMaps = generateMipMaps;
  6370. texture.references = 1;
  6371. texture.samplingMode = samplingMode;
  6372. this.resetTextureCache();
  6373. this._loadedTexturesCache.push(texture);
  6374. return texture;
  6375. };
  6376. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6377. var gl = this._gl;
  6378. var texture = gl.createTexture();
  6379. var generateMipMaps = true;
  6380. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6381. if (options !== undefined) {
  6382. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6383. if (options.samplingMode !== undefined) {
  6384. samplingMode = options.samplingMode;
  6385. }
  6386. }
  6387. texture.isCube = true;
  6388. texture.references = 1;
  6389. texture.generateMipMaps = generateMipMaps;
  6390. texture.references = 1;
  6391. texture.samplingMode = samplingMode;
  6392. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6393. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6394. for (var face = 0; face < 6; face++) {
  6395. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6396. }
  6397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6401. // Create the depth buffer
  6402. var depthBuffer = gl.createRenderbuffer();
  6403. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6404. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6405. // Create the framebuffer
  6406. var framebuffer = gl.createFramebuffer();
  6407. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6408. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6409. // mipmaps
  6410. if (texture.generateMipMaps) {
  6411. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6412. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6413. }
  6414. // Unbind
  6415. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6416. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6417. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6418. texture._framebuffer = framebuffer;
  6419. texture._depthBuffer = depthBuffer;
  6420. this.resetTextureCache();
  6421. texture._width = size;
  6422. texture._height = size;
  6423. texture.isReady = true;
  6424. return texture;
  6425. };
  6426. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6427. var _this = this;
  6428. var gl = this._gl;
  6429. var texture = gl.createTexture();
  6430. texture.isCube = true;
  6431. texture.url = rootUrl;
  6432. texture.references = 1;
  6433. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6434. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6435. if (isDDS) {
  6436. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6437. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6438. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6439. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6440. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6441. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6442. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6443. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6444. }
  6445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6449. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6450. _this.resetTextureCache();
  6451. texture._width = info.width;
  6452. texture._height = info.height;
  6453. texture.isReady = true;
  6454. }, null, null, true);
  6455. }
  6456. else {
  6457. cascadeLoad(rootUrl, scene, function (imgs) {
  6458. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6459. var height = width;
  6460. _this._prepareWorkingCanvas();
  6461. _this._workingCanvas.width = width;
  6462. _this._workingCanvas.height = height;
  6463. var faces = [
  6464. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6465. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6466. ];
  6467. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6468. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6469. for (var index = 0; index < faces.length; index++) {
  6470. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6471. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6472. }
  6473. if (!noMipmap) {
  6474. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6475. }
  6476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6480. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6481. _this.resetTextureCache();
  6482. texture._width = width;
  6483. texture._height = height;
  6484. texture.isReady = true;
  6485. }, extensions);
  6486. }
  6487. return texture;
  6488. };
  6489. Engine.prototype._releaseTexture = function (texture) {
  6490. var gl = this._gl;
  6491. if (texture._framebuffer) {
  6492. gl.deleteFramebuffer(texture._framebuffer);
  6493. }
  6494. if (texture._depthBuffer) {
  6495. gl.deleteRenderbuffer(texture._depthBuffer);
  6496. }
  6497. gl.deleteTexture(texture);
  6498. // Unbind channels
  6499. this.unbindAllTextures();
  6500. var index = this._loadedTexturesCache.indexOf(texture);
  6501. if (index !== -1) {
  6502. this._loadedTexturesCache.splice(index, 1);
  6503. }
  6504. };
  6505. Engine.prototype.bindSamplers = function (effect) {
  6506. this._gl.useProgram(effect.getProgram());
  6507. var samplers = effect.getSamplers();
  6508. for (var index = 0; index < samplers.length; index++) {
  6509. var uniform = effect.getUniform(samplers[index]);
  6510. this._gl.uniform1i(uniform, index);
  6511. }
  6512. this._currentEffect = null;
  6513. };
  6514. Engine.prototype._bindTexture = function (channel, texture) {
  6515. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6516. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6517. this._activeTexturesCache[channel] = null;
  6518. };
  6519. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6520. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6521. };
  6522. Engine.prototype.unbindAllTextures = function () {
  6523. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6524. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6525. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6526. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6527. this._activeTexturesCache[channel] = null;
  6528. }
  6529. };
  6530. Engine.prototype.setTexture = function (channel, texture) {
  6531. if (channel < 0) {
  6532. return;
  6533. }
  6534. // Not ready?
  6535. if (!texture || !texture.isReady()) {
  6536. if (this._activeTexturesCache[channel] != null) {
  6537. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6538. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6539. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6540. this._activeTexturesCache[channel] = null;
  6541. }
  6542. return;
  6543. }
  6544. // Video
  6545. var alreadyActivated = false;
  6546. if (texture instanceof BABYLON.VideoTexture) {
  6547. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6548. alreadyActivated = true;
  6549. texture.update();
  6550. }
  6551. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6552. texture.delayLoad();
  6553. return;
  6554. }
  6555. if (this._activeTexturesCache[channel] === texture) {
  6556. return;
  6557. }
  6558. this._activeTexturesCache[channel] = texture;
  6559. var internalTexture = texture.getInternalTexture();
  6560. if (!alreadyActivated) {
  6561. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6562. }
  6563. if (internalTexture.isCube) {
  6564. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6565. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6566. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6567. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6568. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6569. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6570. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6571. }
  6572. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6573. }
  6574. else {
  6575. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6576. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6577. internalTexture._cachedWrapU = texture.wrapU;
  6578. switch (texture.wrapU) {
  6579. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6580. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6581. break;
  6582. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6584. break;
  6585. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6587. break;
  6588. }
  6589. }
  6590. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6591. internalTexture._cachedWrapV = texture.wrapV;
  6592. switch (texture.wrapV) {
  6593. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6595. break;
  6596. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6598. break;
  6599. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6601. break;
  6602. }
  6603. }
  6604. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6605. }
  6606. };
  6607. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6608. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6609. var value = texture.anisotropicFilteringLevel;
  6610. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6611. value = 1;
  6612. }
  6613. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6614. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6615. texture._cachedAnisotropicFilteringLevel = value;
  6616. }
  6617. };
  6618. Engine.prototype.readPixels = function (x, y, width, height) {
  6619. var data = new Uint8Array(height * width * 4);
  6620. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6621. return data;
  6622. };
  6623. Engine.prototype.releaseInternalTexture = function (texture) {
  6624. if (!texture) {
  6625. return;
  6626. }
  6627. texture.references--;
  6628. // Final reference ?
  6629. if (texture.references === 0) {
  6630. var texturesCache = this.getLoadedTexturesCache();
  6631. var index = texturesCache.indexOf(texture);
  6632. if (index > -1) {
  6633. texturesCache.splice(index, 1);
  6634. }
  6635. this._releaseTexture(texture);
  6636. }
  6637. };
  6638. // Dispose
  6639. Engine.prototype.dispose = function () {
  6640. this.hideLoadingUI();
  6641. this.stopRenderLoop();
  6642. // Release scenes
  6643. while (this.scenes.length) {
  6644. this.scenes[0].dispose();
  6645. }
  6646. // Release audio engine
  6647. Engine.audioEngine.dispose();
  6648. // Release effects
  6649. for (var name in this._compiledEffects) {
  6650. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6651. }
  6652. // Unbind
  6653. for (var i in this._vertexAttribArrays) {
  6654. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6655. continue;
  6656. }
  6657. this._gl.disableVertexAttribArray(i);
  6658. }
  6659. this._gl = null;
  6660. // Events
  6661. window.removeEventListener("blur", this._onBlur);
  6662. window.removeEventListener("focus", this._onFocus);
  6663. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6664. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6665. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6666. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6667. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6668. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6669. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6670. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6671. };
  6672. // Loading screen
  6673. Engine.prototype.displayLoadingUI = function () {
  6674. this._loadingScreen.displayLoadingUI();
  6675. };
  6676. Engine.prototype.hideLoadingUI = function () {
  6677. this._loadingScreen.hideLoadingUI();
  6678. };
  6679. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6680. get: function () {
  6681. return this._loadingScreen;
  6682. },
  6683. set: function (loadingScreen) {
  6684. this._loadingScreen = loadingScreen;
  6685. },
  6686. enumerable: true,
  6687. configurable: true
  6688. });
  6689. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6690. set: function (text) {
  6691. this._loadingScreen.loadingUIText = text;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6697. set: function (color) {
  6698. this._loadingScreen.loadingUIBackgroundColor = color;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. // FPS
  6704. Engine.prototype.getFps = function () {
  6705. return this.fps;
  6706. };
  6707. Engine.prototype.getDeltaTime = function () {
  6708. return this.deltaTime;
  6709. };
  6710. Engine.prototype._measureFps = function () {
  6711. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6712. var length = this.previousFramesDuration.length;
  6713. if (length >= 2) {
  6714. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6715. }
  6716. if (length >= this.fpsRange) {
  6717. if (length > this.fpsRange) {
  6718. this.previousFramesDuration.splice(0, 1);
  6719. length = this.previousFramesDuration.length;
  6720. }
  6721. var sum = 0;
  6722. for (var id = 0; id < length - 1; id++) {
  6723. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6724. }
  6725. this.fps = 1000.0 / (sum / (length - 1));
  6726. }
  6727. };
  6728. // Statics
  6729. Engine.isSupported = function () {
  6730. try {
  6731. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6732. if (navigator.isCocoonJS) {
  6733. return true;
  6734. }
  6735. var tempcanvas = document.createElement("canvas");
  6736. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6737. return gl != null && !!window.WebGLRenderingContext;
  6738. }
  6739. catch (e) {
  6740. return false;
  6741. }
  6742. };
  6743. // Const statics
  6744. Engine._ALPHA_DISABLE = 0;
  6745. Engine._ALPHA_ADD = 1;
  6746. Engine._ALPHA_COMBINE = 2;
  6747. Engine._ALPHA_SUBTRACT = 3;
  6748. Engine._ALPHA_MULTIPLY = 4;
  6749. Engine._ALPHA_MAXIMIZED = 5;
  6750. Engine._ALPHA_ONEONE = 6;
  6751. Engine._DELAYLOADSTATE_NONE = 0;
  6752. Engine._DELAYLOADSTATE_LOADED = 1;
  6753. Engine._DELAYLOADSTATE_LOADING = 2;
  6754. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6755. Engine._TEXTUREFORMAT_ALPHA = 0;
  6756. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6757. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6758. Engine._TEXTUREFORMAT_RGB = 4;
  6759. Engine._TEXTUREFORMAT_RGBA = 5;
  6760. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6761. Engine._TEXTURETYPE_FLOAT = 1;
  6762. // Updatable statics so stick with vars here
  6763. Engine.Epsilon = 0.001;
  6764. Engine.CollisionsEpsilon = 0.001;
  6765. Engine.CodeRepository = "src/";
  6766. Engine.ShadersRepository = "src/Shaders/";
  6767. return Engine;
  6768. })();
  6769. BABYLON.Engine = Engine;
  6770. })(BABYLON || (BABYLON = {}));
  6771. var BABYLON;
  6772. (function (BABYLON) {
  6773. /**
  6774. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6775. */
  6776. var Node = (function () {
  6777. /**
  6778. * @constructor
  6779. * @param {string} name - the name and id to be given to this node
  6780. * @param {BABYLON.Scene} the scene this node will be added to
  6781. */
  6782. function Node(name, scene) {
  6783. this.state = "";
  6784. this.animations = new Array();
  6785. this._childrenFlag = -1;
  6786. this._isEnabled = true;
  6787. this._isReady = true;
  6788. this._currentRenderId = -1;
  6789. this._parentRenderId = -1;
  6790. this.name = name;
  6791. this.id = name;
  6792. this._scene = scene;
  6793. this._initCache();
  6794. }
  6795. Node.prototype.getScene = function () {
  6796. return this._scene;
  6797. };
  6798. Node.prototype.getEngine = function () {
  6799. return this._scene.getEngine();
  6800. };
  6801. // override it in derived class
  6802. Node.prototype.getWorldMatrix = function () {
  6803. return BABYLON.Matrix.Identity();
  6804. };
  6805. // override it in derived class if you add new variables to the cache
  6806. // and call the parent class method
  6807. Node.prototype._initCache = function () {
  6808. this._cache = {};
  6809. this._cache.parent = undefined;
  6810. };
  6811. Node.prototype.updateCache = function (force) {
  6812. if (!force && this.isSynchronized())
  6813. return;
  6814. this._cache.parent = this.parent;
  6815. this._updateCache();
  6816. };
  6817. // override it in derived class if you add new variables to the cache
  6818. // and call the parent class method if !ignoreParentClass
  6819. Node.prototype._updateCache = function (ignoreParentClass) {
  6820. };
  6821. // override it in derived class if you add new variables to the cache
  6822. Node.prototype._isSynchronized = function () {
  6823. return true;
  6824. };
  6825. Node.prototype._markSyncedWithParent = function () {
  6826. this._parentRenderId = this.parent._currentRenderId;
  6827. };
  6828. Node.prototype.isSynchronizedWithParent = function () {
  6829. if (!this.parent) {
  6830. return true;
  6831. }
  6832. if (this._parentRenderId !== this.parent._currentRenderId) {
  6833. return false;
  6834. }
  6835. return this.parent.isSynchronized();
  6836. };
  6837. Node.prototype.isSynchronized = function (updateCache) {
  6838. var check = this.hasNewParent();
  6839. check = check || !this.isSynchronizedWithParent();
  6840. check = check || !this._isSynchronized();
  6841. if (updateCache)
  6842. this.updateCache(true);
  6843. return !check;
  6844. };
  6845. Node.prototype.hasNewParent = function (update) {
  6846. if (this._cache.parent === this.parent)
  6847. return false;
  6848. if (update)
  6849. this._cache.parent = this.parent;
  6850. return true;
  6851. };
  6852. /**
  6853. * Is this node ready to be used/rendered
  6854. * @return {boolean} is it ready
  6855. */
  6856. Node.prototype.isReady = function () {
  6857. return this._isReady;
  6858. };
  6859. /**
  6860. * Is this node enabled.
  6861. * If the node has a parent and is enabled, the parent will be inspected as well.
  6862. * @return {boolean} whether this node (and its parent) is enabled.
  6863. * @see setEnabled
  6864. */
  6865. Node.prototype.isEnabled = function () {
  6866. if (!this._isEnabled) {
  6867. return false;
  6868. }
  6869. if (this.parent) {
  6870. return this.parent.isEnabled();
  6871. }
  6872. return true;
  6873. };
  6874. /**
  6875. * Set the enabled state of this node.
  6876. * @param {boolean} value - the new enabled state
  6877. * @see isEnabled
  6878. */
  6879. Node.prototype.setEnabled = function (value) {
  6880. this._isEnabled = value;
  6881. };
  6882. /**
  6883. * Is this node a descendant of the given node.
  6884. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6885. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6886. * @see parent
  6887. */
  6888. Node.prototype.isDescendantOf = function (ancestor) {
  6889. if (this.parent) {
  6890. if (this.parent === ancestor) {
  6891. return true;
  6892. }
  6893. return this.parent.isDescendantOf(ancestor);
  6894. }
  6895. return false;
  6896. };
  6897. Node.prototype._getDescendants = function (list, results) {
  6898. for (var index = 0; index < list.length; index++) {
  6899. var item = list[index];
  6900. if (item.isDescendantOf(this)) {
  6901. results.push(item);
  6902. }
  6903. }
  6904. };
  6905. /**
  6906. * Will return all nodes that have this node as parent.
  6907. * @return {BABYLON.Node[]} all children nodes of all types.
  6908. */
  6909. Node.prototype.getDescendants = function () {
  6910. var results = [];
  6911. this._getDescendants(this._scene.meshes, results);
  6912. this._getDescendants(this._scene.lights, results);
  6913. this._getDescendants(this._scene.cameras, results);
  6914. return results;
  6915. };
  6916. Node.prototype._setReady = function (state) {
  6917. if (state === this._isReady) {
  6918. return;
  6919. }
  6920. if (!state) {
  6921. this._isReady = false;
  6922. return;
  6923. }
  6924. this._isReady = true;
  6925. if (this.onReady) {
  6926. this.onReady(this);
  6927. }
  6928. };
  6929. Node.prototype.getAnimationByName = function (name) {
  6930. for (var i = 0; i < this.animations.length; i++) {
  6931. var animation = this.animations[i];
  6932. if (animation.name === name) {
  6933. return animation;
  6934. }
  6935. }
  6936. return null;
  6937. };
  6938. return Node;
  6939. })();
  6940. BABYLON.Node = Node;
  6941. })(BABYLON || (BABYLON = {}));
  6942. var BABYLON;
  6943. (function (BABYLON) {
  6944. var FilesInput = (function () {
  6945. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6946. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6947. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6948. this._engine = p_engine;
  6949. this._canvas = p_canvas;
  6950. this._currentScene = p_scene;
  6951. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6952. this._progressCallback = p_progressCallback;
  6953. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6954. this._textureLoadingCallback = p_textureLoadingCallback;
  6955. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6956. }
  6957. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6958. var _this = this;
  6959. if (p_elementToMonitor) {
  6960. this._elementToMonitor = p_elementToMonitor;
  6961. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6962. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6963. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6964. }
  6965. };
  6966. FilesInput.prototype.renderFunction = function () {
  6967. if (this._additionnalRenderLoopLogicCallback) {
  6968. this._additionnalRenderLoopLogicCallback();
  6969. }
  6970. if (this._currentScene) {
  6971. if (this._textureLoadingCallback) {
  6972. var remaining = this._currentScene.getWaitingItemsCount();
  6973. if (remaining > 0) {
  6974. this._textureLoadingCallback(remaining);
  6975. }
  6976. }
  6977. this._currentScene.render();
  6978. }
  6979. };
  6980. FilesInput.prototype.drag = function (e) {
  6981. e.stopPropagation();
  6982. e.preventDefault();
  6983. };
  6984. FilesInput.prototype.drop = function (eventDrop) {
  6985. eventDrop.stopPropagation();
  6986. eventDrop.preventDefault();
  6987. this.loadFiles(eventDrop);
  6988. };
  6989. FilesInput.prototype.loadFiles = function (event) {
  6990. if (this._startingProcessingFilesCallback)
  6991. this._startingProcessingFilesCallback();
  6992. // Handling data transfer via drag'n'drop
  6993. if (event && event.dataTransfer && event.dataTransfer.files) {
  6994. this._filesToLoad = event.dataTransfer.files;
  6995. }
  6996. // Handling files from input files
  6997. if (event && event.target && event.target.files) {
  6998. this._filesToLoad = event.target.files;
  6999. }
  7000. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7001. for (var i = 0; i < this._filesToLoad.length; i++) {
  7002. switch (this._filesToLoad[i].type) {
  7003. case "image/jpeg":
  7004. case "image/png":
  7005. case "image/bmp":
  7006. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7007. break;
  7008. case "image/targa":
  7009. case "image/vnd.ms-dds":
  7010. case "audio/wav":
  7011. case "audio/x-wav":
  7012. case "audio/mp3":
  7013. case "audio/mpeg":
  7014. case "audio/mpeg3":
  7015. case "audio/x-mpeg-3":
  7016. case "audio/ogg":
  7017. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7018. break;
  7019. default:
  7020. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7021. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7022. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7023. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7024. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7025. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7026. this._sceneFileToLoad = this._filesToLoad[i];
  7027. }
  7028. break;
  7029. }
  7030. }
  7031. this.reload();
  7032. }
  7033. };
  7034. FilesInput.prototype.reload = function () {
  7035. var _this = this;
  7036. var that = this;
  7037. // If a ".babylon" file has been provided
  7038. if (this._sceneFileToLoad) {
  7039. if (this._currentScene) {
  7040. if (BABYLON.Tools.errorsCount > 0) {
  7041. BABYLON.Tools.ClearLogCache();
  7042. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7043. }
  7044. this._engine.stopRenderLoop();
  7045. this._currentScene.dispose();
  7046. }
  7047. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7048. that._currentScene = newScene;
  7049. // Wait for textures and shaders to be ready
  7050. that._currentScene.executeWhenReady(function () {
  7051. // Attach camera to canvas inputs
  7052. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7053. that._currentScene.createDefaultCameraOrLight();
  7054. }
  7055. that._currentScene.activeCamera.attachControl(that._canvas);
  7056. if (that._sceneLoadedCallback) {
  7057. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7058. }
  7059. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7060. });
  7061. }, function (progress) {
  7062. if (_this._progressCallback) {
  7063. _this._progressCallback(progress);
  7064. }
  7065. });
  7066. }
  7067. else {
  7068. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7069. }
  7070. };
  7071. FilesInput.FilesTextures = new Array();
  7072. FilesInput.FilesToLoad = new Array();
  7073. return FilesInput;
  7074. })();
  7075. BABYLON.FilesInput = FilesInput;
  7076. })(BABYLON || (BABYLON = {}));
  7077. var BABYLON;
  7078. (function (BABYLON) {
  7079. var IntersectionInfo = (function () {
  7080. function IntersectionInfo(bu, bv, distance) {
  7081. this.bu = bu;
  7082. this.bv = bv;
  7083. this.distance = distance;
  7084. this.faceId = 0;
  7085. this.subMeshId = 0;
  7086. }
  7087. return IntersectionInfo;
  7088. })();
  7089. BABYLON.IntersectionInfo = IntersectionInfo;
  7090. var PickingInfo = (function () {
  7091. function PickingInfo() {
  7092. this.hit = false;
  7093. this.distance = 0;
  7094. this.pickedPoint = null;
  7095. this.pickedMesh = null;
  7096. this.bu = 0;
  7097. this.bv = 0;
  7098. this.faceId = -1;
  7099. this.subMeshId = 0;
  7100. this.pickedSprite = null;
  7101. }
  7102. // Methods
  7103. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7104. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7105. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7106. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7107. return null;
  7108. }
  7109. var indices = this.pickedMesh.getIndices();
  7110. var result;
  7111. if (useVerticesNormals) {
  7112. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7113. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7114. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7115. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7116. normal0 = normal0.scale(this.bu);
  7117. normal1 = normal1.scale(this.bv);
  7118. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7119. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7120. }
  7121. else {
  7122. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7123. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7124. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7125. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7126. var p1p2 = vertex1.subtract(vertex2);
  7127. var p3p2 = vertex3.subtract(vertex2);
  7128. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7129. }
  7130. if (useWorldCoordinates) {
  7131. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7132. }
  7133. return BABYLON.Vector3.Normalize(result);
  7134. };
  7135. PickingInfo.prototype.getTextureCoordinates = function () {
  7136. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7137. return null;
  7138. }
  7139. var indices = this.pickedMesh.getIndices();
  7140. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7141. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7142. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7143. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7144. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7145. uv1 = uv1.scale(this.bu);
  7146. uv2 = uv2.scale(this.bv);
  7147. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7148. };
  7149. return PickingInfo;
  7150. })();
  7151. BABYLON.PickingInfo = PickingInfo;
  7152. })(BABYLON || (BABYLON = {}));
  7153. var BABYLON;
  7154. (function (BABYLON) {
  7155. var BoundingSphere = (function () {
  7156. function BoundingSphere(minimum, maximum) {
  7157. this.minimum = minimum;
  7158. this.maximum = maximum;
  7159. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7160. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7161. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7162. this.radius = distance * 0.5;
  7163. this.centerWorld = BABYLON.Vector3.Zero();
  7164. this._update(BABYLON.Matrix.Identity());
  7165. }
  7166. // Methods
  7167. BoundingSphere.prototype._update = function (world) {
  7168. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7169. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7170. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7171. };
  7172. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7173. for (var i = 0; i < 6; i++) {
  7174. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7175. return false;
  7176. }
  7177. return true;
  7178. };
  7179. BoundingSphere.prototype.intersectsPoint = function (point) {
  7180. var x = this.centerWorld.x - point.x;
  7181. var y = this.centerWorld.y - point.y;
  7182. var z = this.centerWorld.z - point.z;
  7183. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7184. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7185. return false;
  7186. return true;
  7187. };
  7188. // Statics
  7189. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7190. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7191. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7192. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7193. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7194. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7195. return false;
  7196. return true;
  7197. };
  7198. return BoundingSphere;
  7199. })();
  7200. BABYLON.BoundingSphere = BoundingSphere;
  7201. })(BABYLON || (BABYLON = {}));
  7202. var BABYLON;
  7203. (function (BABYLON) {
  7204. var BoundingBox = (function () {
  7205. function BoundingBox(minimum, maximum) {
  7206. this.minimum = minimum;
  7207. this.maximum = maximum;
  7208. this.vectors = new Array();
  7209. this.vectorsWorld = new Array();
  7210. // Bounding vectors
  7211. this.vectors.push(this.minimum.clone());
  7212. this.vectors.push(this.maximum.clone());
  7213. this.vectors.push(this.minimum.clone());
  7214. this.vectors[2].x = this.maximum.x;
  7215. this.vectors.push(this.minimum.clone());
  7216. this.vectors[3].y = this.maximum.y;
  7217. this.vectors.push(this.minimum.clone());
  7218. this.vectors[4].z = this.maximum.z;
  7219. this.vectors.push(this.maximum.clone());
  7220. this.vectors[5].z = this.minimum.z;
  7221. this.vectors.push(this.maximum.clone());
  7222. this.vectors[6].x = this.minimum.x;
  7223. this.vectors.push(this.maximum.clone());
  7224. this.vectors[7].y = this.minimum.y;
  7225. // OBB
  7226. this.center = this.maximum.add(this.minimum).scale(0.5);
  7227. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7228. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7229. // World
  7230. for (var index = 0; index < this.vectors.length; index++) {
  7231. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7232. }
  7233. this.minimumWorld = BABYLON.Vector3.Zero();
  7234. this.maximumWorld = BABYLON.Vector3.Zero();
  7235. this._update(BABYLON.Matrix.Identity());
  7236. }
  7237. // Methods
  7238. BoundingBox.prototype.getWorldMatrix = function () {
  7239. return this._worldMatrix;
  7240. };
  7241. BoundingBox.prototype._update = function (world) {
  7242. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7243. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7244. for (var index = 0; index < this.vectors.length; index++) {
  7245. var v = this.vectorsWorld[index];
  7246. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7247. if (v.x < this.minimumWorld.x)
  7248. this.minimumWorld.x = v.x;
  7249. if (v.y < this.minimumWorld.y)
  7250. this.minimumWorld.y = v.y;
  7251. if (v.z < this.minimumWorld.z)
  7252. this.minimumWorld.z = v.z;
  7253. if (v.x > this.maximumWorld.x)
  7254. this.maximumWorld.x = v.x;
  7255. if (v.y > this.maximumWorld.y)
  7256. this.maximumWorld.y = v.y;
  7257. if (v.z > this.maximumWorld.z)
  7258. this.maximumWorld.z = v.z;
  7259. }
  7260. // OBB
  7261. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7262. this.center.scaleInPlace(0.5);
  7263. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7264. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7265. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7266. this._worldMatrix = world;
  7267. };
  7268. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7269. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7270. };
  7271. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7272. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7273. };
  7274. BoundingBox.prototype.intersectsPoint = function (point) {
  7275. var delta = -BABYLON.Engine.Epsilon;
  7276. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7277. return false;
  7278. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7279. return false;
  7280. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7281. return false;
  7282. return true;
  7283. };
  7284. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7285. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7286. };
  7287. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7288. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7289. return false;
  7290. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7291. return false;
  7292. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7293. return false;
  7294. return true;
  7295. };
  7296. // Statics
  7297. BoundingBox.Intersects = function (box0, box1) {
  7298. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7299. return false;
  7300. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7301. return false;
  7302. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7303. return false;
  7304. return true;
  7305. };
  7306. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7307. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7308. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7309. return (num <= (sphereRadius * sphereRadius));
  7310. };
  7311. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7312. for (var p = 0; p < 6; p++) {
  7313. for (var i = 0; i < 8; i++) {
  7314. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7315. return false;
  7316. }
  7317. }
  7318. }
  7319. return true;
  7320. };
  7321. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7322. for (var p = 0; p < 6; p++) {
  7323. var inCount = 8;
  7324. for (var i = 0; i < 8; i++) {
  7325. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7326. --inCount;
  7327. }
  7328. else {
  7329. break;
  7330. }
  7331. }
  7332. if (inCount === 0)
  7333. return false;
  7334. }
  7335. return true;
  7336. };
  7337. return BoundingBox;
  7338. })();
  7339. BABYLON.BoundingBox = BoundingBox;
  7340. })(BABYLON || (BABYLON = {}));
  7341. var BABYLON;
  7342. (function (BABYLON) {
  7343. var computeBoxExtents = function (axis, box) {
  7344. var p = BABYLON.Vector3.Dot(box.center, axis);
  7345. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7346. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7347. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7348. var r = r0 + r1 + r2;
  7349. return {
  7350. min: p - r,
  7351. max: p + r
  7352. };
  7353. };
  7354. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7355. var axisOverlap = function (axis, box0, box1) {
  7356. var result0 = computeBoxExtents(axis, box0);
  7357. var result1 = computeBoxExtents(axis, box1);
  7358. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7359. };
  7360. var BoundingInfo = (function () {
  7361. function BoundingInfo(minimum, maximum) {
  7362. this.minimum = minimum;
  7363. this.maximum = maximum;
  7364. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7365. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7366. }
  7367. // Methods
  7368. BoundingInfo.prototype._update = function (world) {
  7369. this.boundingBox._update(world);
  7370. this.boundingSphere._update(world);
  7371. };
  7372. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7373. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7374. return false;
  7375. return this.boundingBox.isInFrustum(frustumPlanes);
  7376. };
  7377. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7378. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7379. };
  7380. BoundingInfo.prototype._checkCollision = function (collider) {
  7381. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7382. };
  7383. BoundingInfo.prototype.intersectsPoint = function (point) {
  7384. if (!this.boundingSphere.centerWorld) {
  7385. return false;
  7386. }
  7387. if (!this.boundingSphere.intersectsPoint(point)) {
  7388. return false;
  7389. }
  7390. if (!this.boundingBox.intersectsPoint(point)) {
  7391. return false;
  7392. }
  7393. return true;
  7394. };
  7395. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7396. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7397. return false;
  7398. }
  7399. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7400. return false;
  7401. }
  7402. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7403. return false;
  7404. }
  7405. if (!precise) {
  7406. return true;
  7407. }
  7408. var box0 = this.boundingBox;
  7409. var box1 = boundingInfo.boundingBox;
  7410. if (!axisOverlap(box0.directions[0], box0, box1))
  7411. return false;
  7412. if (!axisOverlap(box0.directions[1], box0, box1))
  7413. return false;
  7414. if (!axisOverlap(box0.directions[2], box0, box1))
  7415. return false;
  7416. if (!axisOverlap(box1.directions[0], box0, box1))
  7417. return false;
  7418. if (!axisOverlap(box1.directions[1], box0, box1))
  7419. return false;
  7420. if (!axisOverlap(box1.directions[2], box0, box1))
  7421. return false;
  7422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7423. return false;
  7424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7425. return false;
  7426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7427. return false;
  7428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7429. return false;
  7430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7431. return false;
  7432. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7433. return false;
  7434. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7435. return false;
  7436. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7437. return false;
  7438. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7439. return false;
  7440. return true;
  7441. };
  7442. return BoundingInfo;
  7443. })();
  7444. BABYLON.BoundingInfo = BoundingInfo;
  7445. })(BABYLON || (BABYLON = {}));
  7446. var BABYLON;
  7447. (function (BABYLON) {
  7448. var AbstractMesh = (function (_super) {
  7449. __extends(AbstractMesh, _super);
  7450. function AbstractMesh(name, scene) {
  7451. var _this = this;
  7452. _super.call(this, name, scene);
  7453. // Properties
  7454. this.definedFacingForward = true; // orientation for POV movement & rotation
  7455. this.position = new BABYLON.Vector3(0, 0, 0);
  7456. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7457. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7458. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7459. this.visibility = 1.0;
  7460. this.alphaIndex = Number.MAX_VALUE;
  7461. this.infiniteDistance = false;
  7462. this.isVisible = true;
  7463. this.isPickable = true;
  7464. this.showBoundingBox = false;
  7465. this.showSubMeshesBoundingBox = false;
  7466. this.onDispose = null;
  7467. this.isBlocker = false;
  7468. this.renderingGroupId = 0;
  7469. this.receiveShadows = false;
  7470. this.renderOutline = false;
  7471. this.outlineColor = BABYLON.Color3.Red();
  7472. this.outlineWidth = 0.02;
  7473. this.renderOverlay = false;
  7474. this.overlayColor = BABYLON.Color3.Red();
  7475. this.overlayAlpha = 0.5;
  7476. this.hasVertexAlpha = false;
  7477. this.useVertexColors = true;
  7478. this.applyFog = true;
  7479. this.computeBonesUsingShaders = true;
  7480. this.scalingDeterminant = 1;
  7481. this.numBoneInfluencers = 4;
  7482. this.useOctreeForRenderingSelection = true;
  7483. this.useOctreeForPicking = true;
  7484. this.useOctreeForCollisions = true;
  7485. this.layerMask = 0x0FFFFFFF;
  7486. this.alwaysSelectAsActiveMesh = false;
  7487. // Physics
  7488. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7489. // Collisions
  7490. this._checkCollisions = false;
  7491. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7492. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7493. this._collider = new BABYLON.Collider();
  7494. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7495. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7496. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7497. // Edges
  7498. this.edgesWidth = 1;
  7499. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7500. // Cache
  7501. this._localScaling = BABYLON.Matrix.Zero();
  7502. this._localRotation = BABYLON.Matrix.Zero();
  7503. this._localTranslation = BABYLON.Matrix.Zero();
  7504. this._localBillboard = BABYLON.Matrix.Zero();
  7505. this._localPivotScaling = BABYLON.Matrix.Zero();
  7506. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7507. this._localWorld = BABYLON.Matrix.Zero();
  7508. this._worldMatrix = BABYLON.Matrix.Zero();
  7509. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7510. this._absolutePosition = BABYLON.Vector3.Zero();
  7511. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7512. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7513. this._isDirty = false;
  7514. this._pivotMatrix = BABYLON.Matrix.Identity();
  7515. this._isDisposed = false;
  7516. this._renderId = 0;
  7517. this._intersectionsInProgress = new Array();
  7518. this._onAfterWorldMatrixUpdate = new Array();
  7519. this._isWorldMatrixFrozen = false;
  7520. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7521. if (collidedMesh === void 0) { collidedMesh = null; }
  7522. //TODO move this to the collision coordinator!
  7523. if (_this.getScene().workerCollisions)
  7524. newPosition.multiplyInPlace(_this._collider.radius);
  7525. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7526. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7527. _this.position.addInPlace(_this._diffPositionForCollisions);
  7528. }
  7529. if (_this.onCollide && collidedMesh) {
  7530. _this.onCollide(collidedMesh);
  7531. }
  7532. if (_this.onCollisionPositionChange) {
  7533. _this.onCollisionPositionChange(_this.position);
  7534. }
  7535. };
  7536. scene.addMesh(this);
  7537. }
  7538. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7539. get: function () {
  7540. return AbstractMesh._BILLBOARDMODE_NONE;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7546. get: function () {
  7547. return AbstractMesh._BILLBOARDMODE_X;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7553. get: function () {
  7554. return AbstractMesh._BILLBOARDMODE_Y;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7560. get: function () {
  7561. return AbstractMesh._BILLBOARDMODE_Z;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7567. get: function () {
  7568. return AbstractMesh._BILLBOARDMODE_ALL;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. // Methods
  7574. AbstractMesh.prototype.disableEdgesRendering = function () {
  7575. if (this._edgesRenderer !== undefined) {
  7576. this._edgesRenderer.dispose();
  7577. this._edgesRenderer = undefined;
  7578. }
  7579. };
  7580. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7581. if (epsilon === void 0) { epsilon = 0.95; }
  7582. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7583. this.disableEdgesRendering();
  7584. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7585. };
  7586. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7587. get: function () {
  7588. return false;
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. AbstractMesh.prototype.getLOD = function (camera) {
  7594. return this;
  7595. };
  7596. AbstractMesh.prototype.getTotalVertices = function () {
  7597. return 0;
  7598. };
  7599. AbstractMesh.prototype.getIndices = function () {
  7600. return null;
  7601. };
  7602. AbstractMesh.prototype.getVerticesData = function (kind) {
  7603. return null;
  7604. };
  7605. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7606. return false;
  7607. };
  7608. AbstractMesh.prototype.getBoundingInfo = function () {
  7609. if (this._masterMesh) {
  7610. return this._masterMesh.getBoundingInfo();
  7611. }
  7612. if (!this._boundingInfo) {
  7613. this._updateBoundingInfo();
  7614. }
  7615. return this._boundingInfo;
  7616. };
  7617. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7618. get: function () {
  7619. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. AbstractMesh.prototype._preActivate = function () {
  7625. };
  7626. AbstractMesh.prototype._activate = function (renderId) {
  7627. this._renderId = renderId;
  7628. };
  7629. AbstractMesh.prototype.getWorldMatrix = function () {
  7630. if (this._masterMesh) {
  7631. return this._masterMesh.getWorldMatrix();
  7632. }
  7633. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7634. this.computeWorldMatrix();
  7635. }
  7636. return this._worldMatrix;
  7637. };
  7638. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7639. get: function () {
  7640. return this._worldMatrix;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7646. get: function () {
  7647. return this._absolutePosition;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7653. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7654. this.computeWorldMatrix(true);
  7655. this._isWorldMatrixFrozen = true;
  7656. };
  7657. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7658. this._isWorldMatrixFrozen = false;
  7659. this.computeWorldMatrix(true);
  7660. };
  7661. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7662. get: function () {
  7663. return this._isWorldMatrixFrozen;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7669. axis.normalize();
  7670. if (!this.rotationQuaternion) {
  7671. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7672. this.rotation = BABYLON.Vector3.Zero();
  7673. }
  7674. var rotationQuaternion;
  7675. if (!space || space === BABYLON.Space.LOCAL) {
  7676. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7677. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7678. }
  7679. else {
  7680. if (this.parent) {
  7681. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7682. invertParentWorldMatrix.invert();
  7683. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7684. }
  7685. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7686. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7687. }
  7688. };
  7689. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7690. var displacementVector = axis.scale(distance);
  7691. if (!space || space === BABYLON.Space.LOCAL) {
  7692. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7693. this.setPositionWithLocalVector(tempV3);
  7694. }
  7695. else {
  7696. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7697. }
  7698. };
  7699. AbstractMesh.prototype.getAbsolutePosition = function () {
  7700. this.computeWorldMatrix();
  7701. return this._absolutePosition;
  7702. };
  7703. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7704. if (!absolutePosition) {
  7705. return;
  7706. }
  7707. var absolutePositionX;
  7708. var absolutePositionY;
  7709. var absolutePositionZ;
  7710. if (absolutePosition.x === undefined) {
  7711. if (arguments.length < 3) {
  7712. return;
  7713. }
  7714. absolutePositionX = arguments[0];
  7715. absolutePositionY = arguments[1];
  7716. absolutePositionZ = arguments[2];
  7717. }
  7718. else {
  7719. absolutePositionX = absolutePosition.x;
  7720. absolutePositionY = absolutePosition.y;
  7721. absolutePositionZ = absolutePosition.z;
  7722. }
  7723. if (this.parent) {
  7724. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7725. invertParentWorldMatrix.invert();
  7726. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7727. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7728. }
  7729. else {
  7730. this.position.x = absolutePositionX;
  7731. this.position.y = absolutePositionY;
  7732. this.position.z = absolutePositionZ;
  7733. }
  7734. };
  7735. // ================================== Point of View Movement =================================
  7736. /**
  7737. * Perform relative position change from the point of view of behind the front of the mesh.
  7738. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7739. * Supports definition of mesh facing forward or backward.
  7740. * @param {number} amountRight
  7741. * @param {number} amountUp
  7742. * @param {number} amountForward
  7743. */
  7744. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7745. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7746. };
  7747. /**
  7748. * Calculate relative position change from the point of view of behind the front of the mesh.
  7749. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7750. * Supports definition of mesh facing forward or backward.
  7751. * @param {number} amountRight
  7752. * @param {number} amountUp
  7753. * @param {number} amountForward
  7754. */
  7755. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7756. var rotMatrix = new BABYLON.Matrix();
  7757. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7758. rotQuaternion.toRotationMatrix(rotMatrix);
  7759. var translationDelta = BABYLON.Vector3.Zero();
  7760. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7761. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7762. return translationDelta;
  7763. };
  7764. // ================================== Point of View Rotation =================================
  7765. /**
  7766. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7767. * Supports definition of mesh facing forward or backward.
  7768. * @param {number} flipBack
  7769. * @param {number} twirlClockwise
  7770. * @param {number} tiltRight
  7771. */
  7772. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7773. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7774. };
  7775. /**
  7776. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7777. * Supports definition of mesh facing forward or backward.
  7778. * @param {number} flipBack
  7779. * @param {number} twirlClockwise
  7780. * @param {number} tiltRight
  7781. */
  7782. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7783. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7784. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7785. };
  7786. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7787. this._pivotMatrix = matrix;
  7788. this._cache.pivotMatrixUpdated = true;
  7789. };
  7790. AbstractMesh.prototype.getPivotMatrix = function () {
  7791. return this._pivotMatrix;
  7792. };
  7793. AbstractMesh.prototype._isSynchronized = function () {
  7794. if (this._isDirty) {
  7795. return false;
  7796. }
  7797. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7798. return false;
  7799. if (this._cache.pivotMatrixUpdated) {
  7800. return false;
  7801. }
  7802. if (this.infiniteDistance) {
  7803. return false;
  7804. }
  7805. if (!this._cache.position.equals(this.position))
  7806. return false;
  7807. if (this.rotationQuaternion) {
  7808. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7809. return false;
  7810. }
  7811. else {
  7812. if (!this._cache.rotation.equals(this.rotation))
  7813. return false;
  7814. }
  7815. if (!this._cache.scaling.equals(this.scaling))
  7816. return false;
  7817. return true;
  7818. };
  7819. AbstractMesh.prototype._initCache = function () {
  7820. _super.prototype._initCache.call(this);
  7821. this._cache.localMatrixUpdated = false;
  7822. this._cache.position = BABYLON.Vector3.Zero();
  7823. this._cache.scaling = BABYLON.Vector3.Zero();
  7824. this._cache.rotation = BABYLON.Vector3.Zero();
  7825. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7826. };
  7827. AbstractMesh.prototype.markAsDirty = function (property) {
  7828. if (property === "rotation") {
  7829. this.rotationQuaternion = null;
  7830. }
  7831. this._currentRenderId = Number.MAX_VALUE;
  7832. this._isDirty = true;
  7833. };
  7834. AbstractMesh.prototype._updateBoundingInfo = function () {
  7835. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7836. this._boundingInfo._update(this.worldMatrixFromCache);
  7837. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7838. };
  7839. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7840. if (!this.subMeshes) {
  7841. return;
  7842. }
  7843. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7844. var subMesh = this.subMeshes[subIndex];
  7845. subMesh.updateBoundingInfo(matrix);
  7846. }
  7847. };
  7848. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7849. if (this._isWorldMatrixFrozen) {
  7850. return this._worldMatrix;
  7851. }
  7852. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7853. return this._worldMatrix;
  7854. }
  7855. this._cache.position.copyFrom(this.position);
  7856. this._cache.scaling.copyFrom(this.scaling);
  7857. this._cache.pivotMatrixUpdated = false;
  7858. this._currentRenderId = this.getScene().getRenderId();
  7859. this._isDirty = false;
  7860. // Scaling
  7861. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7862. // Rotation
  7863. if (this.rotationQuaternion) {
  7864. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7865. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7866. }
  7867. else {
  7868. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7869. this._cache.rotation.copyFrom(this.rotation);
  7870. }
  7871. // Translation
  7872. if (this.infiniteDistance && !this.parent) {
  7873. var camera = this.getScene().activeCamera;
  7874. if (camera) {
  7875. var cameraWorldMatrix = camera.getWorldMatrix();
  7876. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7877. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7878. }
  7879. }
  7880. else {
  7881. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7882. }
  7883. // Composing transformations
  7884. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7885. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7886. // Billboarding
  7887. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7888. var localPosition = this.position.clone();
  7889. var zero = this.getScene().activeCamera.globalPosition.clone();
  7890. if (this.parent && this.parent.position) {
  7891. localPosition.addInPlace(this.parent.position);
  7892. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7893. }
  7894. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7895. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7896. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7897. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7898. zero.y = localPosition.y + 0.001;
  7899. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7900. zero.z = localPosition.z + 0.001;
  7901. }
  7902. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7903. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7904. this._localBillboard.invert();
  7905. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7906. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7907. }
  7908. // Local world
  7909. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7910. // Parent
  7911. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7912. this._markSyncedWithParent();
  7913. if (this._meshToBoneReferal) {
  7914. if (!this._localMeshReferalTransform) {
  7915. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7916. }
  7917. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7918. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7919. }
  7920. else {
  7921. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7922. }
  7923. }
  7924. else {
  7925. this._worldMatrix.copyFrom(this._localWorld);
  7926. }
  7927. // Bounding info
  7928. this._updateBoundingInfo();
  7929. // Absolute position
  7930. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7931. // Callbacks
  7932. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7933. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7934. }
  7935. return this._worldMatrix;
  7936. };
  7937. /**
  7938. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7939. * @param func: callback function to add
  7940. */
  7941. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7942. this._onAfterWorldMatrixUpdate.push(func);
  7943. };
  7944. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7945. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7946. if (index > -1) {
  7947. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7948. }
  7949. };
  7950. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7951. this.computeWorldMatrix();
  7952. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7953. };
  7954. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7955. this.computeWorldMatrix();
  7956. var invLocalWorldMatrix = this._localWorld.clone();
  7957. invLocalWorldMatrix.invert();
  7958. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7959. };
  7960. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7961. this.computeWorldMatrix(true);
  7962. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7963. };
  7964. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7965. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7966. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7967. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7968. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7969. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7970. /// <returns>Mesh oriented towards targetMesh</returns>
  7971. yawCor = yawCor || 0; // default to zero if undefined
  7972. pitchCor = pitchCor || 0;
  7973. rollCor = rollCor || 0;
  7974. var dv = targetPoint.subtract(this.position);
  7975. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7976. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7977. var pitch = Math.atan2(dv.y, len);
  7978. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7979. };
  7980. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  7981. this._meshToBoneReferal = affectedMesh;
  7982. this.parent = bone;
  7983. if (bone.getWorldMatrix().determinant() < 0) {
  7984. this.scalingDeterminant *= -1;
  7985. }
  7986. };
  7987. AbstractMesh.prototype.detachFromBone = function () {
  7988. if (this.parent.getWorldMatrix().determinant() < 0) {
  7989. this.scalingDeterminant *= -1;
  7990. }
  7991. this._meshToBoneReferal = null;
  7992. this.parent = null;
  7993. };
  7994. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7995. return this._boundingInfo.isInFrustum(frustumPlanes);
  7996. };
  7997. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7998. if (!camera) {
  7999. camera = this.getScene().activeCamera;
  8000. }
  8001. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8002. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8003. return false;
  8004. }
  8005. return true;
  8006. };
  8007. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8008. if (!this._boundingInfo || !mesh._boundingInfo) {
  8009. return false;
  8010. }
  8011. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8012. };
  8013. AbstractMesh.prototype.intersectsPoint = function (point) {
  8014. if (!this._boundingInfo) {
  8015. return false;
  8016. }
  8017. return this._boundingInfo.intersectsPoint(point);
  8018. };
  8019. // Physics
  8020. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8021. var physicsEngine = this.getScene().getPhysicsEngine();
  8022. if (!physicsEngine) {
  8023. return null;
  8024. }
  8025. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8026. if (impostor.impostor) {
  8027. // Old API
  8028. options = impostor;
  8029. impostor = impostor.impostor;
  8030. }
  8031. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8032. physicsEngine._unregisterMesh(this);
  8033. return null;
  8034. }
  8035. if (!options) {
  8036. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8037. }
  8038. else {
  8039. if (!options.mass && options.mass !== 0)
  8040. options.mass = 0;
  8041. if (!options.friction && options.friction !== 0)
  8042. options.friction = 0.2;
  8043. if (!options.restitution && options.restitution !== 0)
  8044. options.restitution = 0.2;
  8045. }
  8046. this._physicImpostor = impostor;
  8047. this._physicsMass = options.mass;
  8048. this._physicsFriction = options.friction;
  8049. this._physicRestitution = options.restitution;
  8050. return physicsEngine._registerMesh(this, impostor, options);
  8051. };
  8052. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8053. if (!this._physicImpostor) {
  8054. return BABYLON.PhysicsEngine.NoImpostor;
  8055. }
  8056. return this._physicImpostor;
  8057. };
  8058. AbstractMesh.prototype.getPhysicsMass = function () {
  8059. if (!this._physicsMass) {
  8060. return 0;
  8061. }
  8062. return this._physicsMass;
  8063. };
  8064. AbstractMesh.prototype.getPhysicsFriction = function () {
  8065. if (!this._physicsFriction) {
  8066. return 0;
  8067. }
  8068. return this._physicsFriction;
  8069. };
  8070. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8071. if (!this._physicRestitution) {
  8072. return 0;
  8073. }
  8074. return this._physicRestitution;
  8075. };
  8076. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8077. if (!camera) {
  8078. camera = this.getScene().activeCamera;
  8079. }
  8080. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8081. };
  8082. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8083. if (!camera) {
  8084. camera = this.getScene().activeCamera;
  8085. }
  8086. return this.absolutePosition.subtract(camera.position).length();
  8087. };
  8088. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8089. if (!this._physicImpostor) {
  8090. return;
  8091. }
  8092. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8093. };
  8094. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8095. if (!this._physicImpostor) {
  8096. return;
  8097. }
  8098. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8099. };
  8100. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8101. if (!this._physicImpostor) {
  8102. return;
  8103. }
  8104. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8105. };
  8106. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8107. // Collisions
  8108. get: function () {
  8109. return this._checkCollisions;
  8110. },
  8111. set: function (collisionEnabled) {
  8112. this._checkCollisions = collisionEnabled;
  8113. if (this.getScene().workerCollisions) {
  8114. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8115. }
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8121. var globalPosition = this.getAbsolutePosition();
  8122. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8123. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8124. this._collider.radius = this.ellipsoid;
  8125. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8126. };
  8127. // Submeshes octree
  8128. /**
  8129. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8130. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8131. */
  8132. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8133. if (maxCapacity === void 0) { maxCapacity = 64; }
  8134. if (maxDepth === void 0) { maxDepth = 2; }
  8135. if (!this._submeshesOctree) {
  8136. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8137. }
  8138. this.computeWorldMatrix(true);
  8139. // Update octree
  8140. var bbox = this.getBoundingInfo().boundingBox;
  8141. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8142. return this._submeshesOctree;
  8143. };
  8144. // Collisions
  8145. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8146. this._generatePointsArray();
  8147. // Transformation
  8148. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8149. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8150. subMesh._lastColliderWorldVertices = [];
  8151. subMesh._trianglePlanes = [];
  8152. var start = subMesh.verticesStart;
  8153. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8154. for (var i = start; i < end; i++) {
  8155. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8156. }
  8157. }
  8158. // Collide
  8159. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8160. if (collider.collisionFound) {
  8161. collider.collidedMesh = this;
  8162. }
  8163. };
  8164. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8165. var subMeshes;
  8166. var len;
  8167. // Octrees
  8168. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8169. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8170. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8171. len = intersections.length;
  8172. subMeshes = intersections.data;
  8173. }
  8174. else {
  8175. subMeshes = this.subMeshes;
  8176. len = subMeshes.length;
  8177. }
  8178. for (var index = 0; index < len; index++) {
  8179. var subMesh = subMeshes[index];
  8180. // Bounding test
  8181. if (len > 1 && !subMesh._checkCollision(collider))
  8182. continue;
  8183. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8184. }
  8185. };
  8186. AbstractMesh.prototype._checkCollision = function (collider) {
  8187. // Bounding box test
  8188. if (!this._boundingInfo._checkCollision(collider))
  8189. return;
  8190. // Transformation matrix
  8191. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8192. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8193. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8194. };
  8195. // Picking
  8196. AbstractMesh.prototype._generatePointsArray = function () {
  8197. return false;
  8198. };
  8199. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8200. var pickingInfo = new BABYLON.PickingInfo();
  8201. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8202. return pickingInfo;
  8203. }
  8204. if (!this._generatePointsArray()) {
  8205. return pickingInfo;
  8206. }
  8207. var intersectInfo = null;
  8208. // Octrees
  8209. var subMeshes;
  8210. var len;
  8211. if (this._submeshesOctree && this.useOctreeForPicking) {
  8212. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8213. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8214. len = intersections.length;
  8215. subMeshes = intersections.data;
  8216. }
  8217. else {
  8218. subMeshes = this.subMeshes;
  8219. len = subMeshes.length;
  8220. }
  8221. for (var index = 0; index < len; index++) {
  8222. var subMesh = subMeshes[index];
  8223. // Bounding test
  8224. if (len > 1 && !subMesh.canIntersects(ray))
  8225. continue;
  8226. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8227. if (currentIntersectInfo) {
  8228. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8229. intersectInfo = currentIntersectInfo;
  8230. intersectInfo.subMeshId = index;
  8231. if (fastCheck) {
  8232. break;
  8233. }
  8234. }
  8235. }
  8236. }
  8237. if (intersectInfo) {
  8238. // Get picked point
  8239. var world = this.getWorldMatrix();
  8240. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8241. var direction = ray.direction.clone();
  8242. direction = direction.scale(intersectInfo.distance);
  8243. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8244. var pickedPoint = worldOrigin.add(worldDirection);
  8245. // Return result
  8246. pickingInfo.hit = true;
  8247. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8248. pickingInfo.pickedPoint = pickedPoint;
  8249. pickingInfo.pickedMesh = this;
  8250. pickingInfo.bu = intersectInfo.bu;
  8251. pickingInfo.bv = intersectInfo.bv;
  8252. pickingInfo.faceId = intersectInfo.faceId;
  8253. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8254. return pickingInfo;
  8255. }
  8256. return pickingInfo;
  8257. };
  8258. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8259. return null;
  8260. };
  8261. AbstractMesh.prototype.releaseSubMeshes = function () {
  8262. if (this.subMeshes) {
  8263. while (this.subMeshes.length) {
  8264. this.subMeshes[0].dispose();
  8265. }
  8266. }
  8267. else {
  8268. this.subMeshes = new Array();
  8269. }
  8270. };
  8271. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8272. var index;
  8273. // Animations
  8274. this.getScene().stopAnimation(this);
  8275. // Physics
  8276. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8277. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8278. }
  8279. // Intersections in progress
  8280. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8281. var other = this._intersectionsInProgress[index];
  8282. var pos = other._intersectionsInProgress.indexOf(this);
  8283. other._intersectionsInProgress.splice(pos, 1);
  8284. }
  8285. this._intersectionsInProgress = [];
  8286. // Edges
  8287. if (this._edgesRenderer) {
  8288. this._edgesRenderer.dispose();
  8289. this._edgesRenderer = null;
  8290. }
  8291. // SubMeshes
  8292. this.releaseSubMeshes();
  8293. // Remove from scene
  8294. this.getScene().removeMesh(this);
  8295. if (!doNotRecurse) {
  8296. // Particles
  8297. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8298. if (this.getScene().particleSystems[index].emitter === this) {
  8299. this.getScene().particleSystems[index].dispose();
  8300. index--;
  8301. }
  8302. }
  8303. // Children
  8304. var objects = this.getScene().meshes.slice(0);
  8305. for (index = 0; index < objects.length; index++) {
  8306. if (objects[index].parent === this) {
  8307. objects[index].dispose();
  8308. }
  8309. }
  8310. }
  8311. else {
  8312. for (index = 0; index < this.getScene().meshes.length; index++) {
  8313. var obj = this.getScene().meshes[index];
  8314. if (obj.parent === this) {
  8315. obj.parent = null;
  8316. obj.computeWorldMatrix(true);
  8317. }
  8318. }
  8319. }
  8320. this._onAfterWorldMatrixUpdate = [];
  8321. this._isDisposed = true;
  8322. // Callback
  8323. if (this.onDispose) {
  8324. this.onDispose();
  8325. }
  8326. };
  8327. // Statics
  8328. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8329. AbstractMesh._BILLBOARDMODE_X = 1;
  8330. AbstractMesh._BILLBOARDMODE_Y = 2;
  8331. AbstractMesh._BILLBOARDMODE_Z = 4;
  8332. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8333. return AbstractMesh;
  8334. })(BABYLON.Node);
  8335. BABYLON.AbstractMesh = AbstractMesh;
  8336. })(BABYLON || (BABYLON = {}));
  8337. var BABYLON;
  8338. (function (BABYLON) {
  8339. var Light = (function (_super) {
  8340. __extends(Light, _super);
  8341. function Light(name, scene) {
  8342. _super.call(this, name, scene);
  8343. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8344. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8345. this.intensity = 1.0;
  8346. this.range = Number.MAX_VALUE;
  8347. this.includeOnlyWithLayerMask = 0;
  8348. this.includedOnlyMeshes = new Array();
  8349. this.excludedMeshes = new Array();
  8350. this.excludeWithLayerMask = 0;
  8351. this._excludedMeshesIds = new Array();
  8352. this._includedOnlyMeshesIds = new Array();
  8353. scene.addLight(this);
  8354. }
  8355. Light.prototype.getShadowGenerator = function () {
  8356. return this._shadowGenerator;
  8357. };
  8358. Light.prototype.getAbsolutePosition = function () {
  8359. return BABYLON.Vector3.Zero();
  8360. };
  8361. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8362. };
  8363. Light.prototype._getWorldMatrix = function () {
  8364. return BABYLON.Matrix.Identity();
  8365. };
  8366. Light.prototype.canAffectMesh = function (mesh) {
  8367. if (!mesh) {
  8368. return true;
  8369. }
  8370. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8371. return false;
  8372. }
  8373. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8374. return false;
  8375. }
  8376. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8377. return false;
  8378. }
  8379. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8380. return false;
  8381. }
  8382. return true;
  8383. };
  8384. Light.prototype.getWorldMatrix = function () {
  8385. this._currentRenderId = this.getScene().getRenderId();
  8386. var worldMatrix = this._getWorldMatrix();
  8387. if (this.parent && this.parent.getWorldMatrix) {
  8388. if (!this._parentedWorldMatrix) {
  8389. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8390. }
  8391. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8392. this._markSyncedWithParent();
  8393. return this._parentedWorldMatrix;
  8394. }
  8395. return worldMatrix;
  8396. };
  8397. Light.prototype.dispose = function () {
  8398. if (this._shadowGenerator) {
  8399. this._shadowGenerator.dispose();
  8400. this._shadowGenerator = null;
  8401. }
  8402. // Animations
  8403. this.getScene().stopAnimation(this);
  8404. // Remove from scene
  8405. this.getScene().removeLight(this);
  8406. };
  8407. return Light;
  8408. })(BABYLON.Node);
  8409. BABYLON.Light = Light;
  8410. })(BABYLON || (BABYLON = {}));
  8411. var BABYLON;
  8412. (function (BABYLON) {
  8413. var PointLight = (function (_super) {
  8414. __extends(PointLight, _super);
  8415. function PointLight(name, position, scene) {
  8416. _super.call(this, name, scene);
  8417. this.position = position;
  8418. }
  8419. PointLight.prototype.getAbsolutePosition = function () {
  8420. return this.transformedPosition ? this.transformedPosition : this.position;
  8421. };
  8422. PointLight.prototype.computeTransformedPosition = function () {
  8423. if (this.parent && this.parent.getWorldMatrix) {
  8424. if (!this.transformedPosition) {
  8425. this.transformedPosition = BABYLON.Vector3.Zero();
  8426. }
  8427. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8428. return true;
  8429. }
  8430. return false;
  8431. };
  8432. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8433. if (this.parent && this.parent.getWorldMatrix) {
  8434. this.computeTransformedPosition();
  8435. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8436. return;
  8437. }
  8438. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8439. };
  8440. PointLight.prototype.needCube = function () {
  8441. return true;
  8442. };
  8443. PointLight.prototype.supportsVSM = function () {
  8444. return false;
  8445. };
  8446. PointLight.prototype.needRefreshPerFrame = function () {
  8447. return false;
  8448. };
  8449. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8450. switch (faceIndex) {
  8451. case 0:
  8452. return new BABYLON.Vector3(1, 0, 0);
  8453. case 1:
  8454. return new BABYLON.Vector3(-1, 0, 0);
  8455. case 2:
  8456. return new BABYLON.Vector3(0, -1, 0);
  8457. case 3:
  8458. return new BABYLON.Vector3(0, 1, 0);
  8459. case 4:
  8460. return new BABYLON.Vector3(0, 0, 1);
  8461. case 5:
  8462. return new BABYLON.Vector3(0, 0, -1);
  8463. }
  8464. return BABYLON.Vector3.Zero();
  8465. };
  8466. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8467. var activeCamera = this.getScene().activeCamera;
  8468. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8469. };
  8470. PointLight.prototype._getWorldMatrix = function () {
  8471. if (!this._worldMatrix) {
  8472. this._worldMatrix = BABYLON.Matrix.Identity();
  8473. }
  8474. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8475. return this._worldMatrix;
  8476. };
  8477. return PointLight;
  8478. })(BABYLON.Light);
  8479. BABYLON.PointLight = PointLight;
  8480. })(BABYLON || (BABYLON = {}));
  8481. var BABYLON;
  8482. (function (BABYLON) {
  8483. var SpotLight = (function (_super) {
  8484. __extends(SpotLight, _super);
  8485. function SpotLight(name, position, direction, angle, exponent, scene) {
  8486. _super.call(this, name, scene);
  8487. this.position = position;
  8488. this.direction = direction;
  8489. this.angle = angle;
  8490. this.exponent = exponent;
  8491. }
  8492. SpotLight.prototype.getAbsolutePosition = function () {
  8493. return this.transformedPosition ? this.transformedPosition : this.position;
  8494. };
  8495. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8496. var activeCamera = this.getScene().activeCamera;
  8497. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8498. };
  8499. SpotLight.prototype.needCube = function () {
  8500. return false;
  8501. };
  8502. SpotLight.prototype.supportsVSM = function () {
  8503. return true;
  8504. };
  8505. SpotLight.prototype.needRefreshPerFrame = function () {
  8506. return false;
  8507. };
  8508. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8509. return this.direction;
  8510. };
  8511. SpotLight.prototype.setDirectionToTarget = function (target) {
  8512. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8513. return this.direction;
  8514. };
  8515. SpotLight.prototype.computeTransformedPosition = function () {
  8516. if (this.parent && this.parent.getWorldMatrix) {
  8517. if (!this.transformedPosition) {
  8518. this.transformedPosition = BABYLON.Vector3.Zero();
  8519. }
  8520. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8521. return true;
  8522. }
  8523. return false;
  8524. };
  8525. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8526. var normalizeDirection;
  8527. if (this.parent && this.parent.getWorldMatrix) {
  8528. if (!this._transformedDirection) {
  8529. this._transformedDirection = BABYLON.Vector3.Zero();
  8530. }
  8531. this.computeTransformedPosition();
  8532. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8533. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8534. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8535. }
  8536. else {
  8537. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8538. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8539. }
  8540. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8541. };
  8542. SpotLight.prototype._getWorldMatrix = function () {
  8543. if (!this._worldMatrix) {
  8544. this._worldMatrix = BABYLON.Matrix.Identity();
  8545. }
  8546. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8547. return this._worldMatrix;
  8548. };
  8549. return SpotLight;
  8550. })(BABYLON.Light);
  8551. BABYLON.SpotLight = SpotLight;
  8552. })(BABYLON || (BABYLON = {}));
  8553. var BABYLON;
  8554. (function (BABYLON) {
  8555. var HemisphericLight = (function (_super) {
  8556. __extends(HemisphericLight, _super);
  8557. function HemisphericLight(name, direction, scene) {
  8558. _super.call(this, name, scene);
  8559. this.direction = direction;
  8560. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8561. }
  8562. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8563. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8564. return this.direction;
  8565. };
  8566. HemisphericLight.prototype.getShadowGenerator = function () {
  8567. return null;
  8568. };
  8569. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8570. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8571. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8572. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8573. };
  8574. HemisphericLight.prototype._getWorldMatrix = function () {
  8575. if (!this._worldMatrix) {
  8576. this._worldMatrix = BABYLON.Matrix.Identity();
  8577. }
  8578. return this._worldMatrix;
  8579. };
  8580. return HemisphericLight;
  8581. })(BABYLON.Light);
  8582. BABYLON.HemisphericLight = HemisphericLight;
  8583. })(BABYLON || (BABYLON = {}));
  8584. var BABYLON;
  8585. (function (BABYLON) {
  8586. var DirectionalLight = (function (_super) {
  8587. __extends(DirectionalLight, _super);
  8588. function DirectionalLight(name, direction, scene) {
  8589. _super.call(this, name, scene);
  8590. this.direction = direction;
  8591. this.shadowOrthoScale = 0.5;
  8592. this.autoUpdateExtends = true;
  8593. // Cache
  8594. this._orthoLeft = Number.MAX_VALUE;
  8595. this._orthoRight = Number.MIN_VALUE;
  8596. this._orthoTop = Number.MIN_VALUE;
  8597. this._orthoBottom = Number.MAX_VALUE;
  8598. this.position = direction.scale(-1);
  8599. }
  8600. DirectionalLight.prototype.getAbsolutePosition = function () {
  8601. return this.transformedPosition ? this.transformedPosition : this.position;
  8602. };
  8603. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8604. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8605. return this.direction;
  8606. };
  8607. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8608. var activeCamera = this.getScene().activeCamera;
  8609. // Check extends
  8610. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8611. var tempVector3 = BABYLON.Vector3.Zero();
  8612. this._orthoLeft = Number.MAX_VALUE;
  8613. this._orthoRight = Number.MIN_VALUE;
  8614. this._orthoTop = Number.MIN_VALUE;
  8615. this._orthoBottom = Number.MAX_VALUE;
  8616. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8617. var mesh = renderList[meshIndex];
  8618. if (!mesh) {
  8619. continue;
  8620. }
  8621. var boundingInfo = mesh.getBoundingInfo();
  8622. if (!boundingInfo) {
  8623. continue;
  8624. }
  8625. var boundingBox = boundingInfo.boundingBox;
  8626. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8627. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8628. if (tempVector3.x < this._orthoLeft)
  8629. this._orthoLeft = tempVector3.x;
  8630. if (tempVector3.y < this._orthoBottom)
  8631. this._orthoBottom = tempVector3.y;
  8632. if (tempVector3.x > this._orthoRight)
  8633. this._orthoRight = tempVector3.x;
  8634. if (tempVector3.y > this._orthoTop)
  8635. this._orthoTop = tempVector3.y;
  8636. }
  8637. }
  8638. }
  8639. var xOffset = this._orthoRight - this._orthoLeft;
  8640. var yOffset = this._orthoTop - this._orthoBottom;
  8641. 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);
  8642. };
  8643. DirectionalLight.prototype.supportsVSM = function () {
  8644. return true;
  8645. };
  8646. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8647. return true;
  8648. };
  8649. DirectionalLight.prototype.needCube = function () {
  8650. return false;
  8651. };
  8652. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8653. return this.direction;
  8654. };
  8655. DirectionalLight.prototype.computeTransformedPosition = function () {
  8656. if (this.parent && this.parent.getWorldMatrix) {
  8657. if (!this.transformedPosition) {
  8658. this.transformedPosition = BABYLON.Vector3.Zero();
  8659. }
  8660. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8661. return true;
  8662. }
  8663. return false;
  8664. };
  8665. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8666. if (this.parent && this.parent.getWorldMatrix) {
  8667. if (!this._transformedDirection) {
  8668. this._transformedDirection = BABYLON.Vector3.Zero();
  8669. }
  8670. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8671. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8672. return;
  8673. }
  8674. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8675. };
  8676. DirectionalLight.prototype._getWorldMatrix = function () {
  8677. if (!this._worldMatrix) {
  8678. this._worldMatrix = BABYLON.Matrix.Identity();
  8679. }
  8680. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8681. return this._worldMatrix;
  8682. };
  8683. return DirectionalLight;
  8684. })(BABYLON.Light);
  8685. BABYLON.DirectionalLight = DirectionalLight;
  8686. })(BABYLON || (BABYLON = {}));
  8687. var BABYLON;
  8688. (function (BABYLON) {
  8689. var ShadowGenerator = (function () {
  8690. function ShadowGenerator(mapSize, light) {
  8691. var _this = this;
  8692. // Members
  8693. this._filter = ShadowGenerator.FILTER_NONE;
  8694. this.blurScale = 2;
  8695. this._blurBoxOffset = 0;
  8696. this._bias = 0.00005;
  8697. this._lightDirection = BABYLON.Vector3.Zero();
  8698. this._darkness = 0;
  8699. this._transparencyShadow = false;
  8700. this._viewMatrix = BABYLON.Matrix.Zero();
  8701. this._projectionMatrix = BABYLON.Matrix.Zero();
  8702. this._transformMatrix = BABYLON.Matrix.Zero();
  8703. this._worldViewProjection = BABYLON.Matrix.Zero();
  8704. this._currentFaceIndex = 0;
  8705. this._currentFaceIndexCache = 0;
  8706. this._light = light;
  8707. this._scene = light.getScene();
  8708. this._mapSize = mapSize;
  8709. light._shadowGenerator = this;
  8710. // Render target
  8711. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8712. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8713. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8714. this._shadowMap.anisotropicFilteringLevel = 1;
  8715. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8716. this._shadowMap.renderParticles = false;
  8717. this._shadowMap.onBeforeRender = function (faceIndex) {
  8718. _this._currentFaceIndex = faceIndex;
  8719. };
  8720. this._shadowMap.onAfterUnbind = function () {
  8721. if (!_this.useBlurVarianceShadowMap) {
  8722. return;
  8723. }
  8724. if (!_this._shadowMap2) {
  8725. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8726. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8727. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8728. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8729. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8730. _this._downSamplePostprocess.onApply = function (effect) {
  8731. effect.setTexture("textureSampler", _this._shadowMap);
  8732. };
  8733. _this.blurBoxOffset = 1;
  8734. }
  8735. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8736. };
  8737. // Custom render function
  8738. var renderSubMesh = function (subMesh) {
  8739. var mesh = subMesh.getRenderingMesh();
  8740. var scene = _this._scene;
  8741. var engine = scene.getEngine();
  8742. // Culling
  8743. engine.setState(subMesh.getMaterial().backFaceCulling);
  8744. // Managing instances
  8745. var batch = mesh._getInstancesRenderList(subMesh._id);
  8746. if (batch.mustReturn) {
  8747. return;
  8748. }
  8749. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8750. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8751. engine.enableEffect(_this._effect);
  8752. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8753. var material = subMesh.getMaterial();
  8754. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8755. // Alpha test
  8756. if (material && material.needAlphaTesting()) {
  8757. var alphaTexture = material.getAlphaTestTexture();
  8758. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8759. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8760. }
  8761. // Bones
  8762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8763. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8764. }
  8765. // Draw
  8766. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8767. }
  8768. else {
  8769. // Need to reset refresh rate of the shadowMap
  8770. _this._shadowMap.resetRefreshCounter();
  8771. }
  8772. };
  8773. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8774. var index;
  8775. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8776. renderSubMesh(opaqueSubMeshes.data[index]);
  8777. }
  8778. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8779. renderSubMesh(alphaTestSubMeshes.data[index]);
  8780. }
  8781. if (_this._transparencyShadow) {
  8782. for (index = 0; index < transparentSubMeshes.length; index++) {
  8783. renderSubMesh(transparentSubMeshes.data[index]);
  8784. }
  8785. }
  8786. };
  8787. this._shadowMap.onClear = function (engine) {
  8788. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8789. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8790. }
  8791. else {
  8792. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8793. }
  8794. };
  8795. }
  8796. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8797. // Static
  8798. get: function () {
  8799. return ShadowGenerator._FILTER_NONE;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8805. get: function () {
  8806. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8812. get: function () {
  8813. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8819. get: function () {
  8820. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8821. },
  8822. enumerable: true,
  8823. configurable: true
  8824. });
  8825. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8826. get: function () {
  8827. return this._bias;
  8828. },
  8829. set: function (bias) {
  8830. this._bias = bias;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8836. get: function () {
  8837. return this._blurBoxOffset;
  8838. },
  8839. set: function (value) {
  8840. var _this = this;
  8841. if (this._blurBoxOffset === value) {
  8842. return;
  8843. }
  8844. this._blurBoxOffset = value;
  8845. if (this._boxBlurPostprocess) {
  8846. this._boxBlurPostprocess.dispose();
  8847. }
  8848. 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);
  8849. this._boxBlurPostprocess.onApply = function (effect) {
  8850. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8851. };
  8852. },
  8853. enumerable: true,
  8854. configurable: true
  8855. });
  8856. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8857. get: function () {
  8858. return this._filter;
  8859. },
  8860. set: function (value) {
  8861. if (this._filter === value) {
  8862. return;
  8863. }
  8864. this._filter = value;
  8865. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8866. this._shadowMap.anisotropicFilteringLevel = 16;
  8867. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8868. }
  8869. else {
  8870. this._shadowMap.anisotropicFilteringLevel = 1;
  8871. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8872. }
  8873. },
  8874. enumerable: true,
  8875. configurable: true
  8876. });
  8877. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8878. get: function () {
  8879. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8880. },
  8881. set: function (value) {
  8882. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8888. get: function () {
  8889. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8890. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8891. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8892. },
  8893. set: function (value) {
  8894. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8895. },
  8896. enumerable: true,
  8897. configurable: true
  8898. });
  8899. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8900. get: function () {
  8901. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8902. },
  8903. set: function (value) {
  8904. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8905. },
  8906. enumerable: true,
  8907. configurable: true
  8908. });
  8909. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8910. var defines = [];
  8911. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8912. defines.push("#define VSM");
  8913. }
  8914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8915. var mesh = subMesh.getMesh();
  8916. var material = subMesh.getMaterial();
  8917. // Alpha test
  8918. if (material && material.needAlphaTesting()) {
  8919. defines.push("#define ALPHATEST");
  8920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8921. attribs.push(BABYLON.VertexBuffer.UVKind);
  8922. defines.push("#define UV1");
  8923. }
  8924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8925. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8926. defines.push("#define UV2");
  8927. }
  8928. }
  8929. // Bones
  8930. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8933. if (mesh.numBoneInfluencers > 4) {
  8934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  8935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  8936. }
  8937. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  8938. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8939. }
  8940. else {
  8941. defines.push("#define NUM_BONE_INFLUENCERS 0");
  8942. }
  8943. // Instances
  8944. if (useInstances) {
  8945. defines.push("#define INSTANCES");
  8946. attribs.push("world0");
  8947. attribs.push("world1");
  8948. attribs.push("world2");
  8949. attribs.push("world3");
  8950. }
  8951. // Get correct effect
  8952. var join = defines.join("\n");
  8953. if (this._cachedDefines !== join) {
  8954. this._cachedDefines = join;
  8955. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8956. }
  8957. return this._effect.isReady();
  8958. };
  8959. ShadowGenerator.prototype.getShadowMap = function () {
  8960. return this._shadowMap;
  8961. };
  8962. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8963. if (this._shadowMap2) {
  8964. return this._shadowMap2;
  8965. }
  8966. return this._shadowMap;
  8967. };
  8968. ShadowGenerator.prototype.getLight = function () {
  8969. return this._light;
  8970. };
  8971. // Methods
  8972. ShadowGenerator.prototype.getTransformMatrix = function () {
  8973. var scene = this._scene;
  8974. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  8975. return this._transformMatrix;
  8976. }
  8977. this._currentRenderID = scene.getRenderId();
  8978. this._currentFaceIndexCache = this._currentFaceIndex;
  8979. var lightPosition = this._light.position;
  8980. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  8981. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  8982. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  8983. }
  8984. if (this._light.computeTransformedPosition()) {
  8985. lightPosition = this._light.transformedPosition;
  8986. }
  8987. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  8988. this._cachedPosition = lightPosition.clone();
  8989. this._cachedDirection = this._lightDirection.clone();
  8990. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8991. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8993. }
  8994. return this._transformMatrix;
  8995. };
  8996. ShadowGenerator.prototype.getDarkness = function () {
  8997. return this._darkness;
  8998. };
  8999. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9000. if (darkness >= 1.0)
  9001. this._darkness = 1.0;
  9002. else if (darkness <= 0.0)
  9003. this._darkness = 0.0;
  9004. else
  9005. this._darkness = darkness;
  9006. };
  9007. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9008. this._transparencyShadow = hasShadow;
  9009. };
  9010. ShadowGenerator.prototype._packHalf = function (depth) {
  9011. var scale = depth * 255.0;
  9012. var fract = scale - Math.floor(scale);
  9013. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9014. };
  9015. ShadowGenerator.prototype.dispose = function () {
  9016. this._shadowMap.dispose();
  9017. if (this._shadowMap2) {
  9018. this._shadowMap2.dispose();
  9019. }
  9020. if (this._downSamplePostprocess) {
  9021. this._downSamplePostprocess.dispose();
  9022. }
  9023. if (this._boxBlurPostprocess) {
  9024. this._boxBlurPostprocess.dispose();
  9025. }
  9026. };
  9027. ShadowGenerator._FILTER_NONE = 0;
  9028. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9029. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9030. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9031. return ShadowGenerator;
  9032. })();
  9033. BABYLON.ShadowGenerator = ShadowGenerator;
  9034. })(BABYLON || (BABYLON = {}));
  9035. var BABYLON;
  9036. (function (BABYLON) {
  9037. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9038. if (boxMin.x > sphereCenter.x + sphereRadius)
  9039. return false;
  9040. if (sphereCenter.x - sphereRadius > boxMax.x)
  9041. return false;
  9042. if (boxMin.y > sphereCenter.y + sphereRadius)
  9043. return false;
  9044. if (sphereCenter.y - sphereRadius > boxMax.y)
  9045. return false;
  9046. if (boxMin.z > sphereCenter.z + sphereRadius)
  9047. return false;
  9048. if (sphereCenter.z - sphereRadius > boxMax.z)
  9049. return false;
  9050. return true;
  9051. };
  9052. var getLowestRoot = function (a, b, c, maxR) {
  9053. var determinant = b * b - 4.0 * a * c;
  9054. var result = { root: 0, found: false };
  9055. if (determinant < 0)
  9056. return result;
  9057. var sqrtD = Math.sqrt(determinant);
  9058. var r1 = (-b - sqrtD) / (2.0 * a);
  9059. var r2 = (-b + sqrtD) / (2.0 * a);
  9060. if (r1 > r2) {
  9061. var temp = r2;
  9062. r2 = r1;
  9063. r1 = temp;
  9064. }
  9065. if (r1 > 0 && r1 < maxR) {
  9066. result.root = r1;
  9067. result.found = true;
  9068. return result;
  9069. }
  9070. if (r2 > 0 && r2 < maxR) {
  9071. result.root = r2;
  9072. result.found = true;
  9073. return result;
  9074. }
  9075. return result;
  9076. };
  9077. var Collider = (function () {
  9078. function Collider() {
  9079. this.radius = new BABYLON.Vector3(1, 1, 1);
  9080. this.retry = 0;
  9081. this.basePointWorld = BABYLON.Vector3.Zero();
  9082. this.velocityWorld = BABYLON.Vector3.Zero();
  9083. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9084. this._collisionPoint = BABYLON.Vector3.Zero();
  9085. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9086. this._tempVector = BABYLON.Vector3.Zero();
  9087. this._tempVector2 = BABYLON.Vector3.Zero();
  9088. this._tempVector3 = BABYLON.Vector3.Zero();
  9089. this._tempVector4 = BABYLON.Vector3.Zero();
  9090. this._edge = BABYLON.Vector3.Zero();
  9091. this._baseToVertex = BABYLON.Vector3.Zero();
  9092. this._destinationPoint = BABYLON.Vector3.Zero();
  9093. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9094. this._displacementVector = BABYLON.Vector3.Zero();
  9095. }
  9096. // Methods
  9097. Collider.prototype._initialize = function (source, dir, e) {
  9098. this.velocity = dir;
  9099. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9100. this.basePoint = source;
  9101. source.multiplyToRef(this.radius, this.basePointWorld);
  9102. dir.multiplyToRef(this.radius, this.velocityWorld);
  9103. this.velocityWorldLength = this.velocityWorld.length();
  9104. this.epsilon = e;
  9105. this.collisionFound = false;
  9106. };
  9107. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9108. pa.subtractToRef(point, this._tempVector);
  9109. pb.subtractToRef(point, this._tempVector2);
  9110. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9111. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9112. if (d < 0)
  9113. return false;
  9114. pc.subtractToRef(point, this._tempVector3);
  9115. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9116. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9117. if (d < 0)
  9118. return false;
  9119. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9120. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9121. return d >= 0;
  9122. };
  9123. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9124. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9125. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9126. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9127. return false;
  9128. }
  9129. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9130. return false;
  9131. return true;
  9132. };
  9133. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9134. var t0;
  9135. var embeddedInPlane = false;
  9136. //defensive programming, actually not needed.
  9137. if (!trianglePlaneArray) {
  9138. trianglePlaneArray = [];
  9139. }
  9140. if (!trianglePlaneArray[faceIndex]) {
  9141. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9142. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9143. }
  9144. var trianglePlane = trianglePlaneArray[faceIndex];
  9145. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9146. return;
  9147. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9148. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9149. if (normalDotVelocity == 0) {
  9150. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9151. return;
  9152. embeddedInPlane = true;
  9153. t0 = 0;
  9154. }
  9155. else {
  9156. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9157. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9158. if (t0 > t1) {
  9159. var temp = t1;
  9160. t1 = t0;
  9161. t0 = temp;
  9162. }
  9163. if (t0 > 1.0 || t1 < 0.0)
  9164. return;
  9165. if (t0 < 0)
  9166. t0 = 0;
  9167. if (t0 > 1.0)
  9168. t0 = 1.0;
  9169. }
  9170. this._collisionPoint.copyFromFloats(0, 0, 0);
  9171. var found = false;
  9172. var t = 1.0;
  9173. if (!embeddedInPlane) {
  9174. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9175. this.velocity.scaleToRef(t0, this._tempVector);
  9176. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9177. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9178. found = true;
  9179. t = t0;
  9180. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9181. }
  9182. }
  9183. if (!found) {
  9184. var velocitySquaredLength = this.velocity.lengthSquared();
  9185. var a = velocitySquaredLength;
  9186. this.basePoint.subtractToRef(p1, this._tempVector);
  9187. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9188. var c = this._tempVector.lengthSquared() - 1.0;
  9189. var lowestRoot = getLowestRoot(a, b, c, t);
  9190. if (lowestRoot.found) {
  9191. t = lowestRoot.root;
  9192. found = true;
  9193. this._collisionPoint.copyFrom(p1);
  9194. }
  9195. this.basePoint.subtractToRef(p2, this._tempVector);
  9196. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9197. c = this._tempVector.lengthSquared() - 1.0;
  9198. lowestRoot = getLowestRoot(a, b, c, t);
  9199. if (lowestRoot.found) {
  9200. t = lowestRoot.root;
  9201. found = true;
  9202. this._collisionPoint.copyFrom(p2);
  9203. }
  9204. this.basePoint.subtractToRef(p3, this._tempVector);
  9205. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9206. c = this._tempVector.lengthSquared() - 1.0;
  9207. lowestRoot = getLowestRoot(a, b, c, t);
  9208. if (lowestRoot.found) {
  9209. t = lowestRoot.root;
  9210. found = true;
  9211. this._collisionPoint.copyFrom(p3);
  9212. }
  9213. p2.subtractToRef(p1, this._edge);
  9214. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9215. var edgeSquaredLength = this._edge.lengthSquared();
  9216. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9217. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9218. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9219. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9220. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9221. lowestRoot = getLowestRoot(a, b, c, t);
  9222. if (lowestRoot.found) {
  9223. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9224. if (f >= 0.0 && f <= 1.0) {
  9225. t = lowestRoot.root;
  9226. found = true;
  9227. this._edge.scaleInPlace(f);
  9228. p1.addToRef(this._edge, this._collisionPoint);
  9229. }
  9230. }
  9231. p3.subtractToRef(p2, this._edge);
  9232. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9233. edgeSquaredLength = this._edge.lengthSquared();
  9234. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9235. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9236. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9237. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9238. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9239. lowestRoot = getLowestRoot(a, b, c, t);
  9240. if (lowestRoot.found) {
  9241. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9242. if (f >= 0.0 && f <= 1.0) {
  9243. t = lowestRoot.root;
  9244. found = true;
  9245. this._edge.scaleInPlace(f);
  9246. p2.addToRef(this._edge, this._collisionPoint);
  9247. }
  9248. }
  9249. p1.subtractToRef(p3, this._edge);
  9250. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9251. edgeSquaredLength = this._edge.lengthSquared();
  9252. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9253. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9254. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9255. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9256. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9257. lowestRoot = getLowestRoot(a, b, c, t);
  9258. if (lowestRoot.found) {
  9259. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9260. if (f >= 0.0 && f <= 1.0) {
  9261. t = lowestRoot.root;
  9262. found = true;
  9263. this._edge.scaleInPlace(f);
  9264. p3.addToRef(this._edge, this._collisionPoint);
  9265. }
  9266. }
  9267. }
  9268. if (found) {
  9269. var distToCollision = t * this.velocity.length();
  9270. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9271. if (!this.intersectionPoint) {
  9272. this.intersectionPoint = this._collisionPoint.clone();
  9273. }
  9274. else {
  9275. this.intersectionPoint.copyFrom(this._collisionPoint);
  9276. }
  9277. this.nearestDistance = distToCollision;
  9278. this.collisionFound = true;
  9279. }
  9280. }
  9281. };
  9282. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9283. for (var i = indexStart; i < indexEnd; i += 3) {
  9284. var p1 = pts[indices[i] - decal];
  9285. var p2 = pts[indices[i + 1] - decal];
  9286. var p3 = pts[indices[i + 2] - decal];
  9287. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9288. }
  9289. };
  9290. Collider.prototype._getResponse = function (pos, vel) {
  9291. pos.addToRef(vel, this._destinationPoint);
  9292. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9293. this.basePoint.addToRef(vel, pos);
  9294. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9295. this._slidePlaneNormal.normalize();
  9296. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9297. pos.addInPlace(this._displacementVector);
  9298. this.intersectionPoint.addInPlace(this._displacementVector);
  9299. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9300. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9301. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9302. };
  9303. return Collider;
  9304. })();
  9305. BABYLON.Collider = Collider;
  9306. })(BABYLON || (BABYLON = {}));
  9307. var BABYLON;
  9308. (function (BABYLON) {
  9309. //WebWorker code will be inserted to this variable.
  9310. BABYLON.CollisionWorker = "";
  9311. (function (WorkerTaskType) {
  9312. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9313. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9314. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9315. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9316. var WorkerTaskType = BABYLON.WorkerTaskType;
  9317. (function (WorkerReplyType) {
  9318. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9319. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9320. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9321. var WorkerReplyType = BABYLON.WorkerReplyType;
  9322. var CollisionCoordinatorWorker = (function () {
  9323. function CollisionCoordinatorWorker() {
  9324. var _this = this;
  9325. this._scaledPosition = BABYLON.Vector3.Zero();
  9326. this._scaledVelocity = BABYLON.Vector3.Zero();
  9327. this.onMeshUpdated = function (mesh) {
  9328. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9329. };
  9330. this.onGeometryUpdated = function (geometry) {
  9331. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9332. };
  9333. this._afterRender = function () {
  9334. if (!_this._init)
  9335. return;
  9336. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9337. return;
  9338. }
  9339. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9340. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9341. if (_this._runningUpdated > 4) {
  9342. return;
  9343. }
  9344. ++_this._runningUpdated;
  9345. var payload = {
  9346. updatedMeshes: _this._addUpdateMeshesList,
  9347. updatedGeometries: _this._addUpdateGeometriesList,
  9348. removedGeometries: _this._toRemoveGeometryArray,
  9349. removedMeshes: _this._toRemoveMeshesArray
  9350. };
  9351. var message = {
  9352. payload: payload,
  9353. taskType: WorkerTaskType.UPDATE
  9354. };
  9355. var serializable = [];
  9356. for (var id in payload.updatedGeometries) {
  9357. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9358. //prepare transferables
  9359. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9360. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9361. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9362. }
  9363. }
  9364. _this._worker.postMessage(message, serializable);
  9365. _this._addUpdateMeshesList = {};
  9366. _this._addUpdateGeometriesList = {};
  9367. _this._toRemoveGeometryArray = [];
  9368. _this._toRemoveMeshesArray = [];
  9369. };
  9370. this._onMessageFromWorker = function (e) {
  9371. var returnData = e.data;
  9372. if (returnData.error != WorkerReplyType.SUCCESS) {
  9373. //TODO what errors can be returned from the worker?
  9374. BABYLON.Tools.Warn("error returned from worker!");
  9375. return;
  9376. }
  9377. switch (returnData.taskType) {
  9378. case WorkerTaskType.INIT:
  9379. _this._init = true;
  9380. //Update the worked with ALL of the scene's current state
  9381. _this._scene.meshes.forEach(function (mesh) {
  9382. _this.onMeshAdded(mesh);
  9383. });
  9384. _this._scene.getGeometries().forEach(function (geometry) {
  9385. _this.onGeometryAdded(geometry);
  9386. });
  9387. break;
  9388. case WorkerTaskType.UPDATE:
  9389. _this._runningUpdated--;
  9390. break;
  9391. case WorkerTaskType.COLLIDE:
  9392. _this._runningCollisionTask = false;
  9393. var returnPayload = returnData.payload;
  9394. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9395. return;
  9396. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9397. //cleanup
  9398. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9399. break;
  9400. }
  9401. };
  9402. this._collisionsCallbackArray = [];
  9403. this._init = false;
  9404. this._runningUpdated = 0;
  9405. this._runningCollisionTask = false;
  9406. this._addUpdateMeshesList = {};
  9407. this._addUpdateGeometriesList = {};
  9408. this._toRemoveGeometryArray = [];
  9409. this._toRemoveMeshesArray = [];
  9410. }
  9411. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9412. if (!this._init)
  9413. return;
  9414. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9415. return;
  9416. position.divideToRef(collider.radius, this._scaledPosition);
  9417. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9418. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9419. var payload = {
  9420. collider: {
  9421. position: this._scaledPosition.asArray(),
  9422. velocity: this._scaledVelocity.asArray(),
  9423. radius: collider.radius.asArray()
  9424. },
  9425. collisionId: collisionIndex,
  9426. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9427. maximumRetry: maximumRetry
  9428. };
  9429. var message = {
  9430. payload: payload,
  9431. taskType: WorkerTaskType.COLLIDE
  9432. };
  9433. this._worker.postMessage(message);
  9434. };
  9435. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9436. this._scene = scene;
  9437. this._scene.registerAfterRender(this._afterRender);
  9438. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9439. this._worker = new Worker(workerUrl);
  9440. this._worker.onmessage = this._onMessageFromWorker;
  9441. var message = {
  9442. payload: {},
  9443. taskType: WorkerTaskType.INIT
  9444. };
  9445. this._worker.postMessage(message);
  9446. };
  9447. CollisionCoordinatorWorker.prototype.destroy = function () {
  9448. this._scene.unregisterAfterRender(this._afterRender);
  9449. this._worker.terminate();
  9450. };
  9451. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9452. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9453. this.onMeshUpdated(mesh);
  9454. };
  9455. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9456. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9457. };
  9458. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9459. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9460. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9461. this.onGeometryUpdated(geometry);
  9462. };
  9463. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9464. this._toRemoveGeometryArray.push(geometry.id);
  9465. };
  9466. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9467. var submeshes = [];
  9468. if (mesh.subMeshes) {
  9469. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9470. return {
  9471. position: idx,
  9472. verticesStart: sm.verticesStart,
  9473. verticesCount: sm.verticesCount,
  9474. indexStart: sm.indexStart,
  9475. indexCount: sm.indexCount,
  9476. hasMaterial: !!sm.getMaterial(),
  9477. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9478. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9479. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9480. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9481. };
  9482. });
  9483. }
  9484. var geometryId = null;
  9485. if (mesh instanceof BABYLON.Mesh) {
  9486. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9487. }
  9488. else if (mesh instanceof BABYLON.InstancedMesh) {
  9489. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9490. }
  9491. return {
  9492. uniqueId: mesh.uniqueId,
  9493. id: mesh.id,
  9494. name: mesh.name,
  9495. geometryId: geometryId,
  9496. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9497. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9498. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9499. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9500. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9501. subMeshes: submeshes,
  9502. checkCollisions: mesh.checkCollisions
  9503. };
  9504. };
  9505. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9506. return {
  9507. id: geometry.id,
  9508. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9509. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9510. indices: new Int32Array(geometry.getIndices() || []),
  9511. };
  9512. };
  9513. return CollisionCoordinatorWorker;
  9514. })();
  9515. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9516. var CollisionCoordinatorLegacy = (function () {
  9517. function CollisionCoordinatorLegacy() {
  9518. this._scaledPosition = BABYLON.Vector3.Zero();
  9519. this._scaledVelocity = BABYLON.Vector3.Zero();
  9520. this._finalPosition = BABYLON.Vector3.Zero();
  9521. }
  9522. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9523. position.divideToRef(collider.radius, this._scaledPosition);
  9524. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9525. collider.collidedMesh = null;
  9526. collider.retry = 0;
  9527. collider.initialVelocity = this._scaledVelocity;
  9528. collider.initialPosition = this._scaledPosition;
  9529. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9530. this._finalPosition.multiplyInPlace(collider.radius);
  9531. //run the callback
  9532. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9533. };
  9534. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9535. this._scene = scene;
  9536. };
  9537. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9538. //Legacy need no destruction method.
  9539. };
  9540. //No update in legacy mode
  9541. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9542. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9543. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9544. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9545. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9546. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9547. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9548. if (excludedMesh === void 0) { excludedMesh = null; }
  9549. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9550. if (collider.retry >= maximumRetry) {
  9551. finalPosition.copyFrom(position);
  9552. return;
  9553. }
  9554. collider._initialize(position, velocity, closeDistance);
  9555. // Check all meshes
  9556. for (var index = 0; index < this._scene.meshes.length; index++) {
  9557. var mesh = this._scene.meshes[index];
  9558. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9559. mesh._checkCollision(collider);
  9560. }
  9561. }
  9562. if (!collider.collisionFound) {
  9563. position.addToRef(velocity, finalPosition);
  9564. return;
  9565. }
  9566. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9567. collider._getResponse(position, velocity);
  9568. }
  9569. if (velocity.length() <= closeDistance) {
  9570. finalPosition.copyFrom(position);
  9571. return;
  9572. }
  9573. collider.retry++;
  9574. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9575. };
  9576. return CollisionCoordinatorLegacy;
  9577. })();
  9578. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9579. })(BABYLON || (BABYLON = {}));
  9580. var BABYLON;
  9581. (function (BABYLON) {
  9582. var VRCameraMetrics = (function () {
  9583. function VRCameraMetrics() {
  9584. this.compensateDistortion = true;
  9585. }
  9586. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9587. get: function () {
  9588. return this.hResolution / (2 * this.vResolution);
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9594. get: function () {
  9595. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9601. get: function () {
  9602. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9603. var h = (4 * meters) / this.hScreenSize;
  9604. return BABYLON.Matrix.Translation(h, 0, 0);
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9610. get: function () {
  9611. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9612. var h = (4 * meters) / this.hScreenSize;
  9613. return BABYLON.Matrix.Translation(-h, 0, 0);
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9619. get: function () {
  9620. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9626. get: function () {
  9627. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. VRCameraMetrics.GetDefault = function () {
  9633. var result = new VRCameraMetrics();
  9634. result.hResolution = 1280;
  9635. result.vResolution = 800;
  9636. result.hScreenSize = 0.149759993;
  9637. result.vScreenSize = 0.0935999975;
  9638. result.vScreenCenter = 0.0467999987,
  9639. result.eyeToScreenDistance = 0.0410000011;
  9640. result.lensSeparationDistance = 0.0635000020;
  9641. result.interpupillaryDistance = 0.0640000030;
  9642. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9643. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9644. result.postProcessScaleFactor = 1.714605507808412;
  9645. result.lensCenterOffset = 0.151976421;
  9646. return result;
  9647. };
  9648. return VRCameraMetrics;
  9649. })();
  9650. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9651. var Camera = (function (_super) {
  9652. __extends(Camera, _super);
  9653. function Camera(name, position, scene) {
  9654. _super.call(this, name, scene);
  9655. this.position = position;
  9656. // Members
  9657. this.upVector = BABYLON.Vector3.Up();
  9658. this.orthoLeft = null;
  9659. this.orthoRight = null;
  9660. this.orthoBottom = null;
  9661. this.orthoTop = null;
  9662. this.fov = 0.8;
  9663. this.minZ = 1.0;
  9664. this.maxZ = 10000.0;
  9665. this.inertia = 0.9;
  9666. this.mode = Camera.PERSPECTIVE_CAMERA;
  9667. this.isIntermediate = false;
  9668. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9669. this.layerMask = 0x0FFFFFFF;
  9670. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9671. // Camera rig members
  9672. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9673. this._rigCameras = new Array();
  9674. // Cache
  9675. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9676. this._projectionMatrix = new BABYLON.Matrix();
  9677. this._postProcesses = new Array();
  9678. this._postProcessesTakenIndices = [];
  9679. this._activeMeshes = new BABYLON.SmartArray(256);
  9680. this._globalPosition = BABYLON.Vector3.Zero();
  9681. scene.addCamera(this);
  9682. if (!scene.activeCamera) {
  9683. scene.activeCamera = this;
  9684. }
  9685. }
  9686. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9687. get: function () {
  9688. return Camera._PERSPECTIVE_CAMERA;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9694. get: function () {
  9695. return Camera._ORTHOGRAPHIC_CAMERA;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9701. get: function () {
  9702. return Camera._FOVMODE_VERTICAL_FIXED;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9708. get: function () {
  9709. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9715. get: function () {
  9716. return Camera._RIG_MODE_NONE;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9722. get: function () {
  9723. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9729. get: function () {
  9730. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9736. get: function () {
  9737. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9743. get: function () {
  9744. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9750. get: function () {
  9751. return Camera._RIG_MODE_VR;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(Camera.prototype, "globalPosition", {
  9757. get: function () {
  9758. return this._globalPosition;
  9759. },
  9760. enumerable: true,
  9761. configurable: true
  9762. });
  9763. Camera.prototype.getActiveMeshes = function () {
  9764. return this._activeMeshes;
  9765. };
  9766. Camera.prototype.isActiveMesh = function (mesh) {
  9767. return (this._activeMeshes.indexOf(mesh) !== -1);
  9768. };
  9769. //Cache
  9770. Camera.prototype._initCache = function () {
  9771. _super.prototype._initCache.call(this);
  9772. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9773. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9774. this._cache.mode = undefined;
  9775. this._cache.minZ = undefined;
  9776. this._cache.maxZ = undefined;
  9777. this._cache.fov = undefined;
  9778. this._cache.aspectRatio = undefined;
  9779. this._cache.orthoLeft = undefined;
  9780. this._cache.orthoRight = undefined;
  9781. this._cache.orthoBottom = undefined;
  9782. this._cache.orthoTop = undefined;
  9783. this._cache.renderWidth = undefined;
  9784. this._cache.renderHeight = undefined;
  9785. };
  9786. Camera.prototype._updateCache = function (ignoreParentClass) {
  9787. if (!ignoreParentClass) {
  9788. _super.prototype._updateCache.call(this);
  9789. }
  9790. var engine = this.getEngine();
  9791. this._cache.position.copyFrom(this.position);
  9792. this._cache.upVector.copyFrom(this.upVector);
  9793. this._cache.mode = this.mode;
  9794. this._cache.minZ = this.minZ;
  9795. this._cache.maxZ = this.maxZ;
  9796. this._cache.fov = this.fov;
  9797. this._cache.aspectRatio = engine.getAspectRatio(this);
  9798. this._cache.orthoLeft = this.orthoLeft;
  9799. this._cache.orthoRight = this.orthoRight;
  9800. this._cache.orthoBottom = this.orthoBottom;
  9801. this._cache.orthoTop = this.orthoTop;
  9802. this._cache.renderWidth = engine.getRenderWidth();
  9803. this._cache.renderHeight = engine.getRenderHeight();
  9804. };
  9805. Camera.prototype._updateFromScene = function () {
  9806. this.updateCache();
  9807. this._update();
  9808. };
  9809. // Synchronized
  9810. Camera.prototype._isSynchronized = function () {
  9811. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9812. };
  9813. Camera.prototype._isSynchronizedViewMatrix = function () {
  9814. if (!_super.prototype._isSynchronized.call(this))
  9815. return false;
  9816. return this._cache.position.equals(this.position)
  9817. && this._cache.upVector.equals(this.upVector)
  9818. && this.isSynchronizedWithParent();
  9819. };
  9820. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9821. var check = this._cache.mode === this.mode
  9822. && this._cache.minZ === this.minZ
  9823. && this._cache.maxZ === this.maxZ;
  9824. if (!check) {
  9825. return false;
  9826. }
  9827. var engine = this.getEngine();
  9828. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9829. check = this._cache.fov === this.fov
  9830. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9831. }
  9832. else {
  9833. check = this._cache.orthoLeft === this.orthoLeft
  9834. && this._cache.orthoRight === this.orthoRight
  9835. && this._cache.orthoBottom === this.orthoBottom
  9836. && this._cache.orthoTop === this.orthoTop
  9837. && this._cache.renderWidth === engine.getRenderWidth()
  9838. && this._cache.renderHeight === engine.getRenderHeight();
  9839. }
  9840. return check;
  9841. };
  9842. // Controls
  9843. Camera.prototype.attachControl = function (element) {
  9844. };
  9845. Camera.prototype.detachControl = function (element) {
  9846. };
  9847. Camera.prototype._update = function () {
  9848. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9849. this._updateRigCameras();
  9850. }
  9851. this._checkInputs();
  9852. };
  9853. Camera.prototype._checkInputs = function () {
  9854. };
  9855. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9856. if (insertAt === void 0) { insertAt = null; }
  9857. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9858. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9859. return 0;
  9860. }
  9861. if (insertAt == null || insertAt < 0) {
  9862. this._postProcesses.push(postProcess);
  9863. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9864. return this._postProcesses.length - 1;
  9865. }
  9866. var add = 0;
  9867. var i;
  9868. var start;
  9869. if (this._postProcesses[insertAt]) {
  9870. start = this._postProcesses.length - 1;
  9871. for (i = start; i >= insertAt + 1; --i) {
  9872. this._postProcesses[i + 1] = this._postProcesses[i];
  9873. }
  9874. add = 1;
  9875. }
  9876. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9877. if (this._postProcessesTakenIndices[i] < insertAt) {
  9878. continue;
  9879. }
  9880. start = this._postProcessesTakenIndices.length - 1;
  9881. for (var j = start; j >= i; --j) {
  9882. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9883. }
  9884. this._postProcessesTakenIndices[i] = insertAt;
  9885. break;
  9886. }
  9887. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9888. this._postProcessesTakenIndices.push(insertAt);
  9889. }
  9890. var result = insertAt + add;
  9891. this._postProcesses[result] = postProcess;
  9892. return result;
  9893. };
  9894. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9895. if (atIndices === void 0) { atIndices = null; }
  9896. var result = [];
  9897. var i;
  9898. var index;
  9899. if (!atIndices) {
  9900. var length = this._postProcesses.length;
  9901. for (i = 0; i < length; i++) {
  9902. if (this._postProcesses[i] !== postProcess) {
  9903. continue;
  9904. }
  9905. delete this._postProcesses[i];
  9906. index = this._postProcessesTakenIndices.indexOf(i);
  9907. this._postProcessesTakenIndices.splice(index, 1);
  9908. }
  9909. }
  9910. else {
  9911. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9912. for (i = 0; i < atIndices.length; i++) {
  9913. var foundPostProcess = this._postProcesses[atIndices[i]];
  9914. if (foundPostProcess !== postProcess) {
  9915. result.push(i);
  9916. continue;
  9917. }
  9918. delete this._postProcesses[atIndices[i]];
  9919. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9920. this._postProcessesTakenIndices.splice(index, 1);
  9921. }
  9922. }
  9923. return result;
  9924. };
  9925. Camera.prototype.getWorldMatrix = function () {
  9926. if (!this._worldMatrix) {
  9927. this._worldMatrix = BABYLON.Matrix.Identity();
  9928. }
  9929. var viewMatrix = this.getViewMatrix();
  9930. viewMatrix.invertToRef(this._worldMatrix);
  9931. return this._worldMatrix;
  9932. };
  9933. Camera.prototype._getViewMatrix = function () {
  9934. return BABYLON.Matrix.Identity();
  9935. };
  9936. Camera.prototype.getViewMatrix = function (force) {
  9937. this._computedViewMatrix = this._computeViewMatrix(force);
  9938. if (!force && this._isSynchronizedViewMatrix()) {
  9939. return this._computedViewMatrix;
  9940. }
  9941. if (!this.parent || !this.parent.getWorldMatrix) {
  9942. this._globalPosition.copyFrom(this.position);
  9943. }
  9944. else {
  9945. if (!this._worldMatrix) {
  9946. this._worldMatrix = BABYLON.Matrix.Identity();
  9947. }
  9948. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9949. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9950. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9951. this._computedViewMatrix.invert();
  9952. this._markSyncedWithParent();
  9953. }
  9954. this._currentRenderId = this.getScene().getRenderId();
  9955. return this._computedViewMatrix;
  9956. };
  9957. Camera.prototype._computeViewMatrix = function (force) {
  9958. if (!force && this._isSynchronizedViewMatrix()) {
  9959. return this._computedViewMatrix;
  9960. }
  9961. this._computedViewMatrix = this._getViewMatrix();
  9962. this._currentRenderId = this.getScene().getRenderId();
  9963. return this._computedViewMatrix;
  9964. };
  9965. Camera.prototype.getProjectionMatrix = function (force) {
  9966. if (!force && this._isSynchronizedProjectionMatrix()) {
  9967. return this._projectionMatrix;
  9968. }
  9969. var engine = this.getEngine();
  9970. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9971. if (this.minZ <= 0) {
  9972. this.minZ = 0.1;
  9973. }
  9974. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9975. return this._projectionMatrix;
  9976. }
  9977. var halfWidth = engine.getRenderWidth() / 2.0;
  9978. var halfHeight = engine.getRenderHeight() / 2.0;
  9979. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9980. return this._projectionMatrix;
  9981. };
  9982. Camera.prototype.dispose = function () {
  9983. // Animations
  9984. this.getScene().stopAnimation(this);
  9985. // Remove from scene
  9986. this.getScene().removeCamera(this);
  9987. while (this._rigCameras.length > 0) {
  9988. this._rigCameras.pop().dispose();
  9989. }
  9990. // Postprocesses
  9991. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9992. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9993. }
  9994. };
  9995. // ---- Camera rigs section ----
  9996. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9997. while (this._rigCameras.length > 0) {
  9998. this._rigCameras.pop().dispose();
  9999. }
  10000. this.cameraRigMode = mode;
  10001. this._cameraRigParams = {};
  10002. switch (this.cameraRigMode) {
  10003. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10004. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10005. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10006. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10007. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10008. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10009. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10010. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10011. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10012. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10013. break;
  10014. }
  10015. var postProcesses = new Array();
  10016. switch (this.cameraRigMode) {
  10017. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10018. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10019. this._rigCameras[0].isIntermediate = true;
  10020. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10021. postProcesses[1].onApply = function (effect) {
  10022. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10023. };
  10024. break;
  10025. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10026. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10027. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10028. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10029. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10030. var secondCamIndex = 1 - firstCamIndex;
  10031. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10032. this._rigCameras[firstCamIndex].isIntermediate = true;
  10033. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10034. break;
  10035. case Camera.RIG_MODE_VR:
  10036. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10037. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10038. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10039. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10040. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10041. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10042. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10043. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10044. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10045. if (metrics.compensateDistortion) {
  10046. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10047. }
  10048. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10049. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10050. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10051. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10052. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10053. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10054. if (metrics.compensateDistortion) {
  10055. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10056. }
  10057. break;
  10058. }
  10059. this._update();
  10060. };
  10061. Camera.prototype._getVRProjectionMatrix = function () {
  10062. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10063. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10064. return this._projectionMatrix;
  10065. };
  10066. Camera.prototype.setCameraRigParameter = function (name, value) {
  10067. this._cameraRigParams[name] = value;
  10068. //provisionnally:
  10069. if (name === "interaxialDistance") {
  10070. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10071. }
  10072. };
  10073. /**
  10074. * May needs to be overridden by children so sub has required properties to be copied
  10075. */
  10076. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10077. return null;
  10078. };
  10079. /**
  10080. * May needs to be overridden by children
  10081. */
  10082. Camera.prototype._updateRigCameras = function () {
  10083. for (var i = 0; i < this._rigCameras.length; i++) {
  10084. this._rigCameras[i].minZ = this.minZ;
  10085. this._rigCameras[i].maxZ = this.maxZ;
  10086. this._rigCameras[i].fov = this.fov;
  10087. }
  10088. // only update viewport when ANAGLYPH
  10089. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10090. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10091. }
  10092. };
  10093. // Statics
  10094. Camera._PERSPECTIVE_CAMERA = 0;
  10095. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10096. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10097. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10098. Camera._RIG_MODE_NONE = 0;
  10099. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10100. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10101. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10102. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10103. Camera._RIG_MODE_VR = 20;
  10104. return Camera;
  10105. })(BABYLON.Node);
  10106. BABYLON.Camera = Camera;
  10107. })(BABYLON || (BABYLON = {}));
  10108. var BABYLON;
  10109. (function (BABYLON) {
  10110. var TargetCamera = (function (_super) {
  10111. __extends(TargetCamera, _super);
  10112. function TargetCamera(name, position, scene) {
  10113. _super.call(this, name, position, scene);
  10114. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10115. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10116. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10117. this.speed = 2.0;
  10118. this.noRotationConstraint = false;
  10119. this.lockedTarget = null;
  10120. this._currentTarget = BABYLON.Vector3.Zero();
  10121. this._viewMatrix = BABYLON.Matrix.Zero();
  10122. this._camMatrix = BABYLON.Matrix.Zero();
  10123. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10124. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10125. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10126. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10127. this._lookAtTemp = BABYLON.Matrix.Zero();
  10128. this._tempMatrix = BABYLON.Matrix.Zero();
  10129. }
  10130. TargetCamera.prototype.getFrontPosition = function (distance) {
  10131. var direction = this.getTarget().subtract(this.position);
  10132. direction.normalize();
  10133. direction.scaleInPlace(distance);
  10134. return this.globalPosition.add(direction);
  10135. };
  10136. TargetCamera.prototype._getLockedTargetPosition = function () {
  10137. if (!this.lockedTarget) {
  10138. return null;
  10139. }
  10140. return this.lockedTarget.position || this.lockedTarget;
  10141. };
  10142. // Cache
  10143. TargetCamera.prototype._initCache = function () {
  10144. _super.prototype._initCache.call(this);
  10145. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10146. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10147. };
  10148. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10149. if (!ignoreParentClass) {
  10150. _super.prototype._updateCache.call(this);
  10151. }
  10152. var lockedTargetPosition = this._getLockedTargetPosition();
  10153. if (!lockedTargetPosition) {
  10154. this._cache.lockedTarget = null;
  10155. }
  10156. else {
  10157. if (!this._cache.lockedTarget) {
  10158. this._cache.lockedTarget = lockedTargetPosition.clone();
  10159. }
  10160. else {
  10161. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10162. }
  10163. }
  10164. this._cache.rotation.copyFrom(this.rotation);
  10165. };
  10166. // Synchronized
  10167. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10168. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10169. return false;
  10170. }
  10171. var lockedTargetPosition = this._getLockedTargetPosition();
  10172. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10173. && this._cache.rotation.equals(this.rotation);
  10174. };
  10175. // Methods
  10176. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10177. var engine = this.getEngine();
  10178. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10179. };
  10180. // Target
  10181. TargetCamera.prototype.setTarget = function (target) {
  10182. this.upVector.normalize();
  10183. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10184. this._camMatrix.invert();
  10185. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10186. var vDir = target.subtract(this.position);
  10187. if (vDir.x >= 0.0) {
  10188. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10189. }
  10190. else {
  10191. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10192. }
  10193. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10194. if (isNaN(this.rotation.x)) {
  10195. this.rotation.x = 0;
  10196. }
  10197. if (isNaN(this.rotation.y)) {
  10198. this.rotation.y = 0;
  10199. }
  10200. if (isNaN(this.rotation.z)) {
  10201. this.rotation.z = 0;
  10202. }
  10203. };
  10204. TargetCamera.prototype.getTarget = function () {
  10205. return this._currentTarget;
  10206. };
  10207. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10208. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10209. };
  10210. TargetCamera.prototype._updatePosition = function () {
  10211. this.position.addInPlace(this.cameraDirection);
  10212. };
  10213. TargetCamera.prototype._checkInputs = function () {
  10214. var needToMove = this._decideIfNeedsToMove();
  10215. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10216. // Move
  10217. if (needToMove) {
  10218. this._updatePosition();
  10219. }
  10220. // Rotate
  10221. if (needToRotate) {
  10222. this.rotation.x += this.cameraRotation.x;
  10223. this.rotation.y += this.cameraRotation.y;
  10224. if (!this.noRotationConstraint) {
  10225. var limit = (Math.PI / 2) * 0.95;
  10226. if (this.rotation.x > limit)
  10227. this.rotation.x = limit;
  10228. if (this.rotation.x < -limit)
  10229. this.rotation.x = -limit;
  10230. }
  10231. }
  10232. // Inertia
  10233. if (needToMove) {
  10234. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10235. this.cameraDirection.x = 0;
  10236. }
  10237. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10238. this.cameraDirection.y = 0;
  10239. }
  10240. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10241. this.cameraDirection.z = 0;
  10242. }
  10243. this.cameraDirection.scaleInPlace(this.inertia);
  10244. }
  10245. if (needToRotate) {
  10246. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10247. this.cameraRotation.x = 0;
  10248. }
  10249. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10250. this.cameraRotation.y = 0;
  10251. }
  10252. this.cameraRotation.scaleInPlace(this.inertia);
  10253. }
  10254. _super.prototype._checkInputs.call(this);
  10255. };
  10256. TargetCamera.prototype._getViewMatrix = function () {
  10257. if (!this.lockedTarget) {
  10258. // Compute
  10259. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10260. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10261. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10262. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10263. this._lookAtTemp.invert();
  10264. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10265. }
  10266. else {
  10267. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10268. }
  10269. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10270. // Computing target and final matrix
  10271. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10272. }
  10273. else {
  10274. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10275. }
  10276. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10277. return this._viewMatrix;
  10278. };
  10279. TargetCamera.prototype._getVRViewMatrix = function () {
  10280. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10281. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10282. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10283. // Computing target and final matrix
  10284. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10285. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10286. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10287. return this._viewMatrix;
  10288. };
  10289. /**
  10290. * @override
  10291. * Override Camera.createRigCamera
  10292. */
  10293. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10294. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10295. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10296. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10297. rigCamera._cameraRigParams = {};
  10298. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10299. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10300. }
  10301. return rigCamera;
  10302. }
  10303. return null;
  10304. };
  10305. /**
  10306. * @override
  10307. * Override Camera._updateRigCameras
  10308. */
  10309. TargetCamera.prototype._updateRigCameras = function () {
  10310. switch (this.cameraRigMode) {
  10311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10315. case BABYLON.Camera.RIG_MODE_VR:
  10316. var camLeft = this._rigCameras[0];
  10317. var camRight = this._rigCameras[1];
  10318. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10319. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10320. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10321. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10322. camLeft.position.copyFrom(this.position);
  10323. camRight.position.copyFrom(this.position);
  10324. }
  10325. else {
  10326. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10327. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10328. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10329. camLeft.setTarget(this.getTarget());
  10330. camRight.setTarget(this.getTarget());
  10331. }
  10332. break;
  10333. }
  10334. _super.prototype._updateRigCameras.call(this);
  10335. };
  10336. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10337. if (!this._rigCamTransformMatrix) {
  10338. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10339. }
  10340. var target = this.getTarget();
  10341. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10342. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10343. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10344. };
  10345. return TargetCamera;
  10346. })(BABYLON.Camera);
  10347. BABYLON.TargetCamera = TargetCamera;
  10348. })(BABYLON || (BABYLON = {}));
  10349. var BABYLON;
  10350. (function (BABYLON) {
  10351. var FreeCamera = (function (_super) {
  10352. __extends(FreeCamera, _super);
  10353. function FreeCamera(name, position, scene) {
  10354. var _this = this;
  10355. _super.call(this, name, position, scene);
  10356. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10357. this.keysUp = [38];
  10358. this.keysDown = [40];
  10359. this.keysLeft = [37];
  10360. this.keysRight = [39];
  10361. this.checkCollisions = false;
  10362. this.applyGravity = false;
  10363. this.angularSensibility = 2000.0;
  10364. this._keys = [];
  10365. this._collider = new BABYLON.Collider();
  10366. this._needMoveForGravity = false;
  10367. this._oldPosition = BABYLON.Vector3.Zero();
  10368. this._diffPosition = BABYLON.Vector3.Zero();
  10369. this._newPosition = BABYLON.Vector3.Zero();
  10370. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10371. if (collidedMesh === void 0) { collidedMesh = null; }
  10372. //TODO move this to the collision coordinator!
  10373. if (_this.getScene().workerCollisions)
  10374. newPosition.multiplyInPlace(_this._collider.radius);
  10375. var updatePosition = function (newPos) {
  10376. _this._newPosition.copyFrom(newPos);
  10377. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10378. var oldPosition = _this.position.clone();
  10379. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10380. _this.position.addInPlace(_this._diffPosition);
  10381. if (_this.onCollide && collidedMesh) {
  10382. _this.onCollide(collidedMesh);
  10383. }
  10384. }
  10385. };
  10386. updatePosition(newPosition);
  10387. };
  10388. }
  10389. // Controls
  10390. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10391. var _this = this;
  10392. var previousPosition;
  10393. var engine = this.getEngine();
  10394. if (this._attachedElement) {
  10395. return;
  10396. }
  10397. this._attachedElement = element;
  10398. if (this._onMouseDown === undefined) {
  10399. this._onMouseDown = function (evt) {
  10400. previousPosition = {
  10401. x: evt.clientX,
  10402. y: evt.clientY
  10403. };
  10404. if (!noPreventDefault) {
  10405. evt.preventDefault();
  10406. }
  10407. };
  10408. this._onMouseUp = function (evt) {
  10409. previousPosition = null;
  10410. if (!noPreventDefault) {
  10411. evt.preventDefault();
  10412. }
  10413. };
  10414. this._onMouseOut = function (evt) {
  10415. previousPosition = null;
  10416. _this._keys = [];
  10417. if (!noPreventDefault) {
  10418. evt.preventDefault();
  10419. }
  10420. };
  10421. this._onMouseMove = function (evt) {
  10422. if (!previousPosition && !engine.isPointerLock) {
  10423. return;
  10424. }
  10425. var offsetX;
  10426. var offsetY;
  10427. if (!engine.isPointerLock) {
  10428. offsetX = evt.clientX - previousPosition.x;
  10429. offsetY = evt.clientY - previousPosition.y;
  10430. }
  10431. else {
  10432. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10433. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10434. }
  10435. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10436. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10437. previousPosition = {
  10438. x: evt.clientX,
  10439. y: evt.clientY
  10440. };
  10441. if (!noPreventDefault) {
  10442. evt.preventDefault();
  10443. }
  10444. };
  10445. this._onKeyDown = function (evt) {
  10446. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10447. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10448. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10449. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10450. var index = _this._keys.indexOf(evt.keyCode);
  10451. if (index === -1) {
  10452. _this._keys.push(evt.keyCode);
  10453. }
  10454. if (!noPreventDefault) {
  10455. evt.preventDefault();
  10456. }
  10457. }
  10458. };
  10459. this._onKeyUp = function (evt) {
  10460. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10461. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10462. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10463. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10464. var index = _this._keys.indexOf(evt.keyCode);
  10465. if (index >= 0) {
  10466. _this._keys.splice(index, 1);
  10467. }
  10468. if (!noPreventDefault) {
  10469. evt.preventDefault();
  10470. }
  10471. }
  10472. };
  10473. this._onLostFocus = function () {
  10474. _this._keys = [];
  10475. };
  10476. this._reset = function () {
  10477. _this._keys = [];
  10478. previousPosition = null;
  10479. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10480. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10481. };
  10482. }
  10483. element.addEventListener("mousedown", this._onMouseDown, false);
  10484. element.addEventListener("mouseup", this._onMouseUp, false);
  10485. element.addEventListener("mouseout", this._onMouseOut, false);
  10486. element.addEventListener("mousemove", this._onMouseMove, false);
  10487. BABYLON.Tools.RegisterTopRootEvents([
  10488. { name: "keydown", handler: this._onKeyDown },
  10489. { name: "keyup", handler: this._onKeyUp },
  10490. { name: "blur", handler: this._onLostFocus }
  10491. ]);
  10492. };
  10493. FreeCamera.prototype.detachControl = function (element) {
  10494. if (this._attachedElement != element) {
  10495. return;
  10496. }
  10497. element.removeEventListener("mousedown", this._onMouseDown);
  10498. element.removeEventListener("mouseup", this._onMouseUp);
  10499. element.removeEventListener("mouseout", this._onMouseOut);
  10500. element.removeEventListener("mousemove", this._onMouseMove);
  10501. BABYLON.Tools.UnregisterTopRootEvents([
  10502. { name: "keydown", handler: this._onKeyDown },
  10503. { name: "keyup", handler: this._onKeyUp },
  10504. { name: "blur", handler: this._onLostFocus }
  10505. ]);
  10506. this._attachedElement = null;
  10507. if (this._reset) {
  10508. this._reset();
  10509. }
  10510. };
  10511. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10512. var globalPosition;
  10513. if (this.parent) {
  10514. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10515. }
  10516. else {
  10517. globalPosition = this.position;
  10518. }
  10519. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10520. this._collider.radius = this.ellipsoid;
  10521. //no need for clone, as long as gravity is not on.
  10522. var actualVelocity = velocity;
  10523. //add gravity to the velocity to prevent the dual-collision checking
  10524. if (this.applyGravity) {
  10525. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10526. actualVelocity = velocity.add(this.getScene().gravity);
  10527. }
  10528. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10529. };
  10530. FreeCamera.prototype._checkInputs = function () {
  10531. if (!this._localDirection) {
  10532. this._localDirection = BABYLON.Vector3.Zero();
  10533. this._transformedDirection = BABYLON.Vector3.Zero();
  10534. }
  10535. // Keyboard
  10536. for (var index = 0; index < this._keys.length; index++) {
  10537. var keyCode = this._keys[index];
  10538. var speed = this._computeLocalCameraSpeed();
  10539. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10540. this._localDirection.copyFromFloats(-speed, 0, 0);
  10541. }
  10542. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10543. this._localDirection.copyFromFloats(0, 0, speed);
  10544. }
  10545. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10546. this._localDirection.copyFromFloats(speed, 0, 0);
  10547. }
  10548. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10549. this._localDirection.copyFromFloats(0, 0, -speed);
  10550. }
  10551. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10552. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10553. this.cameraDirection.addInPlace(this._transformedDirection);
  10554. }
  10555. _super.prototype._checkInputs.call(this);
  10556. };
  10557. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10558. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10559. };
  10560. FreeCamera.prototype._updatePosition = function () {
  10561. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10562. this._collideWithWorld(this.cameraDirection);
  10563. }
  10564. else {
  10565. this.position.addInPlace(this.cameraDirection);
  10566. }
  10567. };
  10568. return FreeCamera;
  10569. })(BABYLON.TargetCamera);
  10570. BABYLON.FreeCamera = FreeCamera;
  10571. })(BABYLON || (BABYLON = {}));
  10572. var BABYLON;
  10573. (function (BABYLON) {
  10574. var FollowCamera = (function (_super) {
  10575. __extends(FollowCamera, _super);
  10576. function FollowCamera(name, position, scene) {
  10577. _super.call(this, name, position, scene);
  10578. this.radius = 12;
  10579. this.rotationOffset = 0;
  10580. this.heightOffset = 4;
  10581. this.cameraAcceleration = 0.05;
  10582. this.maxCameraSpeed = 20;
  10583. }
  10584. FollowCamera.prototype.getRadians = function (degrees) {
  10585. return degrees * Math.PI / 180;
  10586. };
  10587. FollowCamera.prototype.follow = function (cameraTarget) {
  10588. if (!cameraTarget)
  10589. return;
  10590. var yRotation;
  10591. if (cameraTarget.rotationQuaternion) {
  10592. var rotMatrix = new BABYLON.Matrix();
  10593. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10594. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10595. }
  10596. else {
  10597. yRotation = cameraTarget.rotation.y;
  10598. }
  10599. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10600. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10601. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10602. var dx = targetX - this.position.x;
  10603. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10604. var dz = (targetZ) - this.position.z;
  10605. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10606. var vy = dy * this.cameraAcceleration;
  10607. var vz = dz * this.cameraAcceleration * 2;
  10608. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10609. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10610. }
  10611. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10612. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10613. }
  10614. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10615. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10616. }
  10617. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10618. this.setTarget(cameraTarget.position);
  10619. };
  10620. FollowCamera.prototype._checkInputs = function () {
  10621. _super.prototype._checkInputs.call(this);
  10622. this.follow(this.target);
  10623. };
  10624. return FollowCamera;
  10625. })(BABYLON.TargetCamera);
  10626. BABYLON.FollowCamera = FollowCamera;
  10627. var ArcFollowCamera = (function (_super) {
  10628. __extends(ArcFollowCamera, _super);
  10629. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10630. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10631. this.alpha = alpha;
  10632. this.beta = beta;
  10633. this.radius = radius;
  10634. this.target = target;
  10635. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10636. this.follow();
  10637. }
  10638. ArcFollowCamera.prototype.follow = function () {
  10639. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10640. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10641. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10642. this.position = this.target.position.add(this._cartesianCoordinates);
  10643. this.setTarget(this.target.position);
  10644. };
  10645. ArcFollowCamera.prototype._checkInputs = function () {
  10646. _super.prototype._checkInputs.call(this);
  10647. this.follow();
  10648. };
  10649. return ArcFollowCamera;
  10650. })(BABYLON.TargetCamera);
  10651. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10652. })(BABYLON || (BABYLON = {}));
  10653. var BABYLON;
  10654. (function (BABYLON) {
  10655. // We're mainly based on the logic defined into the FreeCamera code
  10656. var TouchCamera = (function (_super) {
  10657. __extends(TouchCamera, _super);
  10658. function TouchCamera(name, position, scene) {
  10659. _super.call(this, name, position, scene);
  10660. this._offsetX = null;
  10661. this._offsetY = null;
  10662. this._pointerCount = 0;
  10663. this._pointerPressed = [];
  10664. this.angularSensibility = 200000.0;
  10665. this.moveSensibility = 500.0;
  10666. }
  10667. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10668. var _this = this;
  10669. var previousPosition;
  10670. if (this._attachedCanvas) {
  10671. return;
  10672. }
  10673. this._attachedCanvas = canvas;
  10674. if (this._onPointerDown === undefined) {
  10675. this._onPointerDown = function (evt) {
  10676. if (!noPreventDefault) {
  10677. evt.preventDefault();
  10678. }
  10679. _this._pointerPressed.push(evt.pointerId);
  10680. if (_this._pointerPressed.length !== 1) {
  10681. return;
  10682. }
  10683. previousPosition = {
  10684. x: evt.clientX,
  10685. y: evt.clientY
  10686. };
  10687. };
  10688. this._onPointerUp = function (evt) {
  10689. if (!noPreventDefault) {
  10690. evt.preventDefault();
  10691. }
  10692. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10693. if (index === -1) {
  10694. return;
  10695. }
  10696. _this._pointerPressed.splice(index, 1);
  10697. if (index != 0) {
  10698. return;
  10699. }
  10700. previousPosition = null;
  10701. _this._offsetX = null;
  10702. _this._offsetY = null;
  10703. };
  10704. this._onPointerMove = function (evt) {
  10705. if (!noPreventDefault) {
  10706. evt.preventDefault();
  10707. }
  10708. if (!previousPosition) {
  10709. return;
  10710. }
  10711. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10712. if (index != 0) {
  10713. return;
  10714. }
  10715. _this._offsetX = evt.clientX - previousPosition.x;
  10716. _this._offsetY = -(evt.clientY - previousPosition.y);
  10717. };
  10718. this._onLostFocus = function () {
  10719. _this._offsetX = null;
  10720. _this._offsetY = null;
  10721. };
  10722. }
  10723. canvas.addEventListener("pointerdown", this._onPointerDown);
  10724. canvas.addEventListener("pointerup", this._onPointerUp);
  10725. canvas.addEventListener("pointerout", this._onPointerUp);
  10726. canvas.addEventListener("pointermove", this._onPointerMove);
  10727. BABYLON.Tools.RegisterTopRootEvents([
  10728. { name: "blur", handler: this._onLostFocus }
  10729. ]);
  10730. };
  10731. TouchCamera.prototype.detachControl = function (canvas) {
  10732. if (this._attachedCanvas != canvas) {
  10733. return;
  10734. }
  10735. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10736. canvas.removeEventListener("pointerup", this._onPointerUp);
  10737. canvas.removeEventListener("pointerout", this._onPointerUp);
  10738. canvas.removeEventListener("pointermove", this._onPointerMove);
  10739. BABYLON.Tools.UnregisterTopRootEvents([
  10740. { name: "blur", handler: this._onLostFocus }
  10741. ]);
  10742. this._attachedCanvas = null;
  10743. };
  10744. TouchCamera.prototype._checkInputs = function () {
  10745. if (this._offsetX) {
  10746. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10747. if (this._pointerPressed.length > 1) {
  10748. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10749. }
  10750. else {
  10751. var speed = this._computeLocalCameraSpeed();
  10752. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10753. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10754. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10755. }
  10756. }
  10757. _super.prototype._checkInputs.call(this);
  10758. };
  10759. return TouchCamera;
  10760. })(BABYLON.FreeCamera);
  10761. BABYLON.TouchCamera = TouchCamera;
  10762. })(BABYLON || (BABYLON = {}));
  10763. var BABYLON;
  10764. (function (BABYLON) {
  10765. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10766. var ArcRotateCamera = (function (_super) {
  10767. __extends(ArcRotateCamera, _super);
  10768. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10769. var _this = this;
  10770. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10771. this.alpha = alpha;
  10772. this.beta = beta;
  10773. this.radius = radius;
  10774. this.target = target;
  10775. this.inertialAlphaOffset = 0;
  10776. this.inertialBetaOffset = 0;
  10777. this.inertialRadiusOffset = 0;
  10778. this.lowerAlphaLimit = null;
  10779. this.upperAlphaLimit = null;
  10780. this.lowerBetaLimit = 0.01;
  10781. this.upperBetaLimit = Math.PI;
  10782. this.lowerRadiusLimit = null;
  10783. this.upperRadiusLimit = null;
  10784. this.angularSensibilityX = 1000.0;
  10785. this.angularSensibilityY = 1000.0;
  10786. this.wheelPrecision = 3.0;
  10787. this.pinchPrecision = 2.0;
  10788. this.panningSensibility = 50.0;
  10789. this.inertialPanningX = 0;
  10790. this.inertialPanningY = 0;
  10791. this.keysUp = [38];
  10792. this.keysDown = [40];
  10793. this.keysLeft = [37];
  10794. this.keysRight = [39];
  10795. this.zoomOnFactor = 1;
  10796. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10797. this.pinchInwards = true;
  10798. this.allowUpsideDown = true;
  10799. this._keys = [];
  10800. this._viewMatrix = new BABYLON.Matrix();
  10801. this._isRightClick = false;
  10802. this._isCtrlPushed = false;
  10803. this.checkCollisions = false;
  10804. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10805. this._collider = new BABYLON.Collider();
  10806. this._previousPosition = BABYLON.Vector3.Zero();
  10807. this._collisionVelocity = BABYLON.Vector3.Zero();
  10808. this._newPosition = BABYLON.Vector3.Zero();
  10809. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10810. if (collidedMesh === void 0) { collidedMesh = null; }
  10811. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10812. newPosition.multiplyInPlace(_this._collider.radius);
  10813. }
  10814. if (!collidedMesh) {
  10815. _this._previousPosition.copyFrom(_this.position);
  10816. }
  10817. else {
  10818. _this.setPosition(_this.position);
  10819. if (_this.onCollide) {
  10820. _this.onCollide(collidedMesh);
  10821. }
  10822. }
  10823. // Recompute because of constraints
  10824. var cosa = Math.cos(_this.alpha);
  10825. var sina = Math.sin(_this.alpha);
  10826. var cosb = Math.cos(_this.beta);
  10827. var sinb = Math.sin(_this.beta);
  10828. var target = _this._getTargetPosition();
  10829. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10830. _this.position.copyFrom(_this._newPosition);
  10831. var up = _this.upVector;
  10832. if (_this.allowUpsideDown && _this.beta < 0) {
  10833. var up = up.clone();
  10834. up = up.negate();
  10835. }
  10836. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10837. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10838. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10839. _this._collisionTriggered = false;
  10840. };
  10841. if (!this.target) {
  10842. this.target = BABYLON.Vector3.Zero();
  10843. }
  10844. this.getViewMatrix();
  10845. }
  10846. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10847. //deprecated angularSensibility support
  10848. get: function () {
  10849. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10850. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10851. },
  10852. //deprecated angularSensibility support
  10853. set: function (value) {
  10854. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10855. this.angularSensibilityX = value;
  10856. this.angularSensibilityY = value;
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. ArcRotateCamera.prototype._getTargetPosition = function () {
  10862. return this.target.position || this.target;
  10863. };
  10864. // Cache
  10865. ArcRotateCamera.prototype._initCache = function () {
  10866. _super.prototype._initCache.call(this);
  10867. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10868. this._cache.alpha = undefined;
  10869. this._cache.beta = undefined;
  10870. this._cache.radius = undefined;
  10871. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10872. };
  10873. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10874. if (!ignoreParentClass) {
  10875. _super.prototype._updateCache.call(this);
  10876. }
  10877. this._cache.target.copyFrom(this._getTargetPosition());
  10878. this._cache.alpha = this.alpha;
  10879. this._cache.beta = this.beta;
  10880. this._cache.radius = this.radius;
  10881. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10882. };
  10883. // Synchronized
  10884. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10885. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10886. return false;
  10887. return this._cache.target.equals(this._getTargetPosition())
  10888. && this._cache.alpha === this.alpha
  10889. && this._cache.beta === this.beta
  10890. && this._cache.radius === this.radius
  10891. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10892. };
  10893. // Methods
  10894. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10895. var _this = this;
  10896. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10897. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10898. var previousPinchDistance = 0;
  10899. var pointers = new BABYLON.SmartCollection();
  10900. if (this._attachedElement) {
  10901. return;
  10902. }
  10903. this._attachedElement = element;
  10904. var engine = this.getEngine();
  10905. if (this._onPointerDown === undefined) {
  10906. this._onPointerDown = function (evt) {
  10907. // Manage panning with right click
  10908. _this._isRightClick = evt.button === 2 ? true : false;
  10909. // manage pointers
  10910. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10911. cacheSoloPointer = pointers.item(evt.pointerId);
  10912. if (!noPreventDefault) {
  10913. evt.preventDefault();
  10914. }
  10915. };
  10916. this._onPointerUp = function (evt) {
  10917. cacheSoloPointer = null;
  10918. previousPinchDistance = 0;
  10919. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10920. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10921. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10922. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10923. pointers.empty();
  10924. if (!noPreventDefault) {
  10925. evt.preventDefault();
  10926. }
  10927. };
  10928. this._onContextMenu = function (evt) {
  10929. evt.preventDefault();
  10930. };
  10931. this._onPointerMove = function (evt) {
  10932. if (!noPreventDefault) {
  10933. evt.preventDefault();
  10934. }
  10935. switch (pointers.count) {
  10936. case 1:
  10937. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10938. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10939. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10940. }
  10941. else {
  10942. var offsetX = evt.clientX - cacheSoloPointer.x;
  10943. var offsetY = evt.clientY - cacheSoloPointer.y;
  10944. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10945. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10946. }
  10947. cacheSoloPointer.x = evt.clientX;
  10948. cacheSoloPointer.y = evt.clientY;
  10949. break;
  10950. case 2:
  10951. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10952. pointers.item(evt.pointerId).x = evt.clientX;
  10953. pointers.item(evt.pointerId).y = evt.clientY;
  10954. var direction = _this.pinchInwards ? 1 : -1;
  10955. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10956. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10957. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10958. if (previousPinchDistance === 0) {
  10959. previousPinchDistance = pinchSquaredDistance;
  10960. return;
  10961. }
  10962. if (pinchSquaredDistance !== previousPinchDistance) {
  10963. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10964. previousPinchDistance = pinchSquaredDistance;
  10965. }
  10966. break;
  10967. default:
  10968. if (pointers.item(evt.pointerId)) {
  10969. pointers.item(evt.pointerId).x = evt.clientX;
  10970. pointers.item(evt.pointerId).y = evt.clientY;
  10971. }
  10972. }
  10973. };
  10974. this._onMouseMove = function (evt) {
  10975. if (!engine.isPointerLock) {
  10976. return;
  10977. }
  10978. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10979. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10980. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10981. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10982. if (!noPreventDefault) {
  10983. evt.preventDefault();
  10984. }
  10985. };
  10986. this._wheel = function (event) {
  10987. var delta = 0;
  10988. if (event.wheelDelta) {
  10989. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10990. }
  10991. else if (event.detail) {
  10992. delta = -event.detail / _this.wheelPrecision;
  10993. }
  10994. if (delta)
  10995. _this.inertialRadiusOffset += delta;
  10996. if (event.preventDefault) {
  10997. if (!noPreventDefault) {
  10998. event.preventDefault();
  10999. }
  11000. }
  11001. };
  11002. this._onKeyDown = function (evt) {
  11003. _this._isCtrlPushed = evt.ctrlKey;
  11004. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11005. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11006. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11007. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11008. var index = _this._keys.indexOf(evt.keyCode);
  11009. if (index === -1) {
  11010. _this._keys.push(evt.keyCode);
  11011. }
  11012. if (evt.preventDefault) {
  11013. if (!noPreventDefault) {
  11014. evt.preventDefault();
  11015. }
  11016. }
  11017. }
  11018. };
  11019. this._onKeyUp = function (evt) {
  11020. _this._isCtrlPushed = evt.ctrlKey;
  11021. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11022. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11023. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11024. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11025. var index = _this._keys.indexOf(evt.keyCode);
  11026. if (index >= 0) {
  11027. _this._keys.splice(index, 1);
  11028. }
  11029. if (evt.preventDefault) {
  11030. if (!noPreventDefault) {
  11031. evt.preventDefault();
  11032. }
  11033. }
  11034. }
  11035. };
  11036. this._onLostFocus = function () {
  11037. _this._keys = [];
  11038. pointers.empty();
  11039. previousPinchDistance = 0;
  11040. cacheSoloPointer = null;
  11041. };
  11042. this._onGestureStart = function (e) {
  11043. if (window.MSGesture === undefined) {
  11044. return;
  11045. }
  11046. if (!_this._MSGestureHandler) {
  11047. _this._MSGestureHandler = new MSGesture();
  11048. _this._MSGestureHandler.target = element;
  11049. }
  11050. _this._MSGestureHandler.addPointer(e.pointerId);
  11051. };
  11052. this._onGesture = function (e) {
  11053. _this.radius *= e.scale;
  11054. if (e.preventDefault) {
  11055. if (!noPreventDefault) {
  11056. e.stopPropagation();
  11057. e.preventDefault();
  11058. }
  11059. }
  11060. };
  11061. this._reset = function () {
  11062. _this._keys = [];
  11063. _this.inertialAlphaOffset = 0;
  11064. _this.inertialBetaOffset = 0;
  11065. _this.inertialRadiusOffset = 0;
  11066. pointers.empty();
  11067. previousPinchDistance = 0;
  11068. cacheSoloPointer = null;
  11069. };
  11070. }
  11071. if (!useCtrlForPanning) {
  11072. element.addEventListener("contextmenu", this._onContextMenu, false);
  11073. }
  11074. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11075. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11076. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11077. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11078. element.addEventListener("mousemove", this._onMouseMove, false);
  11079. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11080. element.addEventListener("MSGestureChange", this._onGesture, false);
  11081. element.addEventListener('mousewheel', this._wheel, false);
  11082. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11083. BABYLON.Tools.RegisterTopRootEvents([
  11084. { name: "keydown", handler: this._onKeyDown },
  11085. { name: "keyup", handler: this._onKeyUp },
  11086. { name: "blur", handler: this._onLostFocus }
  11087. ]);
  11088. };
  11089. ArcRotateCamera.prototype.detachControl = function (element) {
  11090. if (this._attachedElement !== element) {
  11091. return;
  11092. }
  11093. element.removeEventListener("contextmenu", this._onContextMenu);
  11094. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11095. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11096. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11097. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11098. element.removeEventListener("mousemove", this._onMouseMove);
  11099. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11100. element.removeEventListener("MSGestureChange", this._onGesture);
  11101. element.removeEventListener('mousewheel', this._wheel);
  11102. element.removeEventListener('DOMMouseScroll', this._wheel);
  11103. BABYLON.Tools.UnregisterTopRootEvents([
  11104. { name: "keydown", handler: this._onKeyDown },
  11105. { name: "keyup", handler: this._onKeyUp },
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. this._MSGestureHandler = null;
  11109. this._attachedElement = null;
  11110. if (this._reset) {
  11111. this._reset();
  11112. }
  11113. };
  11114. ArcRotateCamera.prototype._checkInputs = function () {
  11115. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11116. if (this._collisionTriggered) {
  11117. return;
  11118. }
  11119. // Keyboard
  11120. for (var index = 0; index < this._keys.length; index++) {
  11121. var keyCode = this._keys[index];
  11122. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11123. this.inertialAlphaOffset -= 0.01;
  11124. }
  11125. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11126. this.inertialBetaOffset -= 0.01;
  11127. }
  11128. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11129. this.inertialAlphaOffset += 0.01;
  11130. }
  11131. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11132. this.inertialBetaOffset += 0.01;
  11133. }
  11134. }
  11135. // Inertia
  11136. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11137. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11138. this.beta += this.inertialBetaOffset;
  11139. this.radius -= this.inertialRadiusOffset;
  11140. this.inertialAlphaOffset *= this.inertia;
  11141. this.inertialBetaOffset *= this.inertia;
  11142. this.inertialRadiusOffset *= this.inertia;
  11143. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11144. this.inertialAlphaOffset = 0;
  11145. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11146. this.inertialBetaOffset = 0;
  11147. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11148. this.inertialRadiusOffset = 0;
  11149. }
  11150. // Panning inertia
  11151. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11152. if (!this._localDirection) {
  11153. this._localDirection = BABYLON.Vector3.Zero();
  11154. this._transformedDirection = BABYLON.Vector3.Zero();
  11155. }
  11156. this.inertialPanningX *= this.inertia;
  11157. this.inertialPanningY *= this.inertia;
  11158. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11159. this.inertialPanningX = 0;
  11160. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11161. this.inertialPanningY = 0;
  11162. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11163. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11164. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11165. this.target.addInPlace(this._transformedDirection);
  11166. }
  11167. // Limits
  11168. this._checkLimits();
  11169. _super.prototype._checkInputs.call(this);
  11170. };
  11171. ArcRotateCamera.prototype._checkLimits = function () {
  11172. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11173. if (this.allowUpsideDown && this.beta > Math.PI) {
  11174. this.beta = this.beta - (2 * Math.PI);
  11175. }
  11176. }
  11177. else {
  11178. if (this.beta < this.lowerBetaLimit) {
  11179. this.beta = this.lowerBetaLimit;
  11180. }
  11181. }
  11182. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11183. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11184. this.beta = this.beta + (2 * Math.PI);
  11185. }
  11186. }
  11187. else {
  11188. if (this.beta > this.upperBetaLimit) {
  11189. this.beta = this.upperBetaLimit;
  11190. }
  11191. }
  11192. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11193. this.alpha = this.lowerAlphaLimit;
  11194. }
  11195. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11196. this.alpha = this.upperAlphaLimit;
  11197. }
  11198. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11199. this.radius = this.lowerRadiusLimit;
  11200. }
  11201. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11202. this.radius = this.upperRadiusLimit;
  11203. }
  11204. };
  11205. ArcRotateCamera.prototype.setPosition = function (position) {
  11206. if (this.position.equals(position)) {
  11207. return;
  11208. }
  11209. var radiusv3 = position.subtract(this._getTargetPosition());
  11210. this.radius = radiusv3.length();
  11211. // Alpha
  11212. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11213. if (radiusv3.z < 0) {
  11214. this.alpha = 2 * Math.PI - this.alpha;
  11215. }
  11216. // Beta
  11217. this.beta = Math.acos(radiusv3.y / this.radius);
  11218. this._checkLimits();
  11219. };
  11220. ArcRotateCamera.prototype.setTarget = function (target) {
  11221. this.target = target;
  11222. };
  11223. ArcRotateCamera.prototype._getViewMatrix = function () {
  11224. // Compute
  11225. var cosa = Math.cos(this.alpha);
  11226. var sina = Math.sin(this.alpha);
  11227. var cosb = Math.cos(this.beta);
  11228. var sinb = Math.sin(this.beta);
  11229. var target = this._getTargetPosition();
  11230. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11231. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11232. this._collider.radius = this.collisionRadius;
  11233. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11234. this._collisionTriggered = true;
  11235. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11236. }
  11237. else {
  11238. this.position.copyFrom(this._newPosition);
  11239. var up = this.upVector;
  11240. if (this.allowUpsideDown && this.beta < 0) {
  11241. var up = up.clone();
  11242. up = up.negate();
  11243. }
  11244. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11245. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11246. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11247. }
  11248. return this._viewMatrix;
  11249. };
  11250. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11251. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11252. meshes = meshes || this.getScene().meshes;
  11253. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11254. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11255. this.radius = distance * this.zoomOnFactor;
  11256. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11257. };
  11258. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11259. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11260. var meshesOrMinMaxVector;
  11261. var distance;
  11262. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11263. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11264. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11265. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11266. }
  11267. else {
  11268. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11269. distance = meshesOrMinMaxVectorAndDistance.distance;
  11270. }
  11271. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11272. if (!doNotUpdateMaxZ) {
  11273. this.maxZ = distance * 2;
  11274. }
  11275. };
  11276. /**
  11277. * @override
  11278. * Override Camera.createRigCamera
  11279. */
  11280. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11281. switch (this.cameraRigMode) {
  11282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11286. case BABYLON.Camera.RIG_MODE_VR:
  11287. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11288. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11289. }
  11290. };
  11291. /**
  11292. * @override
  11293. * Override Camera._updateRigCameras
  11294. */
  11295. ArcRotateCamera.prototype._updateRigCameras = function () {
  11296. switch (this.cameraRigMode) {
  11297. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11298. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11299. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11300. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11301. case BABYLON.Camera.RIG_MODE_VR:
  11302. var camLeft = this._rigCameras[0];
  11303. var camRight = this._rigCameras[1];
  11304. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11305. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11306. camLeft.beta = camRight.beta = this.beta;
  11307. camLeft.radius = camRight.radius = this.radius;
  11308. break;
  11309. }
  11310. _super.prototype._updateRigCameras.call(this);
  11311. };
  11312. return ArcRotateCamera;
  11313. })(BABYLON.TargetCamera);
  11314. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11315. })(BABYLON || (BABYLON = {}));
  11316. var BABYLON;
  11317. (function (BABYLON) {
  11318. var RenderingManager = (function () {
  11319. function RenderingManager(scene) {
  11320. this._renderingGroups = new Array();
  11321. this._scene = scene;
  11322. }
  11323. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11324. if (this._scene._activeParticleSystems.length === 0) {
  11325. return;
  11326. }
  11327. // Particles
  11328. var activeCamera = this._scene.activeCamera;
  11329. var beforeParticlesDate = BABYLON.Tools.Now;
  11330. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11331. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11332. if (particleSystem.renderingGroupId !== index) {
  11333. continue;
  11334. }
  11335. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11336. continue;
  11337. }
  11338. this._clearDepthBuffer();
  11339. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11340. this._scene._activeParticles += particleSystem.render();
  11341. }
  11342. }
  11343. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11344. };
  11345. RenderingManager.prototype._renderSprites = function (index) {
  11346. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11347. return;
  11348. }
  11349. // Sprites
  11350. var activeCamera = this._scene.activeCamera;
  11351. var beforeSpritessDate = BABYLON.Tools.Now;
  11352. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11353. var spriteManager = this._scene.spriteManagers[id];
  11354. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11355. this._clearDepthBuffer();
  11356. spriteManager.render();
  11357. }
  11358. }
  11359. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11360. };
  11361. RenderingManager.prototype._clearDepthBuffer = function () {
  11362. if (this._depthBufferAlreadyCleaned) {
  11363. return;
  11364. }
  11365. this._scene.getEngine().clear(0, false, true);
  11366. this._depthBufferAlreadyCleaned = true;
  11367. };
  11368. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11369. if (this._currentRenderSprites) {
  11370. this._renderSprites(this._currentIndex);
  11371. }
  11372. if (this._currentRenderParticles) {
  11373. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11374. }
  11375. };
  11376. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11377. this._currentActiveMeshes = activeMeshes;
  11378. this._currentRenderParticles = renderParticles;
  11379. this._currentRenderSprites = renderSprites;
  11380. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11381. this._depthBufferAlreadyCleaned = false;
  11382. var renderingGroup = this._renderingGroups[index];
  11383. var needToStepBack = false;
  11384. this._currentIndex = index;
  11385. if (renderingGroup) {
  11386. this._clearDepthBuffer();
  11387. if (!renderingGroup.onBeforeTransparentRendering) {
  11388. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11389. }
  11390. if (!renderingGroup.render(customRenderFunction)) {
  11391. this._renderingGroups.splice(index, 1);
  11392. needToStepBack = true;
  11393. this._renderSpritesAndParticles();
  11394. }
  11395. }
  11396. else {
  11397. this._renderSpritesAndParticles();
  11398. }
  11399. if (needToStepBack) {
  11400. index--;
  11401. }
  11402. }
  11403. };
  11404. RenderingManager.prototype.reset = function () {
  11405. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11406. if (renderingGroup) {
  11407. renderingGroup.prepare();
  11408. }
  11409. });
  11410. };
  11411. RenderingManager.prototype.dispatch = function (subMesh) {
  11412. var mesh = subMesh.getMesh();
  11413. var renderingGroupId = mesh.renderingGroupId || 0;
  11414. if (!this._renderingGroups[renderingGroupId]) {
  11415. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11416. }
  11417. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11418. };
  11419. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11420. return RenderingManager;
  11421. })();
  11422. BABYLON.RenderingManager = RenderingManager;
  11423. })(BABYLON || (BABYLON = {}));
  11424. var BABYLON;
  11425. (function (BABYLON) {
  11426. var RenderingGroup = (function () {
  11427. function RenderingGroup(index, scene) {
  11428. this.index = index;
  11429. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11430. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11431. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11432. this._scene = scene;
  11433. }
  11434. RenderingGroup.prototype.render = function (customRenderFunction) {
  11435. if (customRenderFunction) {
  11436. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11437. return true;
  11438. }
  11439. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11440. if (this.onBeforeTransparentRendering) {
  11441. this.onBeforeTransparentRendering();
  11442. }
  11443. return false;
  11444. }
  11445. var engine = this._scene.getEngine();
  11446. // Opaque
  11447. var subIndex;
  11448. var submesh;
  11449. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11450. submesh = this._opaqueSubMeshes.data[subIndex];
  11451. submesh.render(false);
  11452. }
  11453. // Alpha test
  11454. engine.setAlphaTesting(true);
  11455. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11456. submesh = this._alphaTestSubMeshes.data[subIndex];
  11457. submesh.render(false);
  11458. }
  11459. engine.setAlphaTesting(false);
  11460. if (this.onBeforeTransparentRendering) {
  11461. this.onBeforeTransparentRendering();
  11462. }
  11463. // Transparent
  11464. if (this._transparentSubMeshes.length) {
  11465. // Sorting
  11466. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11467. submesh = this._transparentSubMeshes.data[subIndex];
  11468. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11469. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11470. }
  11471. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11472. sortedArray.sort(function (a, b) {
  11473. // Alpha index first
  11474. if (a._alphaIndex > b._alphaIndex) {
  11475. return 1;
  11476. }
  11477. if (a._alphaIndex < b._alphaIndex) {
  11478. return -1;
  11479. }
  11480. // Then distance to camera
  11481. if (a._distanceToCamera < b._distanceToCamera) {
  11482. return 1;
  11483. }
  11484. if (a._distanceToCamera > b._distanceToCamera) {
  11485. return -1;
  11486. }
  11487. return 0;
  11488. });
  11489. // Rendering
  11490. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11491. submesh = sortedArray[subIndex];
  11492. submesh.render(true);
  11493. }
  11494. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11495. }
  11496. return true;
  11497. };
  11498. RenderingGroup.prototype.prepare = function () {
  11499. this._opaqueSubMeshes.reset();
  11500. this._transparentSubMeshes.reset();
  11501. this._alphaTestSubMeshes.reset();
  11502. };
  11503. RenderingGroup.prototype.dispatch = function (subMesh) {
  11504. var material = subMesh.getMaterial();
  11505. var mesh = subMesh.getMesh();
  11506. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11507. this._transparentSubMeshes.push(subMesh);
  11508. }
  11509. else if (material.needAlphaTesting()) {
  11510. this._alphaTestSubMeshes.push(subMesh);
  11511. }
  11512. else {
  11513. this._opaqueSubMeshes.push(subMesh); // Opaque
  11514. }
  11515. };
  11516. return RenderingGroup;
  11517. })();
  11518. BABYLON.RenderingGroup = RenderingGroup;
  11519. })(BABYLON || (BABYLON = {}));
  11520. var BABYLON;
  11521. (function (BABYLON) {
  11522. /**
  11523. * Represents a scene to be rendered by the engine.
  11524. * @see http://doc.babylonjs.com/page.php?p=21911
  11525. */
  11526. var Scene = (function () {
  11527. /**
  11528. * @constructor
  11529. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11530. */
  11531. function Scene(engine) {
  11532. // Members
  11533. this.autoClear = true;
  11534. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11535. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11536. this.forceWireframe = false;
  11537. this.forcePointsCloud = false;
  11538. this.forceShowBoundingBoxes = false;
  11539. this.animationsEnabled = true;
  11540. this.constantlyUpdateMeshUnderPointer = false;
  11541. 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
  11542. // Fog
  11543. /**
  11544. * is fog enabled on this scene.
  11545. * @type {boolean}
  11546. */
  11547. this.fogEnabled = true;
  11548. this.fogMode = Scene.FOGMODE_NONE;
  11549. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11550. this.fogDensity = 0.1;
  11551. this.fogStart = 0;
  11552. this.fogEnd = 1000.0;
  11553. // Lights
  11554. /**
  11555. * is shadow enabled on this scene.
  11556. * @type {boolean}
  11557. */
  11558. this.shadowsEnabled = true;
  11559. /**
  11560. * is light enabled on this scene.
  11561. * @type {boolean}
  11562. */
  11563. this.lightsEnabled = true;
  11564. /**
  11565. * All of the lights added to this scene.
  11566. * @see BABYLON.Light
  11567. * @type {BABYLON.Light[]}
  11568. */
  11569. this.lights = new Array();
  11570. // Cameras
  11571. /**
  11572. * All of the cameras added to this scene.
  11573. * @see BABYLON.Camera
  11574. * @type {BABYLON.Camera[]}
  11575. */
  11576. this.cameras = new Array();
  11577. this.activeCameras = new Array();
  11578. // Meshes
  11579. /**
  11580. * All of the (abstract) meshes added to this scene.
  11581. * @see BABYLON.AbstractMesh
  11582. * @type {BABYLON.AbstractMesh[]}
  11583. */
  11584. this.meshes = new Array();
  11585. // Geometries
  11586. this._geometries = new Array();
  11587. this.materials = new Array();
  11588. this.multiMaterials = new Array();
  11589. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11590. // Textures
  11591. this.texturesEnabled = true;
  11592. this.textures = new Array();
  11593. // Particles
  11594. this.particlesEnabled = true;
  11595. this.particleSystems = new Array();
  11596. // Sprites
  11597. this.spritesEnabled = true;
  11598. this.spriteManagers = new Array();
  11599. // Layers
  11600. this.layers = new Array();
  11601. // Skeletons
  11602. this.skeletonsEnabled = true;
  11603. this.skeletons = new Array();
  11604. // Lens flares
  11605. this.lensFlaresEnabled = true;
  11606. this.lensFlareSystems = new Array();
  11607. // Collisions
  11608. this.collisionsEnabled = true;
  11609. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11610. // Postprocesses
  11611. this.postProcessesEnabled = true;
  11612. // Customs render targets
  11613. this.renderTargetsEnabled = true;
  11614. this.dumpNextRenderTargets = false;
  11615. this.customRenderTargets = new Array();
  11616. // Imported meshes
  11617. this.importedMeshesFiles = new Array();
  11618. // Probes
  11619. this.probesEnabled = true;
  11620. this.reflectionProbes = new Array();
  11621. this._actionManagers = new Array();
  11622. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11623. // Procedural textures
  11624. this.proceduralTexturesEnabled = true;
  11625. this._proceduralTextures = new Array();
  11626. this.soundTracks = new Array();
  11627. this._audioEnabled = true;
  11628. this._headphone = false;
  11629. this._totalVertices = 0;
  11630. this._activeIndices = 0;
  11631. this._activeParticles = 0;
  11632. this._lastFrameDuration = 0;
  11633. this._evaluateActiveMeshesDuration = 0;
  11634. this._renderTargetsDuration = 0;
  11635. this._particlesDuration = 0;
  11636. this._renderDuration = 0;
  11637. this._spritesDuration = 0;
  11638. this._animationRatio = 0;
  11639. this._renderId = 0;
  11640. this._executeWhenReadyTimeoutId = -1;
  11641. this._toBeDisposed = new BABYLON.SmartArray(256);
  11642. this._onReadyCallbacks = new Array();
  11643. this._pendingData = []; //ANY
  11644. this._onBeforeRenderCallbacks = new Array();
  11645. this._onAfterRenderCallbacks = new Array();
  11646. this._activeMeshes = new BABYLON.SmartArray(256);
  11647. this._processedMaterials = new BABYLON.SmartArray(256);
  11648. this._renderTargets = new BABYLON.SmartArray(256);
  11649. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11650. this._activeSkeletons = new BABYLON.SmartArray(32);
  11651. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11652. this._activeBones = 0;
  11653. this._activeAnimatables = new Array();
  11654. this._transformMatrix = BABYLON.Matrix.Zero();
  11655. this._edgesRenderers = new BABYLON.SmartArray(16);
  11656. this._uniqueIdCounter = 0;
  11657. this._engine = engine;
  11658. engine.scenes.push(this);
  11659. this._renderingManager = new BABYLON.RenderingManager(this);
  11660. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11661. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11662. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11663. if (BABYLON.OutlineRenderer) {
  11664. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11665. }
  11666. this.attachControl();
  11667. this._debugLayer = new BABYLON.DebugLayer(this);
  11668. if (BABYLON.SoundTrack) {
  11669. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11670. }
  11671. //simplification queue
  11672. if (BABYLON.SimplificationQueue) {
  11673. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11674. }
  11675. //collision coordinator initialization. For now legacy per default.
  11676. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11677. }
  11678. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11679. get: function () {
  11680. return Scene._FOGMODE_NONE;
  11681. },
  11682. enumerable: true,
  11683. configurable: true
  11684. });
  11685. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11686. get: function () {
  11687. return Scene._FOGMODE_EXP;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11693. get: function () {
  11694. return Scene._FOGMODE_EXP2;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11700. get: function () {
  11701. return Scene._FOGMODE_LINEAR;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Scene.prototype, "debugLayer", {
  11707. // Properties
  11708. get: function () {
  11709. return this._debugLayer;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11715. get: function () {
  11716. return this._workerCollisions;
  11717. },
  11718. set: function (enabled) {
  11719. enabled = (enabled && !!Worker);
  11720. this._workerCollisions = enabled;
  11721. if (this.collisionCoordinator) {
  11722. this.collisionCoordinator.destroy();
  11723. }
  11724. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11725. this.collisionCoordinator.init(this);
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11731. get: function () {
  11732. return this._selectionOctree;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11738. /**
  11739. * The mesh that is currently under the pointer.
  11740. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11741. */
  11742. get: function () {
  11743. return this._meshUnderPointer;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Scene.prototype, "pointerX", {
  11749. /**
  11750. * Current on-screen X position of the pointer
  11751. * @return {number} X position of the pointer
  11752. */
  11753. get: function () {
  11754. return this._pointerX;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Scene.prototype, "pointerY", {
  11760. /**
  11761. * Current on-screen Y position of the pointer
  11762. * @return {number} Y position of the pointer
  11763. */
  11764. get: function () {
  11765. return this._pointerY;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Scene.prototype.getCachedMaterial = function () {
  11771. return this._cachedMaterial;
  11772. };
  11773. Scene.prototype.getBoundingBoxRenderer = function () {
  11774. return this._boundingBoxRenderer;
  11775. };
  11776. Scene.prototype.getOutlineRenderer = function () {
  11777. return this._outlineRenderer;
  11778. };
  11779. Scene.prototype.getEngine = function () {
  11780. return this._engine;
  11781. };
  11782. Scene.prototype.getTotalVertices = function () {
  11783. return this._totalVertices;
  11784. };
  11785. Scene.prototype.getActiveIndices = function () {
  11786. return this._activeIndices;
  11787. };
  11788. Scene.prototype.getActiveParticles = function () {
  11789. return this._activeParticles;
  11790. };
  11791. Scene.prototype.getActiveBones = function () {
  11792. return this._activeBones;
  11793. };
  11794. // Stats
  11795. Scene.prototype.getLastFrameDuration = function () {
  11796. return this._lastFrameDuration;
  11797. };
  11798. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11799. return this._evaluateActiveMeshesDuration;
  11800. };
  11801. Scene.prototype.getActiveMeshes = function () {
  11802. return this._activeMeshes;
  11803. };
  11804. Scene.prototype.getRenderTargetsDuration = function () {
  11805. return this._renderTargetsDuration;
  11806. };
  11807. Scene.prototype.getRenderDuration = function () {
  11808. return this._renderDuration;
  11809. };
  11810. Scene.prototype.getParticlesDuration = function () {
  11811. return this._particlesDuration;
  11812. };
  11813. Scene.prototype.getSpritesDuration = function () {
  11814. return this._spritesDuration;
  11815. };
  11816. Scene.prototype.getAnimationRatio = function () {
  11817. return this._animationRatio;
  11818. };
  11819. Scene.prototype.getRenderId = function () {
  11820. return this._renderId;
  11821. };
  11822. Scene.prototype.incrementRenderId = function () {
  11823. this._renderId++;
  11824. };
  11825. Scene.prototype._updatePointerPosition = function (evt) {
  11826. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11827. this._pointerX = evt.clientX - canvasRect.left;
  11828. this._pointerY = evt.clientY - canvasRect.top;
  11829. if (this.cameraToUseForPointers) {
  11830. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11831. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11832. }
  11833. };
  11834. // Pointers handling
  11835. Scene.prototype.attachControl = function () {
  11836. var _this = this;
  11837. var spritePredicate = function (sprite) {
  11838. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11839. };
  11840. this._onPointerMove = function (evt) {
  11841. var canvas = _this._engine.getRenderingCanvas();
  11842. _this._updatePointerPosition(evt);
  11843. // Meshes
  11844. 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);
  11845. if (pickResult.hit && pickResult.pickedMesh) {
  11846. _this._meshUnderPointer = pickResult.pickedMesh;
  11847. _this.setPointerOverMesh(pickResult.pickedMesh);
  11848. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11849. canvas.style.cursor = "pointer";
  11850. }
  11851. else {
  11852. canvas.style.cursor = "";
  11853. }
  11854. }
  11855. else {
  11856. // Sprites
  11857. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11858. if (pickResult.hit && pickResult.pickedSprite) {
  11859. canvas.style.cursor = "pointer";
  11860. return;
  11861. }
  11862. // Restore pointer
  11863. _this.setPointerOverMesh(null);
  11864. canvas.style.cursor = "";
  11865. _this._meshUnderPointer = null;
  11866. }
  11867. };
  11868. this._onPointerDown = function (evt) {
  11869. _this._updatePointerPosition(evt);
  11870. var predicate = null;
  11871. // Meshes
  11872. if (!_this.onPointerDown) {
  11873. predicate = function (mesh) {
  11874. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11875. };
  11876. }
  11877. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11878. if (pickResult.hit && pickResult.pickedMesh) {
  11879. if (pickResult.pickedMesh.actionManager) {
  11880. switch (evt.button) {
  11881. case 0:
  11882. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11883. break;
  11884. case 1:
  11885. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11886. break;
  11887. case 2:
  11888. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11889. break;
  11890. }
  11891. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11892. }
  11893. }
  11894. if (_this.onPointerDown) {
  11895. _this.onPointerDown(evt, pickResult);
  11896. }
  11897. // Sprites
  11898. if (_this.spriteManagers.length > 0) {
  11899. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11900. if (pickResult.hit && pickResult.pickedSprite) {
  11901. if (pickResult.pickedSprite.actionManager) {
  11902. switch (evt.button) {
  11903. case 0:
  11904. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11905. break;
  11906. case 1:
  11907. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11908. break;
  11909. case 2:
  11910. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11911. break;
  11912. }
  11913. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11914. }
  11915. }
  11916. }
  11917. };
  11918. this._onPointerUp = function (evt) {
  11919. var predicate = null;
  11920. _this._updatePointerPosition(evt);
  11921. if (!_this.onPointerUp) {
  11922. predicate = function (mesh) {
  11923. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11924. };
  11925. }
  11926. // Meshes
  11927. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11928. if (pickResult.hit && pickResult.pickedMesh) {
  11929. if (pickResult.pickedMesh.actionManager) {
  11930. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11931. }
  11932. }
  11933. if (_this.onPointerUp) {
  11934. _this.onPointerUp(evt, pickResult);
  11935. }
  11936. // Sprites
  11937. if (_this.spriteManagers.length > 0) {
  11938. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11939. if (pickResult.hit && pickResult.pickedSprite) {
  11940. if (pickResult.pickedSprite.actionManager) {
  11941. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11942. }
  11943. }
  11944. }
  11945. };
  11946. this._onKeyDown = function (evt) {
  11947. if (_this.actionManager) {
  11948. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11949. }
  11950. };
  11951. this._onKeyUp = function (evt) {
  11952. if (_this.actionManager) {
  11953. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11954. }
  11955. };
  11956. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11957. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11958. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11959. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11960. // Wheel
  11961. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11962. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11963. BABYLON.Tools.RegisterTopRootEvents([
  11964. { name: "keydown", handler: this._onKeyDown },
  11965. { name: "keyup", handler: this._onKeyUp }
  11966. ]);
  11967. };
  11968. Scene.prototype.detachControl = function () {
  11969. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11970. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11971. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11972. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11973. // Wheel
  11974. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  11975. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  11976. BABYLON.Tools.UnregisterTopRootEvents([
  11977. { name: "keydown", handler: this._onKeyDown },
  11978. { name: "keyup", handler: this._onKeyUp }
  11979. ]);
  11980. };
  11981. // Ready
  11982. Scene.prototype.isReady = function () {
  11983. if (this._pendingData.length > 0) {
  11984. return false;
  11985. }
  11986. var index;
  11987. for (index = 0; index < this._geometries.length; index++) {
  11988. var geometry = this._geometries[index];
  11989. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11990. return false;
  11991. }
  11992. }
  11993. for (index = 0; index < this.meshes.length; index++) {
  11994. var mesh = this.meshes[index];
  11995. if (!mesh.isReady()) {
  11996. return false;
  11997. }
  11998. var mat = mesh.material;
  11999. if (mat) {
  12000. if (!mat.isReady(mesh)) {
  12001. return false;
  12002. }
  12003. }
  12004. }
  12005. return true;
  12006. };
  12007. Scene.prototype.resetCachedMaterial = function () {
  12008. this._cachedMaterial = null;
  12009. };
  12010. Scene.prototype.registerBeforeRender = function (func) {
  12011. this._onBeforeRenderCallbacks.push(func);
  12012. };
  12013. Scene.prototype.unregisterBeforeRender = function (func) {
  12014. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12015. if (index > -1) {
  12016. this._onBeforeRenderCallbacks.splice(index, 1);
  12017. }
  12018. };
  12019. Scene.prototype.registerAfterRender = function (func) {
  12020. this._onAfterRenderCallbacks.push(func);
  12021. };
  12022. Scene.prototype.unregisterAfterRender = function (func) {
  12023. var index = this._onAfterRenderCallbacks.indexOf(func);
  12024. if (index > -1) {
  12025. this._onAfterRenderCallbacks.splice(index, 1);
  12026. }
  12027. };
  12028. Scene.prototype._addPendingData = function (data) {
  12029. this._pendingData.push(data);
  12030. };
  12031. Scene.prototype._removePendingData = function (data) {
  12032. var index = this._pendingData.indexOf(data);
  12033. if (index !== -1) {
  12034. this._pendingData.splice(index, 1);
  12035. }
  12036. };
  12037. Scene.prototype.getWaitingItemsCount = function () {
  12038. return this._pendingData.length;
  12039. };
  12040. /**
  12041. * Registers a function to be executed when the scene is ready.
  12042. * @param {Function} func - the function to be executed.
  12043. */
  12044. Scene.prototype.executeWhenReady = function (func) {
  12045. var _this = this;
  12046. this._onReadyCallbacks.push(func);
  12047. if (this._executeWhenReadyTimeoutId !== -1) {
  12048. return;
  12049. }
  12050. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12051. _this._checkIsReady();
  12052. }, 150);
  12053. };
  12054. Scene.prototype._checkIsReady = function () {
  12055. var _this = this;
  12056. if (this.isReady()) {
  12057. this._onReadyCallbacks.forEach(function (func) {
  12058. func();
  12059. });
  12060. this._onReadyCallbacks = [];
  12061. this._executeWhenReadyTimeoutId = -1;
  12062. return;
  12063. }
  12064. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12065. _this._checkIsReady();
  12066. }, 150);
  12067. };
  12068. // Animations
  12069. /**
  12070. * Will start the animation sequence of a given target
  12071. * @param target - the target
  12072. * @param {number} from - from which frame should animation start
  12073. * @param {number} to - till which frame should animation run.
  12074. * @param {boolean} [loop] - should the animation loop
  12075. * @param {number} [speedRatio] - the speed in which to run the animation
  12076. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12077. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12078. * @return {BABYLON.Animatable} the animatable object created for this animation
  12079. * @see BABYLON.Animatable
  12080. * @see http://doc.babylonjs.com/page.php?p=22081
  12081. */
  12082. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12083. if (speedRatio === void 0) { speedRatio = 1.0; }
  12084. this.stopAnimation(target);
  12085. if (!animatable) {
  12086. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12087. }
  12088. // Local animations
  12089. if (target.animations) {
  12090. animatable.appendAnimations(target, target.animations);
  12091. }
  12092. // Children animations
  12093. if (target.getAnimatables) {
  12094. var animatables = target.getAnimatables();
  12095. for (var index = 0; index < animatables.length; index++) {
  12096. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12097. }
  12098. }
  12099. return animatable;
  12100. };
  12101. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12102. if (speedRatio === undefined) {
  12103. speedRatio = 1.0;
  12104. }
  12105. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12106. return animatable;
  12107. };
  12108. Scene.prototype.getAnimatableByTarget = function (target) {
  12109. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12110. if (this._activeAnimatables[index].target === target) {
  12111. return this._activeAnimatables[index];
  12112. }
  12113. }
  12114. return null;
  12115. };
  12116. /**
  12117. * Will stop the animation of the given target
  12118. * @param target - the target
  12119. * @see beginAnimation
  12120. */
  12121. Scene.prototype.stopAnimation = function (target) {
  12122. var animatable = this.getAnimatableByTarget(target);
  12123. if (animatable) {
  12124. animatable.stop();
  12125. }
  12126. };
  12127. Scene.prototype._animate = function () {
  12128. if (!this.animationsEnabled) {
  12129. return;
  12130. }
  12131. if (!this._animationStartDate) {
  12132. this._animationStartDate = BABYLON.Tools.Now;
  12133. }
  12134. // Getting time
  12135. var now = BABYLON.Tools.Now;
  12136. var delay = now - this._animationStartDate;
  12137. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12138. this._activeAnimatables[index]._animate(delay);
  12139. }
  12140. };
  12141. // Matrix
  12142. Scene.prototype.getViewMatrix = function () {
  12143. return this._viewMatrix;
  12144. };
  12145. Scene.prototype.getProjectionMatrix = function () {
  12146. return this._projectionMatrix;
  12147. };
  12148. Scene.prototype.getTransformMatrix = function () {
  12149. return this._transformMatrix;
  12150. };
  12151. Scene.prototype.setTransformMatrix = function (view, projection) {
  12152. this._viewMatrix = view;
  12153. this._projectionMatrix = projection;
  12154. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12155. };
  12156. // Methods
  12157. Scene.prototype.addMesh = function (newMesh) {
  12158. newMesh.uniqueId = this._uniqueIdCounter++;
  12159. var position = this.meshes.push(newMesh);
  12160. //notify the collision coordinator
  12161. this.collisionCoordinator.onMeshAdded(newMesh);
  12162. if (this.onNewMeshAdded) {
  12163. this.onNewMeshAdded(newMesh, position, this);
  12164. }
  12165. };
  12166. Scene.prototype.removeMesh = function (toRemove) {
  12167. var index = this.meshes.indexOf(toRemove);
  12168. if (index !== -1) {
  12169. // Remove from the scene if mesh found
  12170. this.meshes.splice(index, 1);
  12171. }
  12172. //notify the collision coordinator
  12173. this.collisionCoordinator.onMeshRemoved(toRemove);
  12174. if (this.onMeshRemoved) {
  12175. this.onMeshRemoved(toRemove);
  12176. }
  12177. return index;
  12178. };
  12179. Scene.prototype.removeSkeleton = function (toRemove) {
  12180. var index = this.skeletons.indexOf(toRemove);
  12181. if (index !== -1) {
  12182. // Remove from the scene if mesh found
  12183. this.skeletons.splice(index, 1);
  12184. }
  12185. return index;
  12186. };
  12187. Scene.prototype.removeLight = function (toRemove) {
  12188. var index = this.lights.indexOf(toRemove);
  12189. if (index !== -1) {
  12190. // Remove from the scene if mesh found
  12191. this.lights.splice(index, 1);
  12192. }
  12193. if (this.onLightRemoved) {
  12194. this.onLightRemoved(toRemove);
  12195. }
  12196. return index;
  12197. };
  12198. Scene.prototype.removeCamera = function (toRemove) {
  12199. var index = this.cameras.indexOf(toRemove);
  12200. if (index !== -1) {
  12201. // Remove from the scene if mesh found
  12202. this.cameras.splice(index, 1);
  12203. }
  12204. // Remove from activeCameras
  12205. var index2 = this.activeCameras.indexOf(toRemove);
  12206. if (index2 !== -1) {
  12207. // Remove from the scene if mesh found
  12208. this.activeCameras.splice(index2, 1);
  12209. }
  12210. // Reset the activeCamera
  12211. if (this.activeCamera === toRemove) {
  12212. if (this.cameras.length > 0) {
  12213. this.activeCamera = this.cameras[0];
  12214. }
  12215. else {
  12216. this.activeCamera = null;
  12217. }
  12218. }
  12219. if (this.onCameraRemoved) {
  12220. this.onCameraRemoved(toRemove);
  12221. }
  12222. return index;
  12223. };
  12224. Scene.prototype.addLight = function (newLight) {
  12225. newLight.uniqueId = this._uniqueIdCounter++;
  12226. var position = this.lights.push(newLight);
  12227. if (this.onNewLightAdded) {
  12228. this.onNewLightAdded(newLight, position, this);
  12229. }
  12230. };
  12231. Scene.prototype.addCamera = function (newCamera) {
  12232. newCamera.uniqueId = this._uniqueIdCounter++;
  12233. var position = this.cameras.push(newCamera);
  12234. if (this.onNewCameraAdded) {
  12235. this.onNewCameraAdded(newCamera, position, this);
  12236. }
  12237. };
  12238. /**
  12239. * sets the active camera of the scene using its ID
  12240. * @param {string} id - the camera's ID
  12241. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12242. * @see activeCamera
  12243. */
  12244. Scene.prototype.setActiveCameraByID = function (id) {
  12245. var camera = this.getCameraByID(id);
  12246. if (camera) {
  12247. this.activeCamera = camera;
  12248. return camera;
  12249. }
  12250. return null;
  12251. };
  12252. /**
  12253. * sets the active camera of the scene using its name
  12254. * @param {string} name - the camera's name
  12255. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12256. * @see activeCamera
  12257. */
  12258. Scene.prototype.setActiveCameraByName = function (name) {
  12259. var camera = this.getCameraByName(name);
  12260. if (camera) {
  12261. this.activeCamera = camera;
  12262. return camera;
  12263. }
  12264. return null;
  12265. };
  12266. /**
  12267. * get a material using its id
  12268. * @param {string} the material's ID
  12269. * @return {BABYLON.Material|null} the material or null if none found.
  12270. */
  12271. Scene.prototype.getMaterialByID = function (id) {
  12272. for (var index = 0; index < this.materials.length; index++) {
  12273. if (this.materials[index].id === id) {
  12274. return this.materials[index];
  12275. }
  12276. }
  12277. return null;
  12278. };
  12279. /**
  12280. * get a material using its name
  12281. * @param {string} the material's name
  12282. * @return {BABYLON.Material|null} the material or null if none found.
  12283. */
  12284. Scene.prototype.getMaterialByName = function (name) {
  12285. for (var index = 0; index < this.materials.length; index++) {
  12286. if (this.materials[index].name === name) {
  12287. return this.materials[index];
  12288. }
  12289. }
  12290. return null;
  12291. };
  12292. Scene.prototype.getLensFlareSystemByName = function (name) {
  12293. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12294. if (this.lensFlareSystems[index].name === name) {
  12295. return this.lensFlareSystems[index];
  12296. }
  12297. }
  12298. return null;
  12299. };
  12300. Scene.prototype.getCameraByID = function (id) {
  12301. for (var index = 0; index < this.cameras.length; index++) {
  12302. if (this.cameras[index].id === id) {
  12303. return this.cameras[index];
  12304. }
  12305. }
  12306. return null;
  12307. };
  12308. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12309. for (var index = 0; index < this.cameras.length; index++) {
  12310. if (this.cameras[index].uniqueId === uniqueId) {
  12311. return this.cameras[index];
  12312. }
  12313. }
  12314. return null;
  12315. };
  12316. /**
  12317. * get a camera using its name
  12318. * @param {string} the camera's name
  12319. * @return {BABYLON.Camera|null} the camera or null if none found.
  12320. */
  12321. Scene.prototype.getCameraByName = function (name) {
  12322. for (var index = 0; index < this.cameras.length; index++) {
  12323. if (this.cameras[index].name === name) {
  12324. return this.cameras[index];
  12325. }
  12326. }
  12327. return null;
  12328. };
  12329. /**
  12330. * get a light node using its name
  12331. * @param {string} the light's name
  12332. * @return {BABYLON.Light|null} the light or null if none found.
  12333. */
  12334. Scene.prototype.getLightByName = function (name) {
  12335. for (var index = 0; index < this.lights.length; index++) {
  12336. if (this.lights[index].name === name) {
  12337. return this.lights[index];
  12338. }
  12339. }
  12340. return null;
  12341. };
  12342. /**
  12343. * get a light node using its ID
  12344. * @param {string} the light's id
  12345. * @return {BABYLON.Light|null} the light or null if none found.
  12346. */
  12347. Scene.prototype.getLightByID = function (id) {
  12348. for (var index = 0; index < this.lights.length; index++) {
  12349. if (this.lights[index].id === id) {
  12350. return this.lights[index];
  12351. }
  12352. }
  12353. return null;
  12354. };
  12355. /**
  12356. * get a light node using its scene-generated unique ID
  12357. * @param {number} the light's unique id
  12358. * @return {BABYLON.Light|null} the light or null if none found.
  12359. */
  12360. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12361. for (var index = 0; index < this.lights.length; index++) {
  12362. if (this.lights[index].uniqueId === uniqueId) {
  12363. return this.lights[index];
  12364. }
  12365. }
  12366. return null;
  12367. };
  12368. /**
  12369. * get a geometry using its ID
  12370. * @param {string} the geometry's id
  12371. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12372. */
  12373. Scene.prototype.getGeometryByID = function (id) {
  12374. for (var index = 0; index < this._geometries.length; index++) {
  12375. if (this._geometries[index].id === id) {
  12376. return this._geometries[index];
  12377. }
  12378. }
  12379. return null;
  12380. };
  12381. /**
  12382. * add a new geometry to this scene.
  12383. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12384. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12385. * @return {boolean} was the geometry added or not
  12386. */
  12387. Scene.prototype.pushGeometry = function (geometry, force) {
  12388. if (!force && this.getGeometryByID(geometry.id)) {
  12389. return false;
  12390. }
  12391. this._geometries.push(geometry);
  12392. //notify the collision coordinator
  12393. this.collisionCoordinator.onGeometryAdded(geometry);
  12394. if (this.onGeometryAdded) {
  12395. this.onGeometryAdded(geometry);
  12396. }
  12397. return true;
  12398. };
  12399. /**
  12400. * Removes an existing geometry
  12401. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12402. * @return {boolean} was the geometry removed or not
  12403. */
  12404. Scene.prototype.removeGeometry = function (geometry) {
  12405. var index = this._geometries.indexOf(geometry);
  12406. if (index > -1) {
  12407. this._geometries.splice(index, 1);
  12408. //notify the collision coordinator
  12409. this.collisionCoordinator.onGeometryDeleted(geometry);
  12410. if (this.onGeometryRemoved) {
  12411. this.onGeometryRemoved(geometry);
  12412. }
  12413. return true;
  12414. }
  12415. return false;
  12416. };
  12417. Scene.prototype.getGeometries = function () {
  12418. return this._geometries;
  12419. };
  12420. /**
  12421. * Get the first added mesh found of a given ID
  12422. * @param {string} id - the id to search for
  12423. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12424. */
  12425. Scene.prototype.getMeshByID = function (id) {
  12426. for (var index = 0; index < this.meshes.length; index++) {
  12427. if (this.meshes[index].id === id) {
  12428. return this.meshes[index];
  12429. }
  12430. }
  12431. return null;
  12432. };
  12433. /**
  12434. * Get a mesh with its auto-generated unique id
  12435. * @param {number} uniqueId - the unique id to search for
  12436. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12437. */
  12438. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12439. for (var index = 0; index < this.meshes.length; index++) {
  12440. if (this.meshes[index].uniqueId === uniqueId) {
  12441. return this.meshes[index];
  12442. }
  12443. }
  12444. return null;
  12445. };
  12446. /**
  12447. * Get a the last added mesh found of a given ID
  12448. * @param {string} id - the id to search for
  12449. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12450. */
  12451. Scene.prototype.getLastMeshByID = function (id) {
  12452. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12453. if (this.meshes[index].id === id) {
  12454. return this.meshes[index];
  12455. }
  12456. }
  12457. return null;
  12458. };
  12459. /**
  12460. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12461. * @param {string} id - the id to search for
  12462. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12463. */
  12464. Scene.prototype.getLastEntryByID = function (id) {
  12465. var index;
  12466. for (index = this.meshes.length - 1; index >= 0; index--) {
  12467. if (this.meshes[index].id === id) {
  12468. return this.meshes[index];
  12469. }
  12470. }
  12471. for (index = this.cameras.length - 1; index >= 0; index--) {
  12472. if (this.cameras[index].id === id) {
  12473. return this.cameras[index];
  12474. }
  12475. }
  12476. for (index = this.lights.length - 1; index >= 0; index--) {
  12477. if (this.lights[index].id === id) {
  12478. return this.lights[index];
  12479. }
  12480. }
  12481. return null;
  12482. };
  12483. Scene.prototype.getNodeByID = function (id) {
  12484. var mesh = this.getMeshByID(id);
  12485. if (mesh) {
  12486. return mesh;
  12487. }
  12488. var light = this.getLightByID(id);
  12489. if (light) {
  12490. return light;
  12491. }
  12492. return this.getCameraByID(id);
  12493. };
  12494. Scene.prototype.getNodeByName = function (name) {
  12495. var mesh = this.getMeshByName(name);
  12496. if (mesh) {
  12497. return mesh;
  12498. }
  12499. var light = this.getLightByName(name);
  12500. if (light) {
  12501. return light;
  12502. }
  12503. return this.getCameraByName(name);
  12504. };
  12505. Scene.prototype.getMeshByName = function (name) {
  12506. for (var index = 0; index < this.meshes.length; index++) {
  12507. if (this.meshes[index].name === name) {
  12508. return this.meshes[index];
  12509. }
  12510. }
  12511. return null;
  12512. };
  12513. Scene.prototype.getSoundByName = function (name) {
  12514. var index;
  12515. if (BABYLON.AudioEngine) {
  12516. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12517. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12518. return this.mainSoundTrack.soundCollection[index];
  12519. }
  12520. }
  12521. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12522. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12523. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12524. return this.soundTracks[sdIndex].soundCollection[index];
  12525. }
  12526. }
  12527. }
  12528. }
  12529. return null;
  12530. };
  12531. Scene.prototype.getLastSkeletonByID = function (id) {
  12532. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12533. if (this.skeletons[index].id === id) {
  12534. return this.skeletons[index];
  12535. }
  12536. }
  12537. return null;
  12538. };
  12539. Scene.prototype.getSkeletonById = function (id) {
  12540. for (var index = 0; index < this.skeletons.length; index++) {
  12541. if (this.skeletons[index].id === id) {
  12542. return this.skeletons[index];
  12543. }
  12544. }
  12545. return null;
  12546. };
  12547. Scene.prototype.getSkeletonByName = function (name) {
  12548. for (var index = 0; index < this.skeletons.length; index++) {
  12549. if (this.skeletons[index].name === name) {
  12550. return this.skeletons[index];
  12551. }
  12552. }
  12553. return null;
  12554. };
  12555. Scene.prototype.isActiveMesh = function (mesh) {
  12556. return (this._activeMeshes.indexOf(mesh) !== -1);
  12557. };
  12558. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12559. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12560. var material = subMesh.getMaterial();
  12561. if (mesh.showSubMeshesBoundingBox) {
  12562. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12563. }
  12564. if (material) {
  12565. // Render targets
  12566. if (material.getRenderTargetTextures) {
  12567. if (this._processedMaterials.indexOf(material) === -1) {
  12568. this._processedMaterials.push(material);
  12569. this._renderTargets.concat(material.getRenderTargetTextures());
  12570. }
  12571. }
  12572. // Dispatch
  12573. this._activeIndices += subMesh.indexCount;
  12574. this._renderingManager.dispatch(subMesh);
  12575. }
  12576. }
  12577. };
  12578. Scene.prototype._evaluateActiveMeshes = function () {
  12579. this.activeCamera._activeMeshes.reset();
  12580. this._activeMeshes.reset();
  12581. this._renderingManager.reset();
  12582. this._processedMaterials.reset();
  12583. this._activeParticleSystems.reset();
  12584. this._activeSkeletons.reset();
  12585. this._softwareSkinnedMeshes.reset();
  12586. this._boundingBoxRenderer.reset();
  12587. this._edgesRenderers.reset();
  12588. if (!this._frustumPlanes) {
  12589. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12590. }
  12591. else {
  12592. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12593. }
  12594. // Meshes
  12595. var meshes;
  12596. var len;
  12597. if (this._selectionOctree) {
  12598. var selection = this._selectionOctree.select(this._frustumPlanes);
  12599. meshes = selection.data;
  12600. len = selection.length;
  12601. }
  12602. else {
  12603. len = this.meshes.length;
  12604. meshes = this.meshes;
  12605. }
  12606. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12607. var mesh = meshes[meshIndex];
  12608. if (mesh.isBlocked) {
  12609. continue;
  12610. }
  12611. this._totalVertices += mesh.getTotalVertices();
  12612. if (!mesh.isReady() || !mesh.isEnabled()) {
  12613. continue;
  12614. }
  12615. mesh.computeWorldMatrix();
  12616. // Intersections
  12617. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12618. this._meshesForIntersections.pushNoDuplicate(mesh);
  12619. }
  12620. // Switch to current LOD
  12621. var meshLOD = mesh.getLOD(this.activeCamera);
  12622. if (!meshLOD) {
  12623. continue;
  12624. }
  12625. mesh._preActivate();
  12626. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12627. this._activeMeshes.push(mesh);
  12628. this.activeCamera._activeMeshes.push(mesh);
  12629. mesh._activate(this._renderId);
  12630. this._activeMesh(meshLOD);
  12631. }
  12632. }
  12633. // Particle systems
  12634. var beforeParticlesDate = BABYLON.Tools.Now;
  12635. if (this.particlesEnabled) {
  12636. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12637. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12638. var particleSystem = this.particleSystems[particleIndex];
  12639. if (!particleSystem.isStarted()) {
  12640. continue;
  12641. }
  12642. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12643. this._activeParticleSystems.push(particleSystem);
  12644. particleSystem.animate();
  12645. }
  12646. }
  12647. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12648. }
  12649. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12650. };
  12651. Scene.prototype._activeMesh = function (mesh) {
  12652. if (mesh.skeleton && this.skeletonsEnabled) {
  12653. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12654. if (!mesh.computeBonesUsingShaders) {
  12655. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12656. }
  12657. }
  12658. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12659. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12660. }
  12661. if (mesh._edgesRenderer) {
  12662. this._edgesRenderers.push(mesh._edgesRenderer);
  12663. }
  12664. if (mesh && mesh.subMeshes) {
  12665. // Submeshes Octrees
  12666. var len;
  12667. var subMeshes;
  12668. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12669. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12670. len = intersections.length;
  12671. subMeshes = intersections.data;
  12672. }
  12673. else {
  12674. subMeshes = mesh.subMeshes;
  12675. len = subMeshes.length;
  12676. }
  12677. for (var subIndex = 0; subIndex < len; subIndex++) {
  12678. var subMesh = subMeshes[subIndex];
  12679. this._evaluateSubMesh(subMesh, mesh);
  12680. }
  12681. }
  12682. };
  12683. Scene.prototype.updateTransformMatrix = function (force) {
  12684. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12685. };
  12686. Scene.prototype._renderForCamera = function (camera) {
  12687. var engine = this._engine;
  12688. this.activeCamera = camera;
  12689. if (!this.activeCamera)
  12690. throw new Error("Active camera not set");
  12691. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12692. // Viewport
  12693. engine.setViewport(this.activeCamera.viewport);
  12694. // Camera
  12695. this.resetCachedMaterial();
  12696. this._renderId++;
  12697. this.updateTransformMatrix();
  12698. if (this.beforeCameraRender) {
  12699. this.beforeCameraRender(this.activeCamera);
  12700. }
  12701. // Meshes
  12702. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12703. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12704. this._evaluateActiveMeshes();
  12705. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12706. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12707. // Skeletons
  12708. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12709. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12710. skeleton.prepare();
  12711. }
  12712. // Software skinning
  12713. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12714. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12715. mesh.applySkeleton(mesh.skeleton);
  12716. }
  12717. // Render targets
  12718. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12719. if (this.renderTargetsEnabled) {
  12720. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12721. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12722. var renderTarget = this._renderTargets.data[renderIndex];
  12723. if (renderTarget._shouldRender()) {
  12724. this._renderId++;
  12725. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12726. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12727. }
  12728. }
  12729. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12730. this._renderId++;
  12731. }
  12732. if (this._renderTargets.length > 0) {
  12733. engine.restoreDefaultFramebuffer();
  12734. }
  12735. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12736. // Prepare Frame
  12737. this.postProcessManager._prepareFrame();
  12738. var beforeRenderDate = BABYLON.Tools.Now;
  12739. // Backgrounds
  12740. var layerIndex;
  12741. var layer;
  12742. if (this.layers.length) {
  12743. engine.setDepthBuffer(false);
  12744. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12745. layer = this.layers[layerIndex];
  12746. if (layer.isBackground) {
  12747. layer.render();
  12748. }
  12749. }
  12750. engine.setDepthBuffer(true);
  12751. }
  12752. // Render
  12753. BABYLON.Tools.StartPerformanceCounter("Main render");
  12754. this._renderingManager.render(null, null, true, true);
  12755. BABYLON.Tools.EndPerformanceCounter("Main render");
  12756. // Bounding boxes
  12757. this._boundingBoxRenderer.render();
  12758. // Edges
  12759. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12760. this._edgesRenderers.data[edgesRendererIndex].render();
  12761. }
  12762. // Lens flares
  12763. if (this.lensFlaresEnabled) {
  12764. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12765. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12766. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12767. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12768. lensFlareSystem.render();
  12769. }
  12770. }
  12771. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12772. }
  12773. // Foregrounds
  12774. if (this.layers.length) {
  12775. engine.setDepthBuffer(false);
  12776. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12777. layer = this.layers[layerIndex];
  12778. if (!layer.isBackground) {
  12779. layer.render();
  12780. }
  12781. }
  12782. engine.setDepthBuffer(true);
  12783. }
  12784. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12785. // Finalize frame
  12786. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12787. // Update camera
  12788. this.activeCamera._updateFromScene();
  12789. // Reset some special arrays
  12790. this._renderTargets.reset();
  12791. if (this.afterCameraRender) {
  12792. this.afterCameraRender(this.activeCamera);
  12793. }
  12794. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12795. };
  12796. Scene.prototype._processSubCameras = function (camera) {
  12797. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12798. this._renderForCamera(camera);
  12799. return;
  12800. }
  12801. // rig cameras
  12802. for (var index = 0; index < camera._rigCameras.length; index++) {
  12803. this._renderForCamera(camera._rigCameras[index]);
  12804. }
  12805. this.activeCamera = camera;
  12806. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12807. // Update camera
  12808. this.activeCamera._updateFromScene();
  12809. };
  12810. Scene.prototype._checkIntersections = function () {
  12811. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12812. var sourceMesh = this._meshesForIntersections.data[index];
  12813. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12814. var action = sourceMesh.actionManager.actions[actionIndex];
  12815. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12816. var parameters = action.getTriggerParameter();
  12817. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12818. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12819. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12820. if (areIntersecting && currentIntersectionInProgress === -1) {
  12821. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12822. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12823. sourceMesh._intersectionsInProgress.push(otherMesh);
  12824. }
  12825. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12826. sourceMesh._intersectionsInProgress.push(otherMesh);
  12827. }
  12828. }
  12829. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12830. //They intersected, and now they don't.
  12831. //is this trigger an exit trigger? execute an event.
  12832. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12833. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12834. }
  12835. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12836. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12837. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12838. }
  12839. }
  12840. }
  12841. }
  12842. }
  12843. };
  12844. Scene.prototype.render = function () {
  12845. var startDate = BABYLON.Tools.Now;
  12846. this._particlesDuration = 0;
  12847. this._spritesDuration = 0;
  12848. this._activeParticles = 0;
  12849. this._renderDuration = 0;
  12850. this._renderTargetsDuration = 0;
  12851. this._evaluateActiveMeshesDuration = 0;
  12852. this._totalVertices = 0;
  12853. this._activeIndices = 0;
  12854. this._activeBones = 0;
  12855. this.getEngine().resetDrawCalls();
  12856. this._meshesForIntersections.reset();
  12857. this.resetCachedMaterial();
  12858. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12859. // Actions
  12860. if (this.actionManager) {
  12861. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12862. }
  12863. //Simplification Queue
  12864. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12865. this.simplificationQueue.executeNext();
  12866. }
  12867. // Animations
  12868. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12869. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12870. this._animate();
  12871. // Physics
  12872. if (this._physicsEngine) {
  12873. BABYLON.Tools.StartPerformanceCounter("Physics");
  12874. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12875. BABYLON.Tools.EndPerformanceCounter("Physics");
  12876. }
  12877. // Before render
  12878. if (this.beforeRender) {
  12879. this.beforeRender();
  12880. }
  12881. var callbackIndex;
  12882. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12883. this._onBeforeRenderCallbacks[callbackIndex]();
  12884. }
  12885. // Customs render targets
  12886. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12887. var engine = this.getEngine();
  12888. var currentActiveCamera = this.activeCamera;
  12889. if (this.renderTargetsEnabled) {
  12890. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12891. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12892. var renderTarget = this.customRenderTargets[customIndex];
  12893. if (renderTarget._shouldRender()) {
  12894. this._renderId++;
  12895. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12896. if (!this.activeCamera)
  12897. throw new Error("Active camera not set");
  12898. // Viewport
  12899. engine.setViewport(this.activeCamera.viewport);
  12900. // Camera
  12901. this.updateTransformMatrix();
  12902. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12903. }
  12904. }
  12905. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12906. this._renderId++;
  12907. }
  12908. if (this.customRenderTargets.length > 0) {
  12909. engine.restoreDefaultFramebuffer();
  12910. }
  12911. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12912. this.activeCamera = currentActiveCamera;
  12913. // Procedural textures
  12914. if (this.proceduralTexturesEnabled) {
  12915. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12916. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12917. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12918. if (proceduralTexture._shouldRender()) {
  12919. proceduralTexture.render();
  12920. }
  12921. }
  12922. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12923. }
  12924. // Clear
  12925. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12926. // Shadows
  12927. if (this.shadowsEnabled) {
  12928. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12929. var light = this.lights[lightIndex];
  12930. var shadowGenerator = light.getShadowGenerator();
  12931. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12932. this._renderTargets.push(shadowGenerator.getShadowMap());
  12933. }
  12934. }
  12935. }
  12936. // Depth renderer
  12937. if (this._depthRenderer) {
  12938. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12939. }
  12940. // RenderPipeline
  12941. this.postProcessRenderPipelineManager.update();
  12942. // Multi-cameras?
  12943. if (this.activeCameras.length > 0) {
  12944. var currentRenderId = this._renderId;
  12945. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12946. this._renderId = currentRenderId;
  12947. this._processSubCameras(this.activeCameras[cameraIndex]);
  12948. }
  12949. }
  12950. else {
  12951. if (!this.activeCamera) {
  12952. throw new Error("No camera defined");
  12953. }
  12954. this._processSubCameras(this.activeCamera);
  12955. }
  12956. // Intersection checks
  12957. this._checkIntersections();
  12958. // Update the audio listener attached to the camera
  12959. if (BABYLON.AudioEngine) {
  12960. this._updateAudioParameters();
  12961. }
  12962. // After render
  12963. if (this.afterRender) {
  12964. this.afterRender();
  12965. }
  12966. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12967. this._onAfterRenderCallbacks[callbackIndex]();
  12968. }
  12969. // Cleaning
  12970. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12971. this._toBeDisposed.data[index].dispose();
  12972. this._toBeDisposed[index] = null;
  12973. }
  12974. this._toBeDisposed.reset();
  12975. if (this.dumpNextRenderTargets) {
  12976. this.dumpNextRenderTargets = false;
  12977. }
  12978. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12979. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12980. };
  12981. Scene.prototype._updateAudioParameters = function () {
  12982. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  12983. return;
  12984. }
  12985. var listeningCamera;
  12986. var audioEngine = BABYLON.Engine.audioEngine;
  12987. if (this.activeCameras.length > 0) {
  12988. listeningCamera = this.activeCameras[0];
  12989. }
  12990. else {
  12991. listeningCamera = this.activeCamera;
  12992. }
  12993. if (listeningCamera && audioEngine.canUseWebAudio) {
  12994. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12995. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12996. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12997. cameraDirection.normalize();
  12998. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12999. var i;
  13000. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13001. var sound = this.mainSoundTrack.soundCollection[i];
  13002. if (sound.useCustomAttenuation) {
  13003. sound.updateDistanceFromListener();
  13004. }
  13005. }
  13006. for (i = 0; i < this.soundTracks.length; i++) {
  13007. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13008. sound = this.soundTracks[i].soundCollection[j];
  13009. if (sound.useCustomAttenuation) {
  13010. sound.updateDistanceFromListener();
  13011. }
  13012. }
  13013. }
  13014. }
  13015. };
  13016. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13017. // Audio
  13018. get: function () {
  13019. return this._audioEnabled;
  13020. },
  13021. set: function (value) {
  13022. this._audioEnabled = value;
  13023. if (BABYLON.AudioEngine) {
  13024. if (this._audioEnabled) {
  13025. this._enableAudio();
  13026. }
  13027. else {
  13028. this._disableAudio();
  13029. }
  13030. }
  13031. },
  13032. enumerable: true,
  13033. configurable: true
  13034. });
  13035. Scene.prototype._disableAudio = function () {
  13036. var i;
  13037. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13038. this.mainSoundTrack.soundCollection[i].pause();
  13039. }
  13040. for (i = 0; i < this.soundTracks.length; i++) {
  13041. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13042. this.soundTracks[i].soundCollection[j].pause();
  13043. }
  13044. }
  13045. };
  13046. Scene.prototype._enableAudio = function () {
  13047. var i;
  13048. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13049. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13050. this.mainSoundTrack.soundCollection[i].play();
  13051. }
  13052. }
  13053. for (i = 0; i < this.soundTracks.length; i++) {
  13054. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13055. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13056. this.soundTracks[i].soundCollection[j].play();
  13057. }
  13058. }
  13059. }
  13060. };
  13061. Object.defineProperty(Scene.prototype, "headphone", {
  13062. get: function () {
  13063. return this._headphone;
  13064. },
  13065. set: function (value) {
  13066. this._headphone = value;
  13067. if (BABYLON.AudioEngine) {
  13068. if (this._headphone) {
  13069. this._switchAudioModeForHeadphones();
  13070. }
  13071. else {
  13072. this._switchAudioModeForNormalSpeakers();
  13073. }
  13074. }
  13075. },
  13076. enumerable: true,
  13077. configurable: true
  13078. });
  13079. Scene.prototype._switchAudioModeForHeadphones = function () {
  13080. this.mainSoundTrack.switchPanningModelToHRTF();
  13081. for (var i = 0; i < this.soundTracks.length; i++) {
  13082. this.soundTracks[i].switchPanningModelToHRTF();
  13083. }
  13084. };
  13085. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13086. this.mainSoundTrack.switchPanningModelToEqualPower();
  13087. for (var i = 0; i < this.soundTracks.length; i++) {
  13088. this.soundTracks[i].switchPanningModelToEqualPower();
  13089. }
  13090. };
  13091. Scene.prototype.enableDepthRenderer = function () {
  13092. if (this._depthRenderer) {
  13093. return this._depthRenderer;
  13094. }
  13095. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13096. return this._depthRenderer;
  13097. };
  13098. Scene.prototype.disableDepthRenderer = function () {
  13099. if (!this._depthRenderer) {
  13100. return;
  13101. }
  13102. this._depthRenderer.dispose();
  13103. this._depthRenderer = null;
  13104. };
  13105. Scene.prototype.dispose = function () {
  13106. this.beforeRender = null;
  13107. this.afterRender = null;
  13108. this.skeletons = [];
  13109. this._boundingBoxRenderer.dispose();
  13110. if (this._depthRenderer) {
  13111. this._depthRenderer.dispose();
  13112. }
  13113. // Debug layer
  13114. this.debugLayer.hide();
  13115. // Events
  13116. if (this.onDispose) {
  13117. this.onDispose();
  13118. }
  13119. this._onBeforeRenderCallbacks = [];
  13120. this._onAfterRenderCallbacks = [];
  13121. this.detachControl();
  13122. // Release sounds & sounds tracks
  13123. if (BABYLON.AudioEngine) {
  13124. this.disposeSounds();
  13125. }
  13126. // Detach cameras
  13127. var canvas = this._engine.getRenderingCanvas();
  13128. var index;
  13129. for (index = 0; index < this.cameras.length; index++) {
  13130. this.cameras[index].detachControl(canvas);
  13131. }
  13132. // Release lights
  13133. while (this.lights.length) {
  13134. this.lights[0].dispose();
  13135. }
  13136. // Release meshes
  13137. while (this.meshes.length) {
  13138. this.meshes[0].dispose(true);
  13139. }
  13140. // Release cameras
  13141. while (this.cameras.length) {
  13142. this.cameras[0].dispose();
  13143. }
  13144. // Release materials
  13145. while (this.materials.length) {
  13146. this.materials[0].dispose();
  13147. }
  13148. // Release particles
  13149. while (this.particleSystems.length) {
  13150. this.particleSystems[0].dispose();
  13151. }
  13152. // Release sprites
  13153. while (this.spriteManagers.length) {
  13154. this.spriteManagers[0].dispose();
  13155. }
  13156. // Release layers
  13157. while (this.layers.length) {
  13158. this.layers[0].dispose();
  13159. }
  13160. // Release textures
  13161. while (this.textures.length) {
  13162. this.textures[0].dispose();
  13163. }
  13164. // Post-processes
  13165. this.postProcessManager.dispose();
  13166. // Physics
  13167. if (this._physicsEngine) {
  13168. this.disablePhysicsEngine();
  13169. }
  13170. // Remove from engine
  13171. index = this._engine.scenes.indexOf(this);
  13172. if (index > -1) {
  13173. this._engine.scenes.splice(index, 1);
  13174. }
  13175. this._engine.wipeCaches();
  13176. };
  13177. // Release sounds & sounds tracks
  13178. Scene.prototype.disposeSounds = function () {
  13179. this.mainSoundTrack.dispose();
  13180. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13181. this.soundTracks[scIndex].dispose();
  13182. }
  13183. };
  13184. // Octrees
  13185. Scene.prototype.getWorldExtends = function () {
  13186. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13187. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13188. for (var index = 0; index < this.meshes.length; index++) {
  13189. var mesh = this.meshes[index];
  13190. mesh.computeWorldMatrix(true);
  13191. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13192. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13193. BABYLON.Tools.CheckExtends(minBox, min, max);
  13194. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13195. }
  13196. return {
  13197. min: min,
  13198. max: max
  13199. };
  13200. };
  13201. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13202. if (maxCapacity === void 0) { maxCapacity = 64; }
  13203. if (maxDepth === void 0) { maxDepth = 2; }
  13204. if (!this._selectionOctree) {
  13205. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13206. }
  13207. var worldExtends = this.getWorldExtends();
  13208. // Update octree
  13209. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13210. return this._selectionOctree;
  13211. };
  13212. // Picking
  13213. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13214. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13215. var engine = this._engine;
  13216. if (!camera) {
  13217. if (!this.activeCamera)
  13218. throw new Error("Active camera not set");
  13219. camera = this.activeCamera;
  13220. }
  13221. var cameraViewport = camera.viewport;
  13222. var viewport = cameraViewport.toGlobal(engine);
  13223. // Moving coordinates to local viewport world
  13224. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13225. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13226. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13227. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13228. };
  13229. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13230. var engine = this._engine;
  13231. if (!camera) {
  13232. if (!this.activeCamera)
  13233. throw new Error("Active camera not set");
  13234. camera = this.activeCamera;
  13235. }
  13236. var cameraViewport = camera.viewport;
  13237. var viewport = cameraViewport.toGlobal(engine);
  13238. var identity = BABYLON.Matrix.Identity();
  13239. // Moving coordinates to local viewport world
  13240. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13241. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13242. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13243. };
  13244. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13245. var pickingInfo = null;
  13246. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13247. var mesh = this.meshes[meshIndex];
  13248. if (predicate) {
  13249. if (!predicate(mesh)) {
  13250. continue;
  13251. }
  13252. }
  13253. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13254. continue;
  13255. }
  13256. var world = mesh.getWorldMatrix();
  13257. var ray = rayFunction(world);
  13258. var result = mesh.intersects(ray, fastCheck);
  13259. if (!result || !result.hit)
  13260. continue;
  13261. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13262. continue;
  13263. pickingInfo = result;
  13264. if (fastCheck) {
  13265. break;
  13266. }
  13267. }
  13268. return pickingInfo || new BABYLON.PickingInfo();
  13269. };
  13270. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13271. var pickingInfo = null;
  13272. camera = camera || this.activeCamera;
  13273. if (this.spriteManagers.length > 0) {
  13274. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13275. var spriteManager = this.spriteManagers[spriteIndex];
  13276. if (!spriteManager.isPickable) {
  13277. continue;
  13278. }
  13279. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13280. if (!result || !result.hit)
  13281. continue;
  13282. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13283. continue;
  13284. pickingInfo = result;
  13285. if (fastCheck) {
  13286. break;
  13287. }
  13288. }
  13289. }
  13290. return pickingInfo || new BABYLON.PickingInfo();
  13291. };
  13292. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13293. var _this = this;
  13294. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13295. /// <param name="x">X position on screen</param>
  13296. /// <param name="y">Y position on screen</param>
  13297. /// <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>
  13298. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13299. /// <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>
  13300. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13301. };
  13302. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13303. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13304. /// <param name="x">X position on screen</param>
  13305. /// <param name="y">Y position on screen</param>
  13306. /// <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>
  13307. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13308. /// <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>
  13309. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13310. };
  13311. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13312. var _this = this;
  13313. return this._internalPick(function (world) {
  13314. if (!_this._pickWithRayInverseMatrix) {
  13315. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13316. }
  13317. world.invertToRef(_this._pickWithRayInverseMatrix);
  13318. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13319. }, predicate, fastCheck);
  13320. };
  13321. Scene.prototype.setPointerOverMesh = function (mesh) {
  13322. if (this._pointerOverMesh === mesh) {
  13323. return;
  13324. }
  13325. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13326. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13327. }
  13328. this._pointerOverMesh = mesh;
  13329. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13330. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13331. }
  13332. };
  13333. Scene.prototype.getPointerOverMesh = function () {
  13334. return this._pointerOverMesh;
  13335. };
  13336. // Physics
  13337. Scene.prototype.getPhysicsEngine = function () {
  13338. return this._physicsEngine;
  13339. };
  13340. /**
  13341. * Enables physics to the current scene
  13342. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13343. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13344. * @return {boolean} was the physics engine initialized
  13345. */
  13346. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13347. if (this._physicsEngine) {
  13348. return true;
  13349. }
  13350. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13351. if (!this._physicsEngine.isSupported()) {
  13352. this._physicsEngine = null;
  13353. return false;
  13354. }
  13355. this._physicsEngine._initialize(gravity);
  13356. return true;
  13357. };
  13358. Scene.prototype.disablePhysicsEngine = function () {
  13359. if (!this._physicsEngine) {
  13360. return;
  13361. }
  13362. this._physicsEngine.dispose();
  13363. this._physicsEngine = undefined;
  13364. };
  13365. Scene.prototype.isPhysicsEnabled = function () {
  13366. return this._physicsEngine !== undefined;
  13367. };
  13368. /**
  13369. * Sets the gravity of the physics engine (and NOT of the scene)
  13370. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13371. */
  13372. Scene.prototype.setGravity = function (gravity) {
  13373. if (!this._physicsEngine) {
  13374. return;
  13375. }
  13376. this._physicsEngine._setGravity(gravity);
  13377. };
  13378. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13379. if (parts.parts) {
  13380. options = parts;
  13381. parts = parts.parts;
  13382. }
  13383. if (!this._physicsEngine) {
  13384. return null;
  13385. }
  13386. for (var index = 0; index < parts.length; index++) {
  13387. var mesh = parts[index].mesh;
  13388. mesh._physicImpostor = parts[index].impostor;
  13389. mesh._physicsMass = options.mass / parts.length;
  13390. mesh._physicsFriction = options.friction;
  13391. mesh._physicRestitution = options.restitution;
  13392. }
  13393. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13394. };
  13395. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13396. for (var index = 0; index < compound.parts.length; index++) {
  13397. var mesh = compound.parts[index].mesh;
  13398. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13399. this._physicsEngine._unregisterMesh(mesh);
  13400. }
  13401. };
  13402. // Misc.
  13403. Scene.prototype.createDefaultCameraOrLight = function () {
  13404. // Light
  13405. if (this.lights.length === 0) {
  13406. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13407. }
  13408. // Camera
  13409. if (!this.activeCamera) {
  13410. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13411. // Compute position
  13412. var worldExtends = this.getWorldExtends();
  13413. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13414. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13415. camera.setTarget(worldCenter);
  13416. this.activeCamera = camera;
  13417. }
  13418. };
  13419. // Tags
  13420. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13421. if (tagsQuery === undefined) {
  13422. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13423. return list;
  13424. }
  13425. var listByTags = [];
  13426. forEach = forEach || (function (item) { return; });
  13427. for (var i in list) {
  13428. var item = list[i];
  13429. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13430. listByTags.push(item);
  13431. forEach(item);
  13432. }
  13433. }
  13434. return listByTags;
  13435. };
  13436. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13437. return this._getByTags(this.meshes, tagsQuery, forEach);
  13438. };
  13439. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13440. return this._getByTags(this.cameras, tagsQuery, forEach);
  13441. };
  13442. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13443. return this._getByTags(this.lights, tagsQuery, forEach);
  13444. };
  13445. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13446. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13447. };
  13448. // Statics
  13449. Scene._FOGMODE_NONE = 0;
  13450. Scene._FOGMODE_EXP = 1;
  13451. Scene._FOGMODE_EXP2 = 2;
  13452. Scene._FOGMODE_LINEAR = 3;
  13453. Scene.MinDeltaTime = 1.0;
  13454. Scene.MaxDeltaTime = 1000.0;
  13455. return Scene;
  13456. })();
  13457. BABYLON.Scene = Scene;
  13458. })(BABYLON || (BABYLON = {}));
  13459. var BABYLON;
  13460. (function (BABYLON) {
  13461. var VertexBuffer = (function () {
  13462. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13463. if (engine instanceof BABYLON.Mesh) {
  13464. this._engine = engine.getScene().getEngine();
  13465. }
  13466. else {
  13467. this._engine = engine;
  13468. }
  13469. this._updatable = updatable;
  13470. this._data = data;
  13471. if (!postponeInternalCreation) {
  13472. this.create();
  13473. }
  13474. this._kind = kind;
  13475. if (stride) {
  13476. this._strideSize = stride;
  13477. return;
  13478. }
  13479. // Deduce stride from kind
  13480. switch (kind) {
  13481. case VertexBuffer.PositionKind:
  13482. this._strideSize = 3;
  13483. break;
  13484. case VertexBuffer.NormalKind:
  13485. this._strideSize = 3;
  13486. break;
  13487. case VertexBuffer.UVKind:
  13488. case VertexBuffer.UV2Kind:
  13489. case VertexBuffer.UV3Kind:
  13490. case VertexBuffer.UV4Kind:
  13491. case VertexBuffer.UV5Kind:
  13492. case VertexBuffer.UV6Kind:
  13493. this._strideSize = 2;
  13494. break;
  13495. case VertexBuffer.ColorKind:
  13496. this._strideSize = 4;
  13497. break;
  13498. case VertexBuffer.MatricesIndicesKind:
  13499. case VertexBuffer.MatricesIndicesExtraKind:
  13500. this._strideSize = 4;
  13501. break;
  13502. case VertexBuffer.MatricesWeightsKind:
  13503. case VertexBuffer.MatricesWeightsExtraKind:
  13504. this._strideSize = 4;
  13505. break;
  13506. }
  13507. }
  13508. // Properties
  13509. VertexBuffer.prototype.isUpdatable = function () {
  13510. return this._updatable;
  13511. };
  13512. VertexBuffer.prototype.getData = function () {
  13513. return this._data;
  13514. };
  13515. VertexBuffer.prototype.getBuffer = function () {
  13516. return this._buffer;
  13517. };
  13518. VertexBuffer.prototype.getStrideSize = function () {
  13519. return this._strideSize;
  13520. };
  13521. // Methods
  13522. VertexBuffer.prototype.create = function (data) {
  13523. if (!data && this._buffer) {
  13524. return; // nothing to do
  13525. }
  13526. data = data || this._data;
  13527. if (!this._buffer) {
  13528. if (this._updatable) {
  13529. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13530. }
  13531. else {
  13532. this._buffer = this._engine.createVertexBuffer(data);
  13533. }
  13534. }
  13535. if (this._updatable) {
  13536. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13537. this._data = data;
  13538. }
  13539. };
  13540. VertexBuffer.prototype.update = function (data) {
  13541. this.create(data);
  13542. };
  13543. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13544. if (!this._buffer) {
  13545. return;
  13546. }
  13547. if (this._updatable) {
  13548. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13549. this._data = null;
  13550. }
  13551. };
  13552. VertexBuffer.prototype.dispose = function () {
  13553. if (!this._buffer) {
  13554. return;
  13555. }
  13556. if (this._engine._releaseBuffer(this._buffer)) {
  13557. this._buffer = null;
  13558. }
  13559. };
  13560. Object.defineProperty(VertexBuffer, "PositionKind", {
  13561. get: function () {
  13562. return VertexBuffer._PositionKind;
  13563. },
  13564. enumerable: true,
  13565. configurable: true
  13566. });
  13567. Object.defineProperty(VertexBuffer, "NormalKind", {
  13568. get: function () {
  13569. return VertexBuffer._NormalKind;
  13570. },
  13571. enumerable: true,
  13572. configurable: true
  13573. });
  13574. Object.defineProperty(VertexBuffer, "UVKind", {
  13575. get: function () {
  13576. return VertexBuffer._UVKind;
  13577. },
  13578. enumerable: true,
  13579. configurable: true
  13580. });
  13581. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13582. get: function () {
  13583. return VertexBuffer._UV2Kind;
  13584. },
  13585. enumerable: true,
  13586. configurable: true
  13587. });
  13588. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13589. get: function () {
  13590. return VertexBuffer._UV3Kind;
  13591. },
  13592. enumerable: true,
  13593. configurable: true
  13594. });
  13595. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13596. get: function () {
  13597. return VertexBuffer._UV4Kind;
  13598. },
  13599. enumerable: true,
  13600. configurable: true
  13601. });
  13602. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13603. get: function () {
  13604. return VertexBuffer._UV5Kind;
  13605. },
  13606. enumerable: true,
  13607. configurable: true
  13608. });
  13609. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13610. get: function () {
  13611. return VertexBuffer._UV6Kind;
  13612. },
  13613. enumerable: true,
  13614. configurable: true
  13615. });
  13616. Object.defineProperty(VertexBuffer, "ColorKind", {
  13617. get: function () {
  13618. return VertexBuffer._ColorKind;
  13619. },
  13620. enumerable: true,
  13621. configurable: true
  13622. });
  13623. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13624. get: function () {
  13625. return VertexBuffer._MatricesIndicesKind;
  13626. },
  13627. enumerable: true,
  13628. configurable: true
  13629. });
  13630. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13631. get: function () {
  13632. return VertexBuffer._MatricesWeightsKind;
  13633. },
  13634. enumerable: true,
  13635. configurable: true
  13636. });
  13637. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  13638. get: function () {
  13639. return VertexBuffer._MatricesIndicesExtraKind;
  13640. },
  13641. enumerable: true,
  13642. configurable: true
  13643. });
  13644. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  13645. get: function () {
  13646. return VertexBuffer._MatricesWeightsExtraKind;
  13647. },
  13648. enumerable: true,
  13649. configurable: true
  13650. });
  13651. // Enums
  13652. VertexBuffer._PositionKind = "position";
  13653. VertexBuffer._NormalKind = "normal";
  13654. VertexBuffer._UVKind = "uv";
  13655. VertexBuffer._UV2Kind = "uv2";
  13656. VertexBuffer._UV3Kind = "uv3";
  13657. VertexBuffer._UV4Kind = "uv4";
  13658. VertexBuffer._UV5Kind = "uv5";
  13659. VertexBuffer._UV6Kind = "uv6";
  13660. VertexBuffer._ColorKind = "color";
  13661. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13662. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13663. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  13664. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  13665. return VertexBuffer;
  13666. })();
  13667. BABYLON.VertexBuffer = VertexBuffer;
  13668. })(BABYLON || (BABYLON = {}));
  13669. var BABYLON;
  13670. (function (BABYLON) {
  13671. /**
  13672. * Creates an instance based on a source mesh.
  13673. */
  13674. var InstancedMesh = (function (_super) {
  13675. __extends(InstancedMesh, _super);
  13676. function InstancedMesh(name, source) {
  13677. _super.call(this, name, source.getScene());
  13678. source.instances.push(this);
  13679. this._sourceMesh = source;
  13680. this.position.copyFrom(source.position);
  13681. this.rotation.copyFrom(source.rotation);
  13682. this.scaling.copyFrom(source.scaling);
  13683. if (source.rotationQuaternion) {
  13684. this.rotationQuaternion = source.rotationQuaternion.clone();
  13685. }
  13686. this.infiniteDistance = source.infiniteDistance;
  13687. this.setPivotMatrix(source.getPivotMatrix());
  13688. this.refreshBoundingInfo();
  13689. this._syncSubMeshes();
  13690. }
  13691. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13692. // Methods
  13693. get: function () {
  13694. return this._sourceMesh.receiveShadows;
  13695. },
  13696. enumerable: true,
  13697. configurable: true
  13698. });
  13699. Object.defineProperty(InstancedMesh.prototype, "material", {
  13700. get: function () {
  13701. return this._sourceMesh.material;
  13702. },
  13703. enumerable: true,
  13704. configurable: true
  13705. });
  13706. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13707. get: function () {
  13708. return this._sourceMesh.visibility;
  13709. },
  13710. enumerable: true,
  13711. configurable: true
  13712. });
  13713. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13714. get: function () {
  13715. return this._sourceMesh.skeleton;
  13716. },
  13717. enumerable: true,
  13718. configurable: true
  13719. });
  13720. InstancedMesh.prototype.getTotalVertices = function () {
  13721. return this._sourceMesh.getTotalVertices();
  13722. };
  13723. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13724. get: function () {
  13725. return this._sourceMesh;
  13726. },
  13727. enumerable: true,
  13728. configurable: true
  13729. });
  13730. InstancedMesh.prototype.getVerticesData = function (kind) {
  13731. return this._sourceMesh.getVerticesData(kind);
  13732. };
  13733. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13734. return this._sourceMesh.isVerticesDataPresent(kind);
  13735. };
  13736. InstancedMesh.prototype.getIndices = function () {
  13737. return this._sourceMesh.getIndices();
  13738. };
  13739. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13740. get: function () {
  13741. return this._sourceMesh._positions;
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13747. var meshBB = this._sourceMesh.getBoundingInfo();
  13748. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13749. this._updateBoundingInfo();
  13750. };
  13751. InstancedMesh.prototype._preActivate = function () {
  13752. if (this._currentLOD) {
  13753. this._currentLOD._preActivate();
  13754. }
  13755. };
  13756. InstancedMesh.prototype._activate = function (renderId) {
  13757. if (this._currentLOD) {
  13758. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13759. }
  13760. };
  13761. InstancedMesh.prototype.getLOD = function (camera) {
  13762. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13763. if (this._currentLOD === this.sourceMesh) {
  13764. return this;
  13765. }
  13766. return this._currentLOD;
  13767. };
  13768. InstancedMesh.prototype._syncSubMeshes = function () {
  13769. this.releaseSubMeshes();
  13770. if (this._sourceMesh.subMeshes) {
  13771. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13772. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13773. }
  13774. }
  13775. };
  13776. InstancedMesh.prototype._generatePointsArray = function () {
  13777. return this._sourceMesh._generatePointsArray();
  13778. };
  13779. // Clone
  13780. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13781. var result = this._sourceMesh.createInstance(name);
  13782. // Deep copy
  13783. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13784. // Bounding info
  13785. this.refreshBoundingInfo();
  13786. // Parent
  13787. if (newParent) {
  13788. result.parent = newParent;
  13789. }
  13790. if (!doNotCloneChildren) {
  13791. // Children
  13792. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13793. var mesh = this.getScene().meshes[index];
  13794. if (mesh.parent === this) {
  13795. mesh.clone(mesh.name, result);
  13796. }
  13797. }
  13798. }
  13799. result.computeWorldMatrix(true);
  13800. return result;
  13801. };
  13802. // Dispoe
  13803. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13804. // Remove from mesh
  13805. var index = this._sourceMesh.instances.indexOf(this);
  13806. this._sourceMesh.instances.splice(index, 1);
  13807. _super.prototype.dispose.call(this, doNotRecurse);
  13808. };
  13809. return InstancedMesh;
  13810. })(BABYLON.AbstractMesh);
  13811. BABYLON.InstancedMesh = InstancedMesh;
  13812. })(BABYLON || (BABYLON = {}));
  13813. var BABYLON;
  13814. (function (BABYLON) {
  13815. var _InstancesBatch = (function () {
  13816. function _InstancesBatch() {
  13817. this.mustReturn = false;
  13818. this.visibleInstances = new Array();
  13819. this.renderSelf = new Array();
  13820. }
  13821. return _InstancesBatch;
  13822. })();
  13823. BABYLON._InstancesBatch = _InstancesBatch;
  13824. var Mesh = (function (_super) {
  13825. __extends(Mesh, _super);
  13826. /**
  13827. * @constructor
  13828. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13829. * @param {Scene} scene - The scene to add this mesh to.
  13830. * @param {Node} parent - The parent of this mesh, if it has one
  13831. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13832. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13833. * When false, achieved by calling a clone(), also passing False.
  13834. * This will make creation of children, recursive.
  13835. */
  13836. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13837. if (parent === void 0) { parent = null; }
  13838. _super.call(this, name, scene);
  13839. // Members
  13840. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13841. this.instances = new Array();
  13842. this._LODLevels = new Array();
  13843. this._onBeforeRenderCallbacks = new Array();
  13844. this._onAfterRenderCallbacks = new Array();
  13845. this._visibleInstances = {};
  13846. this._renderIdForInstances = new Array();
  13847. this._batchCache = new _InstancesBatch();
  13848. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13849. this._sideOrientation = Mesh._DEFAULTSIDE;
  13850. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13851. if (source) {
  13852. // Geometry
  13853. if (source._geometry) {
  13854. source._geometry.applyToMesh(this);
  13855. }
  13856. // Deep copy
  13857. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13858. this.id = name + "." + source.id;
  13859. // Material
  13860. this.material = source.material;
  13861. var index;
  13862. if (!doNotCloneChildren) {
  13863. // Children
  13864. for (index = 0; index < scene.meshes.length; index++) {
  13865. var mesh = scene.meshes[index];
  13866. if (mesh.parent === source) {
  13867. // doNotCloneChildren is always going to be False
  13868. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13869. }
  13870. }
  13871. }
  13872. // Particles
  13873. for (index = 0; index < scene.particleSystems.length; index++) {
  13874. var system = scene.particleSystems[index];
  13875. if (system.emitter === source) {
  13876. system.clone(system.name, this);
  13877. }
  13878. }
  13879. this.computeWorldMatrix(true);
  13880. }
  13881. // Parent
  13882. if (parent !== null) {
  13883. this.parent = parent;
  13884. }
  13885. }
  13886. Object.defineProperty(Mesh, "FRONTSIDE", {
  13887. get: function () {
  13888. return Mesh._FRONTSIDE;
  13889. },
  13890. enumerable: true,
  13891. configurable: true
  13892. });
  13893. Object.defineProperty(Mesh, "BACKSIDE", {
  13894. get: function () {
  13895. return Mesh._BACKSIDE;
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13901. get: function () {
  13902. return Mesh._DOUBLESIDE;
  13903. },
  13904. enumerable: true,
  13905. configurable: true
  13906. });
  13907. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13908. get: function () {
  13909. return Mesh._DEFAULTSIDE;
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(Mesh, "NO_CAP", {
  13915. get: function () {
  13916. return Mesh._NO_CAP;
  13917. },
  13918. enumerable: true,
  13919. configurable: true
  13920. });
  13921. Object.defineProperty(Mesh, "CAP_START", {
  13922. get: function () {
  13923. return Mesh._CAP_START;
  13924. },
  13925. enumerable: true,
  13926. configurable: true
  13927. });
  13928. Object.defineProperty(Mesh, "CAP_END", {
  13929. get: function () {
  13930. return Mesh._CAP_END;
  13931. },
  13932. enumerable: true,
  13933. configurable: true
  13934. });
  13935. Object.defineProperty(Mesh, "CAP_ALL", {
  13936. get: function () {
  13937. return Mesh._CAP_ALL;
  13938. },
  13939. enumerable: true,
  13940. configurable: true
  13941. });
  13942. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13943. // Methods
  13944. get: function () {
  13945. return this._LODLevels.length > 0;
  13946. },
  13947. enumerable: true,
  13948. configurable: true
  13949. });
  13950. Mesh.prototype._sortLODLevels = function () {
  13951. this._LODLevels.sort(function (a, b) {
  13952. if (a.distance < b.distance) {
  13953. return 1;
  13954. }
  13955. if (a.distance > b.distance) {
  13956. return -1;
  13957. }
  13958. return 0;
  13959. });
  13960. };
  13961. /**
  13962. * Add a mesh as LOD level triggered at the given distance.
  13963. * @param {number} distance - the distance from the center of the object to show this level
  13964. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13965. * @return {BABYLON.Mesh} this mesh (for chaining)
  13966. */
  13967. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13968. if (mesh && mesh._masterMesh) {
  13969. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13970. return this;
  13971. }
  13972. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13973. this._LODLevels.push(level);
  13974. if (mesh) {
  13975. mesh._masterMesh = this;
  13976. }
  13977. this._sortLODLevels();
  13978. return this;
  13979. };
  13980. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13981. for (var index = 0; index < this._LODLevels.length; index++) {
  13982. var level = this._LODLevels[index];
  13983. if (level.distance === distance) {
  13984. return level.mesh;
  13985. }
  13986. }
  13987. return null;
  13988. };
  13989. /**
  13990. * Remove a mesh from the LOD array
  13991. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13992. * @return {BABYLON.Mesh} this mesh (for chaining)
  13993. */
  13994. Mesh.prototype.removeLODLevel = function (mesh) {
  13995. for (var index = 0; index < this._LODLevels.length; index++) {
  13996. if (this._LODLevels[index].mesh === mesh) {
  13997. this._LODLevels.splice(index, 1);
  13998. if (mesh) {
  13999. mesh._masterMesh = null;
  14000. }
  14001. }
  14002. }
  14003. this._sortLODLevels();
  14004. return this;
  14005. };
  14006. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14007. if (!this._LODLevels || this._LODLevels.length === 0) {
  14008. return this;
  14009. }
  14010. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14011. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14012. if (this.onLODLevelSelection) {
  14013. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14014. }
  14015. return this;
  14016. }
  14017. for (var index = 0; index < this._LODLevels.length; index++) {
  14018. var level = this._LODLevels[index];
  14019. if (level.distance < distanceToCamera) {
  14020. if (level.mesh) {
  14021. level.mesh._preActivate();
  14022. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14023. }
  14024. if (this.onLODLevelSelection) {
  14025. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14026. }
  14027. return level.mesh;
  14028. }
  14029. }
  14030. if (this.onLODLevelSelection) {
  14031. this.onLODLevelSelection(distanceToCamera, this, this);
  14032. }
  14033. return this;
  14034. };
  14035. Object.defineProperty(Mesh.prototype, "geometry", {
  14036. get: function () {
  14037. return this._geometry;
  14038. },
  14039. enumerable: true,
  14040. configurable: true
  14041. });
  14042. Mesh.prototype.getTotalVertices = function () {
  14043. if (!this._geometry) {
  14044. return 0;
  14045. }
  14046. return this._geometry.getTotalVertices();
  14047. };
  14048. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14049. if (!this._geometry) {
  14050. return null;
  14051. }
  14052. return this._geometry.getVerticesData(kind, copyWhenShared);
  14053. };
  14054. Mesh.prototype.getVertexBuffer = function (kind) {
  14055. if (!this._geometry) {
  14056. return undefined;
  14057. }
  14058. return this._geometry.getVertexBuffer(kind);
  14059. };
  14060. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14061. if (!this._geometry) {
  14062. if (this._delayInfo) {
  14063. return this._delayInfo.indexOf(kind) !== -1;
  14064. }
  14065. return false;
  14066. }
  14067. return this._geometry.isVerticesDataPresent(kind);
  14068. };
  14069. Mesh.prototype.getVerticesDataKinds = function () {
  14070. if (!this._geometry) {
  14071. var result = [];
  14072. if (this._delayInfo) {
  14073. for (var kind in this._delayInfo) {
  14074. result.push(kind);
  14075. }
  14076. }
  14077. return result;
  14078. }
  14079. return this._geometry.getVerticesDataKinds();
  14080. };
  14081. Mesh.prototype.getTotalIndices = function () {
  14082. if (!this._geometry) {
  14083. return 0;
  14084. }
  14085. return this._geometry.getTotalIndices();
  14086. };
  14087. Mesh.prototype.getIndices = function (copyWhenShared) {
  14088. if (!this._geometry) {
  14089. return [];
  14090. }
  14091. return this._geometry.getIndices(copyWhenShared);
  14092. };
  14093. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14094. get: function () {
  14095. return this._masterMesh !== null && this._masterMesh !== undefined;
  14096. },
  14097. enumerable: true,
  14098. configurable: true
  14099. });
  14100. Mesh.prototype.isReady = function () {
  14101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14102. return false;
  14103. }
  14104. return _super.prototype.isReady.call(this);
  14105. };
  14106. Mesh.prototype.isDisposed = function () {
  14107. return this._isDisposed;
  14108. };
  14109. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14110. get: function () {
  14111. return this._sideOrientation;
  14112. },
  14113. set: function (sideO) {
  14114. this._sideOrientation = sideO;
  14115. },
  14116. enumerable: true,
  14117. configurable: true
  14118. });
  14119. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14120. get: function () {
  14121. return this._areNormalsFrozen;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14127. Mesh.prototype.freezeNormals = function () {
  14128. this._areNormalsFrozen = true;
  14129. };
  14130. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14131. Mesh.prototype.unfreezeNormals = function () {
  14132. this._areNormalsFrozen = false;
  14133. };
  14134. // Methods
  14135. Mesh.prototype._preActivate = function () {
  14136. var sceneRenderId = this.getScene().getRenderId();
  14137. if (this._preActivateId === sceneRenderId) {
  14138. return;
  14139. }
  14140. this._preActivateId = sceneRenderId;
  14141. this._visibleInstances = null;
  14142. };
  14143. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14144. if (!this._visibleInstances) {
  14145. this._visibleInstances = {};
  14146. this._visibleInstances.defaultRenderId = renderId;
  14147. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14148. }
  14149. if (!this._visibleInstances[renderId]) {
  14150. this._visibleInstances[renderId] = new Array();
  14151. }
  14152. this._visibleInstances[renderId].push(instance);
  14153. };
  14154. Mesh.prototype.refreshBoundingInfo = function () {
  14155. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14156. if (data) {
  14157. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14158. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14159. }
  14160. if (this.subMeshes) {
  14161. for (var index = 0; index < this.subMeshes.length; index++) {
  14162. this.subMeshes[index].refreshBoundingInfo();
  14163. }
  14164. }
  14165. this._updateBoundingInfo();
  14166. };
  14167. Mesh.prototype._createGlobalSubMesh = function () {
  14168. var totalVertices = this.getTotalVertices();
  14169. if (!totalVertices || !this.getIndices()) {
  14170. return null;
  14171. }
  14172. this.releaseSubMeshes();
  14173. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14174. };
  14175. Mesh.prototype.subdivide = function (count) {
  14176. if (count < 1) {
  14177. return;
  14178. }
  14179. var totalIndices = this.getTotalIndices();
  14180. var subdivisionSize = (totalIndices / count) | 0;
  14181. var offset = 0;
  14182. // Ensure that subdivisionSize is a multiple of 3
  14183. while (subdivisionSize % 3 !== 0) {
  14184. subdivisionSize++;
  14185. }
  14186. this.releaseSubMeshes();
  14187. for (var index = 0; index < count; index++) {
  14188. if (offset >= totalIndices) {
  14189. break;
  14190. }
  14191. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14192. offset += subdivisionSize;
  14193. }
  14194. this.synchronizeInstances();
  14195. };
  14196. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14197. if (!this._geometry) {
  14198. var vertexData = new BABYLON.VertexData();
  14199. vertexData.set(data, kind);
  14200. var scene = this.getScene();
  14201. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14202. }
  14203. else {
  14204. this._geometry.setVerticesData(kind, data, updatable, stride);
  14205. }
  14206. };
  14207. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14208. if (!this._geometry) {
  14209. return;
  14210. }
  14211. if (!makeItUnique) {
  14212. this._geometry.updateVerticesData(kind, data, updateExtends);
  14213. }
  14214. else {
  14215. this.makeGeometryUnique();
  14216. this.updateVerticesData(kind, data, updateExtends, false);
  14217. }
  14218. };
  14219. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14220. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14221. if (!this._geometry) {
  14222. return;
  14223. }
  14224. if (!makeItUnique) {
  14225. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14226. }
  14227. else {
  14228. this.makeGeometryUnique();
  14229. this.updateVerticesDataDirectly(kind, data, offset, false);
  14230. }
  14231. };
  14232. // Mesh positions update function :
  14233. // updates the mesh positions according to the positionFunction returned values.
  14234. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14235. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14236. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14237. if (computeNormals === void 0) { computeNormals = true; }
  14238. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14239. positionFunction(positions);
  14240. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14241. if (computeNormals) {
  14242. var indices = this.getIndices();
  14243. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14244. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14245. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14246. }
  14247. };
  14248. Mesh.prototype.makeGeometryUnique = function () {
  14249. if (!this._geometry) {
  14250. return;
  14251. }
  14252. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14253. geometry.applyToMesh(this);
  14254. };
  14255. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14256. if (!this._geometry) {
  14257. var vertexData = new BABYLON.VertexData();
  14258. vertexData.indices = indices;
  14259. var scene = this.getScene();
  14260. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14261. }
  14262. else {
  14263. this._geometry.setIndices(indices, totalVertices);
  14264. }
  14265. };
  14266. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14267. var engine = this.getScene().getEngine();
  14268. // Wireframe
  14269. var indexToBind;
  14270. switch (fillMode) {
  14271. case BABYLON.Material.PointFillMode:
  14272. indexToBind = null;
  14273. break;
  14274. case BABYLON.Material.WireFrameFillMode:
  14275. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14276. break;
  14277. default:
  14278. case BABYLON.Material.TriangleFillMode:
  14279. indexToBind = this._geometry.getIndexBuffer();
  14280. break;
  14281. }
  14282. // VBOs
  14283. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14284. };
  14285. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14286. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14287. return;
  14288. }
  14289. var engine = this.getScene().getEngine();
  14290. // Draw order
  14291. switch (fillMode) {
  14292. case BABYLON.Material.PointFillMode:
  14293. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14294. break;
  14295. case BABYLON.Material.WireFrameFillMode:
  14296. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14297. break;
  14298. default:
  14299. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14300. }
  14301. };
  14302. Mesh.prototype.registerBeforeRender = function (func) {
  14303. this._onBeforeRenderCallbacks.push(func);
  14304. };
  14305. Mesh.prototype.unregisterBeforeRender = function (func) {
  14306. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14307. if (index > -1) {
  14308. this._onBeforeRenderCallbacks.splice(index, 1);
  14309. }
  14310. };
  14311. Mesh.prototype.registerAfterRender = function (func) {
  14312. this._onAfterRenderCallbacks.push(func);
  14313. };
  14314. Mesh.prototype.unregisterAfterRender = function (func) {
  14315. var index = this._onAfterRenderCallbacks.indexOf(func);
  14316. if (index > -1) {
  14317. this._onAfterRenderCallbacks.splice(index, 1);
  14318. }
  14319. };
  14320. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14321. var scene = this.getScene();
  14322. this._batchCache.mustReturn = false;
  14323. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14324. this._batchCache.visibleInstances[subMeshId] = null;
  14325. if (this._visibleInstances) {
  14326. var currentRenderId = scene.getRenderId();
  14327. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14328. var selfRenderId = this._renderId;
  14329. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14330. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14331. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14332. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14333. }
  14334. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14335. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14336. this._batchCache.mustReturn = true;
  14337. return this._batchCache;
  14338. }
  14339. if (currentRenderId !== selfRenderId) {
  14340. this._batchCache.renderSelf[subMeshId] = false;
  14341. }
  14342. }
  14343. this._renderIdForInstances[subMeshId] = currentRenderId;
  14344. }
  14345. return this._batchCache;
  14346. };
  14347. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14348. var visibleInstances = batch.visibleInstances[subMesh._id];
  14349. var matricesCount = visibleInstances.length + 1;
  14350. var bufferSize = matricesCount * 16 * 4;
  14351. while (this._instancesBufferSize < bufferSize) {
  14352. this._instancesBufferSize *= 2;
  14353. }
  14354. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14355. if (this._worldMatricesInstancesBuffer) {
  14356. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14357. }
  14358. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14359. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14360. }
  14361. var offset = 0;
  14362. var instancesCount = 0;
  14363. var world = this.getWorldMatrix();
  14364. if (batch.renderSelf[subMesh._id]) {
  14365. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14366. offset += 16;
  14367. instancesCount++;
  14368. }
  14369. if (visibleInstances) {
  14370. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14371. var instance = visibleInstances[instanceIndex];
  14372. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14373. offset += 16;
  14374. instancesCount++;
  14375. }
  14376. }
  14377. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14378. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14379. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14380. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14381. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14382. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14383. this._draw(subMesh, fillMode, instancesCount);
  14384. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14385. };
  14386. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14387. var scene = this.getScene();
  14388. var engine = scene.getEngine();
  14389. if (hardwareInstancedRendering) {
  14390. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14391. }
  14392. else {
  14393. if (batch.renderSelf[subMesh._id]) {
  14394. // Draw
  14395. if (onBeforeDraw) {
  14396. onBeforeDraw(false, this.getWorldMatrix());
  14397. }
  14398. this._draw(subMesh, fillMode);
  14399. }
  14400. if (batch.visibleInstances[subMesh._id]) {
  14401. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14402. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14403. // World
  14404. var world = instance.getWorldMatrix();
  14405. if (onBeforeDraw) {
  14406. onBeforeDraw(true, world);
  14407. }
  14408. // Draw
  14409. this._draw(subMesh, fillMode);
  14410. }
  14411. }
  14412. }
  14413. };
  14414. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14415. var scene = this.getScene();
  14416. // Managing instances
  14417. var batch = this._getInstancesRenderList(subMesh._id);
  14418. if (batch.mustReturn) {
  14419. return;
  14420. }
  14421. // Checking geometry state
  14422. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14423. return;
  14424. }
  14425. var callbackIndex;
  14426. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14427. this._onBeforeRenderCallbacks[callbackIndex](this);
  14428. }
  14429. var engine = scene.getEngine();
  14430. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14431. // Material
  14432. var effectiveMaterial = subMesh.getMaterial();
  14433. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14434. return;
  14435. }
  14436. // Outline - step 1
  14437. var savedDepthWrite = engine.getDepthWrite();
  14438. if (this.renderOutline) {
  14439. engine.setDepthWrite(false);
  14440. scene.getOutlineRenderer().render(subMesh, batch);
  14441. engine.setDepthWrite(savedDepthWrite);
  14442. }
  14443. effectiveMaterial._preBind();
  14444. var effect = effectiveMaterial.getEffect();
  14445. // Bind
  14446. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14447. this._bind(subMesh, effect, fillMode);
  14448. var world = this.getWorldMatrix();
  14449. effectiveMaterial.bind(world, this);
  14450. // Alpha mode
  14451. if (enableAlphaMode) {
  14452. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14453. }
  14454. // Draw
  14455. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14456. if (isInstance) {
  14457. effectiveMaterial.bindOnlyWorldMatrix(world);
  14458. }
  14459. });
  14460. // Unbind
  14461. effectiveMaterial.unbind();
  14462. // Outline - step 2
  14463. if (this.renderOutline && savedDepthWrite) {
  14464. engine.setDepthWrite(true);
  14465. engine.setColorWrite(false);
  14466. scene.getOutlineRenderer().render(subMesh, batch);
  14467. engine.setColorWrite(true);
  14468. }
  14469. // Overlay
  14470. if (this.renderOverlay) {
  14471. var currentMode = engine.getAlphaMode();
  14472. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14473. scene.getOutlineRenderer().render(subMesh, batch, true);
  14474. engine.setAlphaMode(currentMode);
  14475. }
  14476. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14477. this._onAfterRenderCallbacks[callbackIndex](this);
  14478. }
  14479. };
  14480. Mesh.prototype.getEmittedParticleSystems = function () {
  14481. var results = new Array();
  14482. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14483. var particleSystem = this.getScene().particleSystems[index];
  14484. if (particleSystem.emitter === this) {
  14485. results.push(particleSystem);
  14486. }
  14487. }
  14488. return results;
  14489. };
  14490. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14491. var results = new Array();
  14492. var descendants = this.getDescendants();
  14493. descendants.push(this);
  14494. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14495. var particleSystem = this.getScene().particleSystems[index];
  14496. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14497. results.push(particleSystem);
  14498. }
  14499. }
  14500. return results;
  14501. };
  14502. Mesh.prototype.getChildren = function () {
  14503. var results = [];
  14504. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14505. var mesh = this.getScene().meshes[index];
  14506. if (mesh.parent === this) {
  14507. results.push(mesh);
  14508. }
  14509. }
  14510. return results;
  14511. };
  14512. Mesh.prototype._checkDelayState = function () {
  14513. var _this = this;
  14514. var that = this;
  14515. var scene = this.getScene();
  14516. if (this._geometry) {
  14517. this._geometry.load(scene);
  14518. }
  14519. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14520. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14521. scene._addPendingData(that);
  14522. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14523. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14524. if (data instanceof ArrayBuffer) {
  14525. _this._delayLoadingFunction(data, _this);
  14526. }
  14527. else {
  14528. _this._delayLoadingFunction(JSON.parse(data), _this);
  14529. }
  14530. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14531. scene._removePendingData(_this);
  14532. }, function () { }, scene.database, getBinaryData);
  14533. }
  14534. };
  14535. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14536. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14537. return false;
  14538. }
  14539. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14540. return false;
  14541. }
  14542. this._checkDelayState();
  14543. return true;
  14544. };
  14545. Mesh.prototype.setMaterialByID = function (id) {
  14546. var materials = this.getScene().materials;
  14547. var index;
  14548. for (index = 0; index < materials.length; index++) {
  14549. if (materials[index].id === id) {
  14550. this.material = materials[index];
  14551. return;
  14552. }
  14553. }
  14554. // Multi
  14555. var multiMaterials = this.getScene().multiMaterials;
  14556. for (index = 0; index < multiMaterials.length; index++) {
  14557. if (multiMaterials[index].id === id) {
  14558. this.material = multiMaterials[index];
  14559. return;
  14560. }
  14561. }
  14562. };
  14563. Mesh.prototype.getAnimatables = function () {
  14564. var results = [];
  14565. if (this.material) {
  14566. results.push(this.material);
  14567. }
  14568. if (this.skeleton) {
  14569. results.push(this.skeleton);
  14570. }
  14571. return results;
  14572. };
  14573. // Geometry
  14574. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14575. // Position
  14576. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14577. return;
  14578. }
  14579. this._resetPointsArrayCache();
  14580. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14581. var temp = [];
  14582. var index;
  14583. for (index = 0; index < data.length; index += 3) {
  14584. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14585. }
  14586. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14587. // Normals
  14588. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14589. return;
  14590. }
  14591. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14592. temp = [];
  14593. for (index = 0; index < data.length; index += 3) {
  14594. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14595. }
  14596. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14597. // flip faces?
  14598. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14599. this.flipFaces();
  14600. }
  14601. };
  14602. // Will apply current transform to mesh and reset world matrix
  14603. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14604. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14605. this.scaling.copyFromFloats(1, 1, 1);
  14606. this.position.copyFromFloats(0, 0, 0);
  14607. this.rotation.copyFromFloats(0, 0, 0);
  14608. //only if quaternion is already set
  14609. if (this.rotationQuaternion) {
  14610. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14611. }
  14612. this._worldMatrix = BABYLON.Matrix.Identity();
  14613. };
  14614. // Cache
  14615. Mesh.prototype._resetPointsArrayCache = function () {
  14616. this._positions = null;
  14617. };
  14618. Mesh.prototype._generatePointsArray = function () {
  14619. if (this._positions)
  14620. return true;
  14621. this._positions = [];
  14622. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14623. if (!data) {
  14624. return false;
  14625. }
  14626. for (var index = 0; index < data.length; index += 3) {
  14627. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14628. }
  14629. return true;
  14630. };
  14631. // Clone
  14632. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14633. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14634. };
  14635. // Dispose
  14636. Mesh.prototype.dispose = function (doNotRecurse) {
  14637. if (this._geometry) {
  14638. this._geometry.releaseForMesh(this, true);
  14639. }
  14640. // Instances
  14641. if (this._worldMatricesInstancesBuffer) {
  14642. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14643. this._worldMatricesInstancesBuffer = null;
  14644. }
  14645. while (this.instances.length) {
  14646. this.instances[0].dispose();
  14647. }
  14648. _super.prototype.dispose.call(this, doNotRecurse);
  14649. };
  14650. // Geometric tools
  14651. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14652. var _this = this;
  14653. var scene = this.getScene();
  14654. var onload = function (img) {
  14655. // Getting height map data
  14656. var canvas = document.createElement("canvas");
  14657. var context = canvas.getContext("2d");
  14658. var heightMapWidth = img.width;
  14659. var heightMapHeight = img.height;
  14660. canvas.width = heightMapWidth;
  14661. canvas.height = heightMapHeight;
  14662. context.drawImage(img, 0, 0);
  14663. // Create VertexData from map data
  14664. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14665. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14666. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14667. //execute success callback, if set
  14668. if (onSuccess) {
  14669. onSuccess(_this);
  14670. }
  14671. };
  14672. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14673. };
  14674. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14675. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14676. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14677. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14678. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14679. return;
  14680. }
  14681. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14682. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14683. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14684. var position = BABYLON.Vector3.Zero();
  14685. var normal = BABYLON.Vector3.Zero();
  14686. var uv = BABYLON.Vector2.Zero();
  14687. for (var index = 0; index < positions.length; index += 3) {
  14688. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14689. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14690. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14691. // Compute height
  14692. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14693. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14694. var pos = (u + v * heightMapWidth) * 4;
  14695. var r = buffer[pos] / 255.0;
  14696. var g = buffer[pos + 1] / 255.0;
  14697. var b = buffer[pos + 2] / 255.0;
  14698. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14699. normal.normalize();
  14700. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14701. position = position.add(normal);
  14702. position.toArray(positions, index);
  14703. }
  14704. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14705. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14706. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14707. };
  14708. Mesh.prototype.convertToFlatShadedMesh = function () {
  14709. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14710. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14711. var kinds = this.getVerticesDataKinds();
  14712. var vbs = [];
  14713. var data = [];
  14714. var newdata = [];
  14715. var updatableNormals = false;
  14716. var kindIndex;
  14717. var kind;
  14718. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14719. kind = kinds[kindIndex];
  14720. var vertexBuffer = this.getVertexBuffer(kind);
  14721. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14722. updatableNormals = vertexBuffer.isUpdatable();
  14723. kinds.splice(kindIndex, 1);
  14724. kindIndex--;
  14725. continue;
  14726. }
  14727. vbs[kind] = vertexBuffer;
  14728. data[kind] = vbs[kind].getData();
  14729. newdata[kind] = [];
  14730. }
  14731. // Save previous submeshes
  14732. var previousSubmeshes = this.subMeshes.slice(0);
  14733. var indices = this.getIndices();
  14734. var totalIndices = this.getTotalIndices();
  14735. // Generating unique vertices per face
  14736. var index;
  14737. for (index = 0; index < totalIndices; index++) {
  14738. var vertexIndex = indices[index];
  14739. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14740. kind = kinds[kindIndex];
  14741. var stride = vbs[kind].getStrideSize();
  14742. for (var offset = 0; offset < stride; offset++) {
  14743. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14744. }
  14745. }
  14746. }
  14747. // Updating faces & normal
  14748. var normals = [];
  14749. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14750. for (index = 0; index < totalIndices; index += 3) {
  14751. indices[index] = index;
  14752. indices[index + 1] = index + 1;
  14753. indices[index + 2] = index + 2;
  14754. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14755. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14756. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14757. var p1p2 = p1.subtract(p2);
  14758. var p3p2 = p3.subtract(p2);
  14759. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14760. // Store same normals for every vertex
  14761. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14762. normals.push(normal.x);
  14763. normals.push(normal.y);
  14764. normals.push(normal.z);
  14765. }
  14766. }
  14767. this.setIndices(indices);
  14768. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14769. // Updating vertex buffers
  14770. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14771. kind = kinds[kindIndex];
  14772. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14773. }
  14774. // Updating submeshes
  14775. this.releaseSubMeshes();
  14776. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14777. var previousOne = previousSubmeshes[submeshIndex];
  14778. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14779. }
  14780. this.synchronizeInstances();
  14781. };
  14782. // will inverse faces orientations, and invert normals too if specified
  14783. Mesh.prototype.flipFaces = function (flipNormals) {
  14784. if (flipNormals === void 0) { flipNormals = false; }
  14785. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14786. var i;
  14787. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14788. for (i = 0; i < vertex_data.normals.length; i++) {
  14789. vertex_data.normals[i] *= -1;
  14790. }
  14791. }
  14792. var temp;
  14793. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14794. // reassign indices
  14795. temp = vertex_data.indices[i + 1];
  14796. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14797. vertex_data.indices[i + 2] = temp;
  14798. }
  14799. vertex_data.applyToMesh(this);
  14800. };
  14801. // Instances
  14802. Mesh.prototype.createInstance = function (name) {
  14803. return new BABYLON.InstancedMesh(name, this);
  14804. };
  14805. Mesh.prototype.synchronizeInstances = function () {
  14806. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14807. var instance = this.instances[instanceIndex];
  14808. instance._syncSubMeshes();
  14809. }
  14810. };
  14811. /**
  14812. * Simplify the mesh according to the given array of settings.
  14813. * Function will return immediately and will simplify async.
  14814. * @param settings a collection of simplification settings.
  14815. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14816. * @param type the type of simplification to run.
  14817. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14818. */
  14819. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14820. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14821. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14822. this.getScene().simplificationQueue.addTask({
  14823. settings: settings,
  14824. parallelProcessing: parallelProcessing,
  14825. mesh: this,
  14826. simplificationType: simplificationType,
  14827. successCallback: successCallback
  14828. });
  14829. };
  14830. /**
  14831. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14832. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14833. * This should be used together with the simplification to avoid disappearing triangles.
  14834. * @param successCallback an optional success callback to be called after the optimization finished.
  14835. */
  14836. Mesh.prototype.optimizeIndices = function (successCallback) {
  14837. var _this = this;
  14838. var indices = this.getIndices();
  14839. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14840. var vectorPositions = [];
  14841. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14842. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14843. }
  14844. var dupes = [];
  14845. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14846. var realPos = vectorPositions.length - 1 - iteration;
  14847. var testedPosition = vectorPositions[realPos];
  14848. for (var j = 0; j < realPos; ++j) {
  14849. var againstPosition = vectorPositions[j];
  14850. if (testedPosition.equals(againstPosition)) {
  14851. dupes[realPos] = j;
  14852. break;
  14853. }
  14854. }
  14855. }, function () {
  14856. for (var i = 0; i < indices.length; ++i) {
  14857. indices[i] = dupes[indices[i]] || indices[i];
  14858. }
  14859. //indices are now reordered
  14860. var originalSubMeshes = _this.subMeshes.slice(0);
  14861. _this.setIndices(indices);
  14862. _this.subMeshes = originalSubMeshes;
  14863. if (successCallback) {
  14864. successCallback(_this);
  14865. }
  14866. });
  14867. };
  14868. // Statics
  14869. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14870. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14871. pathArray: pathArray,
  14872. closeArray: closeArray,
  14873. closePath: closePath,
  14874. offset: offset,
  14875. updatable: updatable,
  14876. sideOrientation: sideOrientation,
  14877. instance: instance
  14878. }, scene);
  14879. };
  14880. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14881. var options = {
  14882. radius: radius,
  14883. tessellation: tessellation,
  14884. sideOrientation: sideOrientation,
  14885. updatable: updatable
  14886. };
  14887. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14888. };
  14889. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14890. var options = {
  14891. size: size,
  14892. sideOrientation: sideOrientation,
  14893. updatable: updatable
  14894. };
  14895. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14896. };
  14897. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14898. var options = {
  14899. segments: segments,
  14900. diameterX: diameter,
  14901. diameterY: diameter,
  14902. diameterZ: diameter,
  14903. sideOrientation: sideOrientation,
  14904. updatable: updatable
  14905. };
  14906. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14907. };
  14908. // Cylinder and cone
  14909. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14910. var options = {
  14911. height: height,
  14912. diameterTop: diameterTop,
  14913. diameterBottom: diameterBottom,
  14914. tessellation: tessellation,
  14915. subdivisions: subdivisions,
  14916. sideOrientation: sideOrientation,
  14917. updatable: updatable
  14918. };
  14919. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14920. };
  14921. // Torus (Code from SharpDX.org)
  14922. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14923. var options = {
  14924. diameter: diameter,
  14925. thickness: thickness,
  14926. tessellation: tessellation,
  14927. sideOrientation: sideOrientation,
  14928. updatable: updatable
  14929. };
  14930. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14931. };
  14932. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14933. var options = {
  14934. radius: radius,
  14935. tube: tube,
  14936. radialSegments: radialSegments,
  14937. tubularSegments: tubularSegments,
  14938. p: p,
  14939. q: q,
  14940. sideOrientation: sideOrientation,
  14941. updatable: updatable
  14942. };
  14943. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14944. };
  14945. // Lines
  14946. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14947. var options = {
  14948. points: points,
  14949. updatable: updatable,
  14950. instance: instance
  14951. };
  14952. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14953. };
  14954. // Dashed Lines
  14955. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14956. var options = {
  14957. points: points,
  14958. dashSize: dashSize,
  14959. gapSize: gapSize,
  14960. dashNb: dashNb,
  14961. updatable: updatable
  14962. };
  14963. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14964. };
  14965. // Extrusion
  14966. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14967. var options = {
  14968. shape: shape,
  14969. path: path,
  14970. scale: scale,
  14971. rotation: rotation,
  14972. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14973. sideOrientation: sideOrientation,
  14974. instance: instance,
  14975. updatable: updatable
  14976. };
  14977. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  14978. };
  14979. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  14980. var options = {
  14981. shape: shape,
  14982. path: path,
  14983. scaleFunction: scaleFunction,
  14984. rotationFunction: rotationFunction,
  14985. ribbonCloseArray: ribbonCloseArray,
  14986. ribbonClosePath: ribbonClosePath,
  14987. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14988. sideOrientation: sideOrientation,
  14989. instance: instance,
  14990. updatable: updatable
  14991. };
  14992. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  14993. };
  14994. // Lathe
  14995. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  14996. var options = {
  14997. shape: shape,
  14998. radius: radius,
  14999. tesselation: tessellation,
  15000. sideOrientation: sideOrientation,
  15001. updatable: updatable
  15002. };
  15003. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15004. };
  15005. // Plane & ground
  15006. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15007. var options = {
  15008. size: size,
  15009. width: size,
  15010. height: size,
  15011. sideOrientation: sideOrientation,
  15012. updatable: updatable
  15013. };
  15014. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15015. };
  15016. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15017. var options = {
  15018. width: width,
  15019. height: height,
  15020. subdivisions: subdivisions,
  15021. updatable: updatable
  15022. };
  15023. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15024. };
  15025. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15026. var options = {
  15027. xmin: xmin,
  15028. zmin: zmin,
  15029. xmax: xmax,
  15030. zmax: zmax,
  15031. subdivisions: subdivisions,
  15032. precision: precision,
  15033. updatable: updatable
  15034. };
  15035. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15036. };
  15037. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15038. var options = {
  15039. width: width,
  15040. height: height,
  15041. subdivisions: subdivisions,
  15042. minHeight: minHeight,
  15043. maxHeight: maxHeight,
  15044. updatable: updatable,
  15045. onReady: onReady
  15046. };
  15047. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15048. };
  15049. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15050. var options = {
  15051. path: path,
  15052. radius: radius,
  15053. tessellation: tessellation,
  15054. radiusFunction: radiusFunction,
  15055. arc: 1,
  15056. cap: cap,
  15057. updatable: updatable,
  15058. sideOrientation: sideOrientation,
  15059. instance: instance
  15060. };
  15061. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15062. };
  15063. Mesh.CreatePolyhedron = function (name, options, scene) {
  15064. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15065. };
  15066. Mesh.CreateIcoSphere = function (name, options, scene) {
  15067. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15068. };
  15069. // Decals
  15070. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15071. var options = {
  15072. position: position,
  15073. normal: normal,
  15074. size: size,
  15075. angle: angle
  15076. };
  15077. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15078. };
  15079. // Skeletons
  15080. /**
  15081. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15082. */
  15083. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15084. var source;
  15085. if (!this._sourcePositions) {
  15086. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15087. this._sourcePositions = new Float32Array(source);
  15088. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15089. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15090. }
  15091. }
  15092. return this._sourcePositions;
  15093. };
  15094. /**
  15095. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15096. */
  15097. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15098. var source;
  15099. if (!this._sourceNormals) {
  15100. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15101. this._sourceNormals = new Float32Array(source);
  15102. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15103. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15104. }
  15105. }
  15106. return this._sourceNormals;
  15107. };
  15108. /**
  15109. * Update the vertex buffers by applying transformation from the bones
  15110. * @param {skeleton} skeleton to apply
  15111. */
  15112. Mesh.prototype.applySkeleton = function (skeleton) {
  15113. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15114. return this;
  15115. }
  15116. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15117. return this;
  15118. }
  15119. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15120. return this;
  15121. }
  15122. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15123. return this;
  15124. }
  15125. if (!this._sourcePositions) {
  15126. this.setPositionsForCPUSkinning();
  15127. }
  15128. if (!this._sourceNormals) {
  15129. this.setNormalsForCPUSkinning();
  15130. }
  15131. // positionsData checks for not being Float32Array will only pass at most once
  15132. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15133. if (!(positionsData instanceof Float32Array)) {
  15134. positionsData = new Float32Array(positionsData);
  15135. }
  15136. // normalsData checks for not being Float32Array will only pass at most once
  15137. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15138. if (!(normalsData instanceof Float32Array)) {
  15139. normalsData = new Float32Array(normalsData);
  15140. }
  15141. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15142. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15143. var needExtras = this.numBoneInfluencers > 4;
  15144. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15145. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15146. var skeletonMatrices = skeleton.getTransformMatrices();
  15147. var tempVector3 = BABYLON.Vector3.Zero();
  15148. var finalMatrix = new BABYLON.Matrix();
  15149. var tempMatrix = new BABYLON.Matrix();
  15150. var matWeightIdx = 0;
  15151. var inf;
  15152. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15153. for (inf = 0; inf < 4; inf++) {
  15154. var weight = matricesWeightsData[matWeightIdx + inf];
  15155. if (weight > 0) {
  15156. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15157. finalMatrix.addToSelf(tempMatrix);
  15158. }
  15159. else
  15160. break;
  15161. }
  15162. if (needExtras) {
  15163. for (inf = 0; inf < 4; inf++) {
  15164. var weight = matricesWeightsExtraData[matWeightIdx + inf];
  15165. if (weight > 0) {
  15166. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15167. finalMatrix.addToSelf(tempMatrix);
  15168. }
  15169. else
  15170. break;
  15171. }
  15172. }
  15173. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15174. tempVector3.toArray(positionsData, index);
  15175. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15176. tempVector3.toArray(normalsData, index);
  15177. finalMatrix.reset();
  15178. }
  15179. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15180. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15181. return this;
  15182. };
  15183. // Tools
  15184. Mesh.MinMax = function (meshes) {
  15185. var minVector = null;
  15186. var maxVector = null;
  15187. for (var i in meshes) {
  15188. var mesh = meshes[i];
  15189. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15190. if (!minVector) {
  15191. minVector = boundingBox.minimumWorld;
  15192. maxVector = boundingBox.maximumWorld;
  15193. continue;
  15194. }
  15195. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15196. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15197. }
  15198. return {
  15199. min: minVector,
  15200. max: maxVector
  15201. };
  15202. };
  15203. Mesh.Center = function (meshesOrMinMaxVector) {
  15204. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15205. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15206. };
  15207. /**
  15208. * Merge the array of meshes into a single mesh for performance reasons.
  15209. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15210. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15211. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15212. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15213. */
  15214. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15215. if (disposeSource === void 0) { disposeSource = true; }
  15216. var index;
  15217. if (!allow32BitsIndices) {
  15218. var totalVertices = 0;
  15219. // Counting vertices
  15220. for (index = 0; index < meshes.length; index++) {
  15221. if (meshes[index]) {
  15222. totalVertices += meshes[index].getTotalVertices();
  15223. if (totalVertices > 65536) {
  15224. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15225. return null;
  15226. }
  15227. }
  15228. }
  15229. }
  15230. // Merge
  15231. var vertexData;
  15232. var otherVertexData;
  15233. var source;
  15234. for (index = 0; index < meshes.length; index++) {
  15235. if (meshes[index]) {
  15236. meshes[index].computeWorldMatrix(true);
  15237. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15238. otherVertexData.transform(meshes[index].getWorldMatrix());
  15239. if (vertexData) {
  15240. vertexData.merge(otherVertexData);
  15241. }
  15242. else {
  15243. vertexData = otherVertexData;
  15244. source = meshes[index];
  15245. }
  15246. }
  15247. }
  15248. if (!meshSubclass) {
  15249. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15250. }
  15251. vertexData.applyToMesh(meshSubclass);
  15252. // Setting properties
  15253. meshSubclass.material = source.material;
  15254. meshSubclass.checkCollisions = source.checkCollisions;
  15255. // Cleaning
  15256. if (disposeSource) {
  15257. for (index = 0; index < meshes.length; index++) {
  15258. if (meshes[index]) {
  15259. meshes[index].dispose();
  15260. }
  15261. }
  15262. }
  15263. return meshSubclass;
  15264. };
  15265. // Consts
  15266. Mesh._FRONTSIDE = 0;
  15267. Mesh._BACKSIDE = 1;
  15268. Mesh._DOUBLESIDE = 2;
  15269. Mesh._DEFAULTSIDE = 0;
  15270. Mesh._NO_CAP = 0;
  15271. Mesh._CAP_START = 1;
  15272. Mesh._CAP_END = 2;
  15273. Mesh._CAP_ALL = 3;
  15274. return Mesh;
  15275. })(BABYLON.AbstractMesh);
  15276. BABYLON.Mesh = Mesh;
  15277. })(BABYLON || (BABYLON = {}));
  15278. var BABYLON;
  15279. (function (BABYLON) {
  15280. var SubMesh = (function () {
  15281. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15282. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15283. this.materialIndex = materialIndex;
  15284. this.verticesStart = verticesStart;
  15285. this.verticesCount = verticesCount;
  15286. this.indexStart = indexStart;
  15287. this.indexCount = indexCount;
  15288. this._renderId = 0;
  15289. this._mesh = mesh;
  15290. this._renderingMesh = renderingMesh || mesh;
  15291. mesh.subMeshes.push(this);
  15292. this._trianglePlanes = [];
  15293. this._id = mesh.subMeshes.length - 1;
  15294. if (createBoundingBox) {
  15295. this.refreshBoundingInfo();
  15296. mesh.computeWorldMatrix(true);
  15297. }
  15298. }
  15299. SubMesh.prototype.getBoundingInfo = function () {
  15300. return this._boundingInfo;
  15301. };
  15302. SubMesh.prototype.getMesh = function () {
  15303. return this._mesh;
  15304. };
  15305. SubMesh.prototype.getRenderingMesh = function () {
  15306. return this._renderingMesh;
  15307. };
  15308. SubMesh.prototype.getMaterial = function () {
  15309. var rootMaterial = this._renderingMesh.material;
  15310. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15311. var multiMaterial = rootMaterial;
  15312. return multiMaterial.getSubMaterial(this.materialIndex);
  15313. }
  15314. if (!rootMaterial) {
  15315. return this._mesh.getScene().defaultMaterial;
  15316. }
  15317. return rootMaterial;
  15318. };
  15319. // Methods
  15320. SubMesh.prototype.refreshBoundingInfo = function () {
  15321. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15322. if (!data) {
  15323. this._boundingInfo = this._mesh._boundingInfo;
  15324. return;
  15325. }
  15326. var indices = this._renderingMesh.getIndices();
  15327. var extend;
  15328. //is this the only submesh?
  15329. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15330. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15331. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15332. }
  15333. else {
  15334. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15335. }
  15336. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15337. };
  15338. SubMesh.prototype._checkCollision = function (collider) {
  15339. return this._boundingInfo._checkCollision(collider);
  15340. };
  15341. SubMesh.prototype.updateBoundingInfo = function (world) {
  15342. if (!this._boundingInfo) {
  15343. this.refreshBoundingInfo();
  15344. }
  15345. this._boundingInfo._update(world);
  15346. };
  15347. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15348. return this._boundingInfo.isInFrustum(frustumPlanes);
  15349. };
  15350. SubMesh.prototype.render = function (enableAlphaMode) {
  15351. this._renderingMesh.render(this, enableAlphaMode);
  15352. };
  15353. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15354. if (!this._linesIndexBuffer) {
  15355. var linesIndices = [];
  15356. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15357. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15358. }
  15359. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15360. this.linesIndexCount = linesIndices.length;
  15361. }
  15362. return this._linesIndexBuffer;
  15363. };
  15364. SubMesh.prototype.canIntersects = function (ray) {
  15365. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15366. };
  15367. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15368. var intersectInfo = null;
  15369. // Triangles test
  15370. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15371. var p0 = positions[indices[index]];
  15372. var p1 = positions[indices[index + 1]];
  15373. var p2 = positions[indices[index + 2]];
  15374. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15375. if (currentIntersectInfo) {
  15376. if (currentIntersectInfo.distance < 0) {
  15377. continue;
  15378. }
  15379. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15380. intersectInfo = currentIntersectInfo;
  15381. intersectInfo.faceId = index / 3;
  15382. if (fastCheck) {
  15383. break;
  15384. }
  15385. }
  15386. }
  15387. }
  15388. return intersectInfo;
  15389. };
  15390. // Clone
  15391. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15392. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15393. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15394. return result;
  15395. };
  15396. // Dispose
  15397. SubMesh.prototype.dispose = function () {
  15398. if (this._linesIndexBuffer) {
  15399. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15400. this._linesIndexBuffer = null;
  15401. }
  15402. // Remove from mesh
  15403. var index = this._mesh.subMeshes.indexOf(this);
  15404. this._mesh.subMeshes.splice(index, 1);
  15405. };
  15406. // Statics
  15407. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15408. var minVertexIndex = Number.MAX_VALUE;
  15409. var maxVertexIndex = -Number.MAX_VALUE;
  15410. renderingMesh = renderingMesh || mesh;
  15411. var indices = renderingMesh.getIndices();
  15412. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15413. var vertexIndex = indices[index];
  15414. if (vertexIndex < minVertexIndex)
  15415. minVertexIndex = vertexIndex;
  15416. if (vertexIndex > maxVertexIndex)
  15417. maxVertexIndex = vertexIndex;
  15418. }
  15419. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15420. };
  15421. return SubMesh;
  15422. })();
  15423. BABYLON.SubMesh = SubMesh;
  15424. })(BABYLON || (BABYLON = {}));
  15425. var BABYLON;
  15426. (function (BABYLON) {
  15427. var MeshBuilder = (function () {
  15428. function MeshBuilder() {
  15429. }
  15430. MeshBuilder.CreateBox = function (name, options, scene) {
  15431. var box = new BABYLON.Mesh(name, scene);
  15432. var vertexData = BABYLON.VertexData.CreateBox(options);
  15433. vertexData.applyToMesh(box, options.updatable);
  15434. return box;
  15435. };
  15436. MeshBuilder.CreateSphere = function (name, options, scene) {
  15437. var sphere = new BABYLON.Mesh(name, scene);
  15438. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15439. vertexData.applyToMesh(sphere, options.updatable);
  15440. return sphere;
  15441. };
  15442. MeshBuilder.CreateDisc = function (name, options, scene) {
  15443. var disc = new BABYLON.Mesh(name, scene);
  15444. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15445. vertexData.applyToMesh(disc, options.updatable);
  15446. return disc;
  15447. };
  15448. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15449. var sphere = new BABYLON.Mesh(name, scene);
  15450. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15451. vertexData.applyToMesh(sphere, options.updatable);
  15452. return sphere;
  15453. };
  15454. ;
  15455. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15456. var pathArray = options.pathArray;
  15457. var closeArray = options.closeArray;
  15458. var closePath = options.closePath;
  15459. var offset = options.offset;
  15460. var sideOrientation = options.sideOrientation;
  15461. var instance = options.instance;
  15462. var updatable = options.updatable;
  15463. if (instance) {
  15464. // positionFunction : ribbon case
  15465. // only pathArray and sideOrientation parameters are taken into account for positions update
  15466. var positionFunction = function (positions) {
  15467. var minlg = pathArray[0].length;
  15468. var i = 0;
  15469. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15470. for (var si = 1; si <= ns; si++) {
  15471. for (var p = 0; p < pathArray.length; p++) {
  15472. var path = pathArray[p];
  15473. var l = path.length;
  15474. minlg = (minlg < l) ? minlg : l;
  15475. var j = 0;
  15476. while (j < minlg) {
  15477. positions[i] = path[j].x;
  15478. positions[i + 1] = path[j].y;
  15479. positions[i + 2] = path[j].z;
  15480. j++;
  15481. i += 3;
  15482. }
  15483. if (instance._closePath) {
  15484. positions[i] = path[0].x;
  15485. positions[i + 1] = path[0].y;
  15486. positions[i + 2] = path[0].z;
  15487. i += 3;
  15488. }
  15489. }
  15490. }
  15491. };
  15492. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15493. positionFunction(positions);
  15494. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15495. if (!(instance.areNormalsFrozen)) {
  15496. var indices = instance.getIndices();
  15497. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15498. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15499. if (instance._closePath) {
  15500. var indexFirst = 0;
  15501. var indexLast = 0;
  15502. for (var p = 0; p < pathArray.length; p++) {
  15503. indexFirst = instance._idx[p] * 3;
  15504. if (p + 1 < pathArray.length) {
  15505. indexLast = (instance._idx[p + 1] - 1) * 3;
  15506. }
  15507. else {
  15508. indexLast = normals.length - 3;
  15509. }
  15510. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15511. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15512. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15513. normals[indexLast] = normals[indexFirst];
  15514. normals[indexLast + 1] = normals[indexFirst + 1];
  15515. normals[indexLast + 2] = normals[indexFirst + 2];
  15516. }
  15517. }
  15518. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15519. }
  15520. return instance;
  15521. }
  15522. else {
  15523. var ribbon = new BABYLON.Mesh(name, scene);
  15524. ribbon.sideOrientation = sideOrientation;
  15525. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15526. if (closePath) {
  15527. ribbon._idx = vertexData._idx;
  15528. }
  15529. ribbon._closePath = closePath;
  15530. ribbon._closeArray = closeArray;
  15531. vertexData.applyToMesh(ribbon, updatable);
  15532. return ribbon;
  15533. }
  15534. };
  15535. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15536. var cylinder = new BABYLON.Mesh(name, scene);
  15537. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15538. vertexData.applyToMesh(cylinder, options.updatable);
  15539. return cylinder;
  15540. };
  15541. MeshBuilder.CreateTorus = function (name, options, scene) {
  15542. var torus = new BABYLON.Mesh(name, scene);
  15543. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15544. vertexData.applyToMesh(torus, options.updatable);
  15545. return torus;
  15546. };
  15547. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15548. var torusKnot = new BABYLON.Mesh(name, scene);
  15549. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15550. vertexData.applyToMesh(torusKnot, options.updatable);
  15551. return torusKnot;
  15552. };
  15553. MeshBuilder.CreateLines = function (name, options, scene) {
  15554. var instance = options.instance;
  15555. var points = options.points;
  15556. if (instance) {
  15557. var positionFunction = function (positions) {
  15558. var i = 0;
  15559. for (var p = 0; p < points.length; p++) {
  15560. positions[i] = points[p].x;
  15561. positions[i + 1] = points[p].y;
  15562. positions[i + 2] = points[p].z;
  15563. i += 3;
  15564. }
  15565. };
  15566. instance.updateMeshPositions(positionFunction, false);
  15567. return instance;
  15568. }
  15569. // lines creation
  15570. var lines = new BABYLON.LinesMesh(name, scene);
  15571. var vertexData = BABYLON.VertexData.CreateLines(options);
  15572. vertexData.applyToMesh(lines, options.updatable);
  15573. return lines;
  15574. };
  15575. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15576. var points = options.points;
  15577. var instance = options.instance;
  15578. var gapSize = options.gapSize;
  15579. var dashNb = options.dashNb;
  15580. var dashSize = options.dashSize;
  15581. if (instance) {
  15582. var positionFunction = function (positions) {
  15583. var curvect = BABYLON.Vector3.Zero();
  15584. var nbSeg = positions.length / 6;
  15585. var lg = 0;
  15586. var nb = 0;
  15587. var shft = 0;
  15588. var dashshft = 0;
  15589. var curshft = 0;
  15590. var p = 0;
  15591. var i = 0;
  15592. var j = 0;
  15593. for (i = 0; i < points.length - 1; i++) {
  15594. points[i + 1].subtractToRef(points[i], curvect);
  15595. lg += curvect.length();
  15596. }
  15597. shft = lg / nbSeg;
  15598. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15599. for (i = 0; i < points.length - 1; i++) {
  15600. points[i + 1].subtractToRef(points[i], curvect);
  15601. nb = Math.floor(curvect.length() / shft);
  15602. curvect.normalize();
  15603. j = 0;
  15604. while (j < nb && p < positions.length) {
  15605. curshft = shft * j;
  15606. positions[p] = points[i].x + curshft * curvect.x;
  15607. positions[p + 1] = points[i].y + curshft * curvect.y;
  15608. positions[p + 2] = points[i].z + curshft * curvect.z;
  15609. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15610. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15611. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15612. p += 6;
  15613. j++;
  15614. }
  15615. }
  15616. while (p < positions.length) {
  15617. positions[p] = points[i].x;
  15618. positions[p + 1] = points[i].y;
  15619. positions[p + 2] = points[i].z;
  15620. p += 3;
  15621. }
  15622. };
  15623. instance.updateMeshPositions(positionFunction, false);
  15624. return instance;
  15625. }
  15626. // dashed lines creation
  15627. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15628. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15629. vertexData.applyToMesh(dashedLines, options.updatable);
  15630. dashedLines.dashSize = dashSize;
  15631. dashedLines.gapSize = gapSize;
  15632. return dashedLines;
  15633. };
  15634. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15635. var path = options.path;
  15636. var shape = options.shape;
  15637. var scale = options.scale || 1;
  15638. var rotation = options.rotation || 0;
  15639. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15640. var updatable = options.updatable;
  15641. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15642. var instance = options.instance;
  15643. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15644. };
  15645. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15646. var path = options.path;
  15647. var shape = options.shape;
  15648. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15649. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15650. var ribbonCloseArray = options.ribbonCloseArray || false;
  15651. var ribbonClosePath = options.ribbonClosePath || false;
  15652. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15653. var updatable = options.updatable;
  15654. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15655. var instance = options.instance;
  15656. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15657. };
  15658. MeshBuilder.CreateLathe = function (name, options, scene) {
  15659. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15660. var closed = (options.closed === undefined) ? true : options.closed;
  15661. var shape = options.shape;
  15662. var radius = options.radius || 1;
  15663. var tessellation = options.tessellation || 64;
  15664. var updatable = options.updatable;
  15665. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15666. var pi2 = Math.PI * 2;
  15667. var shapeLathe = new Array();
  15668. // first rotatable point
  15669. var i = 0;
  15670. while (shape[i].x === 0) {
  15671. i++;
  15672. }
  15673. var pt = shape[i];
  15674. for (i = 0; i < shape.length; i++) {
  15675. shapeLathe.push(shape[i].subtract(pt));
  15676. }
  15677. // circle path
  15678. var step = pi2 / tessellation * arc;
  15679. var rotated;
  15680. var path = new Array();
  15681. ;
  15682. for (i = 0; i <= tessellation; i++) {
  15683. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15684. path.push(rotated);
  15685. }
  15686. if (closed) {
  15687. path.push(path[0]);
  15688. }
  15689. // extrusion
  15690. var scaleFunction = function () { return 1; };
  15691. var rotateFunction = function () { return 0; };
  15692. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15693. return lathe;
  15694. };
  15695. MeshBuilder.CreatePlane = function (name, options, scene) {
  15696. var plane = new BABYLON.Mesh(name, scene);
  15697. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15698. vertexData.applyToMesh(plane, options.updatable);
  15699. if (options.sourcePlane) {
  15700. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15701. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15702. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15703. plane.rotate(vectorProduct, product);
  15704. }
  15705. return plane;
  15706. };
  15707. MeshBuilder.CreateGround = function (name, options, scene) {
  15708. var ground = new BABYLON.GroundMesh(name, scene);
  15709. ground._setReady(false);
  15710. ground._subdivisions = options.subdivisions || 1;
  15711. var vertexData = BABYLON.VertexData.CreateGround(options);
  15712. vertexData.applyToMesh(ground, options.updatable);
  15713. ground._setReady(true);
  15714. return ground;
  15715. };
  15716. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15717. var tiledGround = new BABYLON.Mesh(name, scene);
  15718. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15719. vertexData.applyToMesh(tiledGround, options.updatable);
  15720. return tiledGround;
  15721. };
  15722. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15723. var width = options.width || 10;
  15724. var height = options.height || 10;
  15725. var subdivisions = options.subdivisions || 1;
  15726. var minHeight = options.minHeight;
  15727. var maxHeight = options.maxHeight || 10;
  15728. var updatable = options.updatable;
  15729. var onReady = options.onReady;
  15730. var ground = new BABYLON.GroundMesh(name, scene);
  15731. ground._subdivisions = subdivisions;
  15732. ground._setReady(false);
  15733. var onload = function (img) {
  15734. // Getting height map data
  15735. var canvas = document.createElement("canvas");
  15736. var context = canvas.getContext("2d");
  15737. var bufferWidth = img.width;
  15738. var bufferHeight = img.height;
  15739. canvas.width = bufferWidth;
  15740. canvas.height = bufferHeight;
  15741. context.drawImage(img, 0, 0);
  15742. // Create VertexData from map data
  15743. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15744. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15745. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15746. width: width, height: height,
  15747. subdivisions: subdivisions,
  15748. minHeight: minHeight, maxHeight: maxHeight,
  15749. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15750. });
  15751. vertexData.applyToMesh(ground, updatable);
  15752. ground._setReady(true);
  15753. //execute ready callback, if set
  15754. if (onReady) {
  15755. onReady(ground);
  15756. }
  15757. };
  15758. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15759. return ground;
  15760. };
  15761. MeshBuilder.CreateTube = function (name, options, scene) {
  15762. var path = options.path;
  15763. var radius = options.radius || 1;
  15764. var tessellation = options.tessellation || 64;
  15765. var radiusFunction = options.radiusFunction;
  15766. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15767. var updatable = options.updatable;
  15768. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15769. var instance = options.instance;
  15770. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15771. // tube geometry
  15772. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15773. var tangents = path3D.getTangents();
  15774. var normals = path3D.getNormals();
  15775. var distances = path3D.getDistances();
  15776. var pi2 = Math.PI * 2;
  15777. var step = pi2 / tessellation * arc;
  15778. var returnRadius = function () { return radius; };
  15779. var radiusFunctionFinal = radiusFunction || returnRadius;
  15780. var circlePath;
  15781. var rad;
  15782. var normal;
  15783. var rotated;
  15784. var rotationMatrix = BABYLON.Matrix.Zero();
  15785. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15786. for (var i = 0; i < path.length; i++) {
  15787. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15788. circlePath = Array(); // current circle array
  15789. normal = normals[i]; // current normal
  15790. for (var t = 0; t < tessellation; t++) {
  15791. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15792. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15793. circlePath.push(rotated);
  15794. }
  15795. circlePaths[index] = circlePath;
  15796. index++;
  15797. }
  15798. // cap
  15799. var capPath = function (nbPoints, pathIndex) {
  15800. var pointCap = Array();
  15801. for (var i = 0; i < nbPoints; i++) {
  15802. pointCap.push(path[pathIndex]);
  15803. }
  15804. return pointCap;
  15805. };
  15806. switch (cap) {
  15807. case BABYLON.Mesh.NO_CAP:
  15808. break;
  15809. case BABYLON.Mesh.CAP_START:
  15810. circlePaths[0] = capPath(tessellation, 0);
  15811. circlePaths[1] = circlePaths[2].slice(0);
  15812. break;
  15813. case BABYLON.Mesh.CAP_END:
  15814. circlePaths[index] = circlePaths[index - 1].slice(0);
  15815. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15816. break;
  15817. case BABYLON.Mesh.CAP_ALL:
  15818. circlePaths[0] = capPath(tessellation, 0);
  15819. circlePaths[1] = circlePaths[2].slice(0);
  15820. circlePaths[index] = circlePaths[index - 1].slice(0);
  15821. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15822. break;
  15823. default:
  15824. break;
  15825. }
  15826. return circlePaths;
  15827. };
  15828. var path3D;
  15829. var pathArray;
  15830. if (instance) {
  15831. var arc = options.arc || instance.arc;
  15832. path3D = (instance.path3D).update(path);
  15833. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15834. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15835. instance.path3D = path3D;
  15836. instance.pathArray = pathArray;
  15837. instance.arc = arc;
  15838. return instance;
  15839. }
  15840. // tube creation
  15841. path3D = new BABYLON.Path3D(path);
  15842. var newPathArray = new Array();
  15843. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15844. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15845. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15846. tube.pathArray = pathArray;
  15847. tube.path3D = path3D;
  15848. tube.tessellation = tessellation;
  15849. tube.cap = cap;
  15850. tube.arc = options.arc;
  15851. return tube;
  15852. };
  15853. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15854. var polyhedron = new BABYLON.Mesh(name, scene);
  15855. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15856. vertexData.applyToMesh(polyhedron, options.updatable);
  15857. return polyhedron;
  15858. };
  15859. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15860. var indices = sourceMesh.getIndices();
  15861. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15862. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15863. var position = options.position || BABYLON.Vector3.Zero();
  15864. var normal = options.normal || BABYLON.Vector3.Up();
  15865. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15866. var angle = options.angle || 0;
  15867. // Getting correct rotation
  15868. if (!normal) {
  15869. var target = new BABYLON.Vector3(0, 0, 1);
  15870. var camera = sourceMesh.getScene().activeCamera;
  15871. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15872. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15873. }
  15874. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15875. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15876. var pitch = Math.atan2(normal.y, len);
  15877. // Matrix
  15878. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15879. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15880. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15881. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15882. var vertexData = new BABYLON.VertexData();
  15883. vertexData.indices = [];
  15884. vertexData.positions = [];
  15885. vertexData.normals = [];
  15886. vertexData.uvs = [];
  15887. var currentVertexDataIndex = 0;
  15888. var extractDecalVector3 = function (indexId) {
  15889. var vertexId = indices[indexId];
  15890. var result = new BABYLON.PositionNormalVertex();
  15891. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15892. // Send vector to decal local world
  15893. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15894. // Get normal
  15895. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15896. return result;
  15897. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15898. var clip = function (vertices, axis) {
  15899. if (vertices.length === 0) {
  15900. return vertices;
  15901. }
  15902. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15903. var clipVertices = function (v0, v1) {
  15904. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15905. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15906. };
  15907. var result = new Array();
  15908. for (var index = 0; index < vertices.length; index += 3) {
  15909. var v1Out;
  15910. var v2Out;
  15911. var v3Out;
  15912. var total = 0;
  15913. var nV1, nV2, nV3, nV4;
  15914. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15915. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15916. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15917. v1Out = d1 > 0;
  15918. v2Out = d2 > 0;
  15919. v3Out = d3 > 0;
  15920. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15921. switch (total) {
  15922. case 0:
  15923. result.push(vertices[index]);
  15924. result.push(vertices[index + 1]);
  15925. result.push(vertices[index + 2]);
  15926. break;
  15927. case 1:
  15928. if (v1Out) {
  15929. nV1 = vertices[index + 1];
  15930. nV2 = vertices[index + 2];
  15931. nV3 = clipVertices(vertices[index], nV1);
  15932. nV4 = clipVertices(vertices[index], nV2);
  15933. }
  15934. if (v2Out) {
  15935. nV1 = vertices[index];
  15936. nV2 = vertices[index + 2];
  15937. nV3 = clipVertices(vertices[index + 1], nV1);
  15938. nV4 = clipVertices(vertices[index + 1], nV2);
  15939. result.push(nV3);
  15940. result.push(nV2.clone());
  15941. result.push(nV1.clone());
  15942. result.push(nV2.clone());
  15943. result.push(nV3.clone());
  15944. result.push(nV4);
  15945. break;
  15946. }
  15947. if (v3Out) {
  15948. nV1 = vertices[index];
  15949. nV2 = vertices[index + 1];
  15950. nV3 = clipVertices(vertices[index + 2], nV1);
  15951. nV4 = clipVertices(vertices[index + 2], nV2);
  15952. }
  15953. result.push(nV1.clone());
  15954. result.push(nV2.clone());
  15955. result.push(nV3);
  15956. result.push(nV4);
  15957. result.push(nV3.clone());
  15958. result.push(nV2.clone());
  15959. break;
  15960. case 2:
  15961. if (!v1Out) {
  15962. nV1 = vertices[index].clone();
  15963. nV2 = clipVertices(nV1, vertices[index + 1]);
  15964. nV3 = clipVertices(nV1, vertices[index + 2]);
  15965. result.push(nV1);
  15966. result.push(nV2);
  15967. result.push(nV3);
  15968. }
  15969. if (!v2Out) {
  15970. nV1 = vertices[index + 1].clone();
  15971. nV2 = clipVertices(nV1, vertices[index + 2]);
  15972. nV3 = clipVertices(nV1, vertices[index]);
  15973. result.push(nV1);
  15974. result.push(nV2);
  15975. result.push(nV3);
  15976. }
  15977. if (!v3Out) {
  15978. nV1 = vertices[index + 2].clone();
  15979. nV2 = clipVertices(nV1, vertices[index]);
  15980. nV3 = clipVertices(nV1, vertices[index + 1]);
  15981. result.push(nV1);
  15982. result.push(nV2);
  15983. result.push(nV3);
  15984. }
  15985. break;
  15986. case 3:
  15987. break;
  15988. }
  15989. }
  15990. return result;
  15991. };
  15992. for (var index = 0; index < indices.length; index += 3) {
  15993. var faceVertices = new Array();
  15994. faceVertices.push(extractDecalVector3(index));
  15995. faceVertices.push(extractDecalVector3(index + 1));
  15996. faceVertices.push(extractDecalVector3(index + 2));
  15997. // Clip
  15998. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15999. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16000. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16001. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16002. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16003. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16004. if (faceVertices.length === 0) {
  16005. continue;
  16006. }
  16007. // Add UVs and get back to world
  16008. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16009. var vertex = faceVertices[vIndex];
  16010. vertexData.indices.push(currentVertexDataIndex);
  16011. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16012. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16013. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16014. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16015. currentVertexDataIndex++;
  16016. }
  16017. }
  16018. // Return mesh
  16019. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16020. vertexData.applyToMesh(decal);
  16021. decal.position = position.clone();
  16022. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16023. return decal;
  16024. };
  16025. // Privates
  16026. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16027. // extrusion geometry
  16028. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16029. var tangents = path3D.getTangents();
  16030. var normals = path3D.getNormals();
  16031. var binormals = path3D.getBinormals();
  16032. var distances = path3D.getDistances();
  16033. var angle = 0;
  16034. var returnScale = function () { return scale; };
  16035. var returnRotation = function () { return rotation; };
  16036. var rotate = custom ? rotateFunction : returnRotation;
  16037. var scl = custom ? scaleFunction : returnScale;
  16038. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16039. var rotationMatrix = BABYLON.Matrix.Zero();
  16040. for (var i = 0; i < curve.length; i++) {
  16041. var shapePath = new Array();
  16042. var angleStep = rotate(i, distances[i]);
  16043. var scaleRatio = scl(i, distances[i]);
  16044. for (var p = 0; p < shape.length; p++) {
  16045. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16046. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16047. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16048. shapePath.push(rotated);
  16049. }
  16050. shapePaths[index] = shapePath;
  16051. angle += angleStep;
  16052. index++;
  16053. }
  16054. // cap
  16055. var capPath = function (shapePath) {
  16056. var pointCap = Array();
  16057. var barycenter = BABYLON.Vector3.Zero();
  16058. var i;
  16059. for (i = 0; i < shapePath.length; i++) {
  16060. barycenter.addInPlace(shapePath[i]);
  16061. }
  16062. barycenter.scaleInPlace(1 / shapePath.length);
  16063. for (i = 0; i < shapePath.length; i++) {
  16064. pointCap.push(barycenter);
  16065. }
  16066. return pointCap;
  16067. };
  16068. switch (cap) {
  16069. case BABYLON.Mesh.NO_CAP:
  16070. break;
  16071. case BABYLON.Mesh.CAP_START:
  16072. shapePaths[0] = capPath(shapePaths[2]);
  16073. shapePaths[1] = shapePaths[2].slice(0);
  16074. break;
  16075. case BABYLON.Mesh.CAP_END:
  16076. shapePaths[index] = shapePaths[index - 1];
  16077. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16078. break;
  16079. case BABYLON.Mesh.CAP_ALL:
  16080. shapePaths[0] = capPath(shapePaths[2]);
  16081. shapePaths[1] = shapePaths[2].slice(0);
  16082. shapePaths[index] = shapePaths[index - 1];
  16083. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16084. break;
  16085. default:
  16086. break;
  16087. }
  16088. return shapePaths;
  16089. };
  16090. var path3D;
  16091. var pathArray;
  16092. if (instance) {
  16093. path3D = (instance.path3D).update(curve);
  16094. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16095. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16096. return instance;
  16097. }
  16098. // extruded shape creation
  16099. path3D = new BABYLON.Path3D(curve);
  16100. var newShapePaths = new Array();
  16101. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16102. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16103. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16104. extrudedGeneric.pathArray = pathArray;
  16105. extrudedGeneric.path3D = path3D;
  16106. extrudedGeneric.cap = cap;
  16107. return extrudedGeneric;
  16108. };
  16109. return MeshBuilder;
  16110. })();
  16111. BABYLON.MeshBuilder = MeshBuilder;
  16112. })(BABYLON || (BABYLON = {}));
  16113. var BABYLON;
  16114. (function (BABYLON) {
  16115. var BaseTexture = (function () {
  16116. function BaseTexture(scene) {
  16117. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16118. this.hasAlpha = false;
  16119. this.getAlphaFromRGB = false;
  16120. this.level = 1;
  16121. this.isCube = false;
  16122. this.isRenderTarget = false;
  16123. this.animations = new Array();
  16124. this.coordinatesIndex = 0;
  16125. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16126. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16127. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16128. this.anisotropicFilteringLevel = 4;
  16129. this._scene = scene;
  16130. this._scene.textures.push(this);
  16131. }
  16132. BaseTexture.prototype.getScene = function () {
  16133. return this._scene;
  16134. };
  16135. BaseTexture.prototype.getTextureMatrix = function () {
  16136. return null;
  16137. };
  16138. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16139. return null;
  16140. };
  16141. BaseTexture.prototype.getInternalTexture = function () {
  16142. return this._texture;
  16143. };
  16144. BaseTexture.prototype.isReady = function () {
  16145. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16146. return true;
  16147. }
  16148. if (this._texture) {
  16149. return this._texture.isReady;
  16150. }
  16151. return false;
  16152. };
  16153. BaseTexture.prototype.getSize = function () {
  16154. if (this._texture._width) {
  16155. return { width: this._texture._width, height: this._texture._height };
  16156. }
  16157. if (this._texture._size) {
  16158. return { width: this._texture._size, height: this._texture._size };
  16159. }
  16160. return { width: 0, height: 0 };
  16161. };
  16162. BaseTexture.prototype.getBaseSize = function () {
  16163. if (!this.isReady())
  16164. return { width: 0, height: 0 };
  16165. if (this._texture._size) {
  16166. return { width: this._texture._size, height: this._texture._size };
  16167. }
  16168. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16169. };
  16170. BaseTexture.prototype.scale = function (ratio) {
  16171. };
  16172. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16173. get: function () {
  16174. return false;
  16175. },
  16176. enumerable: true,
  16177. configurable: true
  16178. });
  16179. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16180. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16181. for (var index = 0; index < texturesCache.length; index++) {
  16182. var texturesCacheEntry = texturesCache[index];
  16183. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16184. texturesCache.splice(index, 1);
  16185. return;
  16186. }
  16187. }
  16188. };
  16189. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16190. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16191. for (var index = 0; index < texturesCache.length; index++) {
  16192. var texturesCacheEntry = texturesCache[index];
  16193. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16194. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16195. texturesCacheEntry.references++;
  16196. return texturesCacheEntry;
  16197. }
  16198. }
  16199. }
  16200. return null;
  16201. };
  16202. BaseTexture.prototype.delayLoad = function () {
  16203. };
  16204. BaseTexture.prototype.clone = function () {
  16205. return null;
  16206. };
  16207. BaseTexture.prototype.releaseInternalTexture = function () {
  16208. if (this._texture) {
  16209. this._scene.getEngine().releaseInternalTexture(this._texture);
  16210. delete this._texture;
  16211. }
  16212. };
  16213. BaseTexture.prototype.dispose = function () {
  16214. // Animations
  16215. this.getScene().stopAnimation(this);
  16216. // Remove from scene
  16217. var index = this._scene.textures.indexOf(this);
  16218. if (index >= 0) {
  16219. this._scene.textures.splice(index, 1);
  16220. }
  16221. if (this._texture === undefined) {
  16222. return;
  16223. }
  16224. // Callback
  16225. if (this.onDispose) {
  16226. this.onDispose();
  16227. }
  16228. };
  16229. return BaseTexture;
  16230. })();
  16231. BABYLON.BaseTexture = BaseTexture;
  16232. })(BABYLON || (BABYLON = {}));
  16233. var BABYLON;
  16234. (function (BABYLON) {
  16235. var Texture = (function (_super) {
  16236. __extends(Texture, _super);
  16237. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16238. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16239. if (onLoad === void 0) { onLoad = null; }
  16240. if (onError === void 0) { onError = null; }
  16241. if (buffer === void 0) { buffer = null; }
  16242. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16243. _super.call(this, scene);
  16244. this.uOffset = 0;
  16245. this.vOffset = 0;
  16246. this.uScale = 1.0;
  16247. this.vScale = 1.0;
  16248. this.uAng = 0;
  16249. this.vAng = 0;
  16250. this.wAng = 0;
  16251. this.name = url;
  16252. this.url = url;
  16253. this._noMipmap = noMipmap;
  16254. this._invertY = invertY;
  16255. this._samplingMode = samplingMode;
  16256. this._buffer = buffer;
  16257. this._deleteBuffer = deleteBuffer;
  16258. if (!url) {
  16259. return;
  16260. }
  16261. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16262. if (!this._texture) {
  16263. if (!scene.useDelayedTextureLoading) {
  16264. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16265. if (deleteBuffer) {
  16266. delete this._buffer;
  16267. }
  16268. }
  16269. else {
  16270. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16271. }
  16272. }
  16273. else {
  16274. BABYLON.Tools.SetImmediate(function () {
  16275. if (onLoad) {
  16276. onLoad();
  16277. }
  16278. });
  16279. }
  16280. }
  16281. Texture.prototype.delayLoad = function () {
  16282. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16283. return;
  16284. }
  16285. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16286. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16287. if (!this._texture) {
  16288. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16289. if (this._deleteBuffer) {
  16290. delete this._buffer;
  16291. }
  16292. }
  16293. };
  16294. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16295. if (!this._texture) {
  16296. return;
  16297. }
  16298. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16299. };
  16300. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16301. x *= this.uScale;
  16302. y *= this.vScale;
  16303. x -= 0.5 * this.uScale;
  16304. y -= 0.5 * this.vScale;
  16305. z -= 0.5;
  16306. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16307. t.x += 0.5 * this.uScale + this.uOffset;
  16308. t.y += 0.5 * this.vScale + this.vOffset;
  16309. t.z += 0.5;
  16310. };
  16311. Texture.prototype.getTextureMatrix = function () {
  16312. if (this.uOffset === this._cachedUOffset &&
  16313. this.vOffset === this._cachedVOffset &&
  16314. this.uScale === this._cachedUScale &&
  16315. this.vScale === this._cachedVScale &&
  16316. this.uAng === this._cachedUAng &&
  16317. this.vAng === this._cachedVAng &&
  16318. this.wAng === this._cachedWAng) {
  16319. return this._cachedTextureMatrix;
  16320. }
  16321. this._cachedUOffset = this.uOffset;
  16322. this._cachedVOffset = this.vOffset;
  16323. this._cachedUScale = this.uScale;
  16324. this._cachedVScale = this.vScale;
  16325. this._cachedUAng = this.uAng;
  16326. this._cachedVAng = this.vAng;
  16327. this._cachedWAng = this.wAng;
  16328. if (!this._cachedTextureMatrix) {
  16329. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16330. this._rowGenerationMatrix = new BABYLON.Matrix();
  16331. this._t0 = BABYLON.Vector3.Zero();
  16332. this._t1 = BABYLON.Vector3.Zero();
  16333. this._t2 = BABYLON.Vector3.Zero();
  16334. }
  16335. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16336. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16337. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16338. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16339. this._t1.subtractInPlace(this._t0);
  16340. this._t2.subtractInPlace(this._t0);
  16341. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16342. this._cachedTextureMatrix.m[0] = this._t1.x;
  16343. this._cachedTextureMatrix.m[1] = this._t1.y;
  16344. this._cachedTextureMatrix.m[2] = this._t1.z;
  16345. this._cachedTextureMatrix.m[4] = this._t2.x;
  16346. this._cachedTextureMatrix.m[5] = this._t2.y;
  16347. this._cachedTextureMatrix.m[6] = this._t2.z;
  16348. this._cachedTextureMatrix.m[8] = this._t0.x;
  16349. this._cachedTextureMatrix.m[9] = this._t0.y;
  16350. this._cachedTextureMatrix.m[10] = this._t0.z;
  16351. return this._cachedTextureMatrix;
  16352. };
  16353. Texture.prototype.getReflectionTextureMatrix = function () {
  16354. if (this.uOffset === this._cachedUOffset &&
  16355. this.vOffset === this._cachedVOffset &&
  16356. this.uScale === this._cachedUScale &&
  16357. this.vScale === this._cachedVScale &&
  16358. this.coordinatesMode === this._cachedCoordinatesMode) {
  16359. return this._cachedTextureMatrix;
  16360. }
  16361. if (!this._cachedTextureMatrix) {
  16362. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16363. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16364. }
  16365. this._cachedCoordinatesMode = this.coordinatesMode;
  16366. switch (this.coordinatesMode) {
  16367. case Texture.PLANAR_MODE:
  16368. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16369. this._cachedTextureMatrix[0] = this.uScale;
  16370. this._cachedTextureMatrix[5] = this.vScale;
  16371. this._cachedTextureMatrix[12] = this.uOffset;
  16372. this._cachedTextureMatrix[13] = this.vOffset;
  16373. break;
  16374. case Texture.PROJECTION_MODE:
  16375. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16376. this._projectionModeMatrix.m[0] = 0.5;
  16377. this._projectionModeMatrix.m[5] = -0.5;
  16378. this._projectionModeMatrix.m[10] = 0.0;
  16379. this._projectionModeMatrix.m[12] = 0.5;
  16380. this._projectionModeMatrix.m[13] = 0.5;
  16381. this._projectionModeMatrix.m[14] = 1.0;
  16382. this._projectionModeMatrix.m[15] = 1.0;
  16383. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16384. break;
  16385. default:
  16386. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16387. break;
  16388. }
  16389. return this._cachedTextureMatrix;
  16390. };
  16391. Texture.prototype.clone = function () {
  16392. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16393. // Base texture
  16394. newTexture.hasAlpha = this.hasAlpha;
  16395. newTexture.level = this.level;
  16396. newTexture.wrapU = this.wrapU;
  16397. newTexture.wrapV = this.wrapV;
  16398. newTexture.coordinatesIndex = this.coordinatesIndex;
  16399. newTexture.coordinatesMode = this.coordinatesMode;
  16400. // Texture
  16401. newTexture.uOffset = this.uOffset;
  16402. newTexture.vOffset = this.vOffset;
  16403. newTexture.uScale = this.uScale;
  16404. newTexture.vScale = this.vScale;
  16405. newTexture.uAng = this.uAng;
  16406. newTexture.vAng = this.vAng;
  16407. newTexture.wAng = this.wAng;
  16408. return newTexture;
  16409. };
  16410. // Statics
  16411. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16412. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16413. if (onLoad === void 0) { onLoad = null; }
  16414. if (onError === void 0) { onError = null; }
  16415. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16416. };
  16417. // Constants
  16418. Texture.NEAREST_SAMPLINGMODE = 1;
  16419. Texture.BILINEAR_SAMPLINGMODE = 2;
  16420. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16421. Texture.EXPLICIT_MODE = 0;
  16422. Texture.SPHERICAL_MODE = 1;
  16423. Texture.PLANAR_MODE = 2;
  16424. Texture.CUBIC_MODE = 3;
  16425. Texture.PROJECTION_MODE = 4;
  16426. Texture.SKYBOX_MODE = 5;
  16427. Texture.INVCUBIC_MODE = 6;
  16428. Texture.EQUIRECTANGULAR_MODE = 7;
  16429. Texture.CLAMP_ADDRESSMODE = 0;
  16430. Texture.WRAP_ADDRESSMODE = 1;
  16431. Texture.MIRROR_ADDRESSMODE = 2;
  16432. return Texture;
  16433. })(BABYLON.BaseTexture);
  16434. BABYLON.Texture = Texture;
  16435. })(BABYLON || (BABYLON = {}));
  16436. var BABYLON;
  16437. (function (BABYLON) {
  16438. var CubeTexture = (function (_super) {
  16439. __extends(CubeTexture, _super);
  16440. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16441. _super.call(this, scene);
  16442. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16443. this.name = rootUrl;
  16444. this.url = rootUrl;
  16445. this._noMipmap = noMipmap;
  16446. this.hasAlpha = false;
  16447. if (!rootUrl) {
  16448. return;
  16449. }
  16450. this._texture = this._getFromCache(rootUrl, noMipmap);
  16451. if (!extensions) {
  16452. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16453. }
  16454. this._extensions = extensions;
  16455. if (!this._texture) {
  16456. if (!scene.useDelayedTextureLoading) {
  16457. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16458. }
  16459. else {
  16460. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16461. }
  16462. }
  16463. this.isCube = true;
  16464. this._textureMatrix = BABYLON.Matrix.Identity();
  16465. }
  16466. CubeTexture.prototype.clone = function () {
  16467. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16468. // Base texture
  16469. newTexture.level = this.level;
  16470. newTexture.wrapU = this.wrapU;
  16471. newTexture.wrapV = this.wrapV;
  16472. newTexture.coordinatesIndex = this.coordinatesIndex;
  16473. newTexture.coordinatesMode = this.coordinatesMode;
  16474. return newTexture;
  16475. };
  16476. // Methods
  16477. CubeTexture.prototype.delayLoad = function () {
  16478. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16479. return;
  16480. }
  16481. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16482. this._texture = this._getFromCache(this.url, this._noMipmap);
  16483. if (!this._texture) {
  16484. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16485. }
  16486. };
  16487. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16488. return this._textureMatrix;
  16489. };
  16490. return CubeTexture;
  16491. })(BABYLON.BaseTexture);
  16492. BABYLON.CubeTexture = CubeTexture;
  16493. })(BABYLON || (BABYLON = {}));
  16494. var BABYLON;
  16495. (function (BABYLON) {
  16496. var RenderTargetTexture = (function (_super) {
  16497. __extends(RenderTargetTexture, _super);
  16498. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16499. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16500. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16501. if (isCube === void 0) { isCube = false; }
  16502. _super.call(this, null, scene, !generateMipMaps);
  16503. this.isCube = isCube;
  16504. this.renderList = new Array();
  16505. this.renderParticles = true;
  16506. this.renderSprites = false;
  16507. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16508. this._currentRefreshId = -1;
  16509. this._refreshRate = 1;
  16510. this.name = name;
  16511. this.isRenderTarget = true;
  16512. this._size = size;
  16513. this._generateMipMaps = generateMipMaps;
  16514. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16515. if (isCube) {
  16516. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16517. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16518. this._textureMatrix = BABYLON.Matrix.Identity();
  16519. }
  16520. else {
  16521. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16522. }
  16523. // Rendering groups
  16524. this._renderingManager = new BABYLON.RenderingManager(scene);
  16525. }
  16526. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16527. get: function () {
  16528. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16529. },
  16530. enumerable: true,
  16531. configurable: true
  16532. });
  16533. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16534. get: function () {
  16535. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16536. },
  16537. enumerable: true,
  16538. configurable: true
  16539. });
  16540. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16541. get: function () {
  16542. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16543. },
  16544. enumerable: true,
  16545. configurable: true
  16546. });
  16547. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16548. this._currentRefreshId = -1;
  16549. };
  16550. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16551. get: function () {
  16552. return this._refreshRate;
  16553. },
  16554. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16555. set: function (value) {
  16556. this._refreshRate = value;
  16557. this.resetRefreshCounter();
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. RenderTargetTexture.prototype._shouldRender = function () {
  16563. if (this._currentRefreshId === -1) {
  16564. this._currentRefreshId = 1;
  16565. return true;
  16566. }
  16567. if (this.refreshRate === this._currentRefreshId) {
  16568. this._currentRefreshId = 1;
  16569. return true;
  16570. }
  16571. this._currentRefreshId++;
  16572. return false;
  16573. };
  16574. RenderTargetTexture.prototype.isReady = function () {
  16575. if (!this.getScene().renderTargetsEnabled) {
  16576. return false;
  16577. }
  16578. return _super.prototype.isReady.call(this);
  16579. };
  16580. RenderTargetTexture.prototype.getRenderSize = function () {
  16581. return this._size;
  16582. };
  16583. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16584. get: function () {
  16585. return true;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. RenderTargetTexture.prototype.scale = function (ratio) {
  16591. var newSize = this._size * ratio;
  16592. this.resize(newSize, this._generateMipMaps);
  16593. };
  16594. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16595. if (this.isCube) {
  16596. return this._textureMatrix;
  16597. }
  16598. return _super.prototype.getReflectionTextureMatrix.call(this);
  16599. };
  16600. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16601. this.releaseInternalTexture();
  16602. if (this.isCube) {
  16603. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16604. }
  16605. else {
  16606. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16607. }
  16608. };
  16609. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16610. var scene = this.getScene();
  16611. if (this._waitingRenderList) {
  16612. this.renderList = [];
  16613. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16614. var id = this._waitingRenderList[index];
  16615. this.renderList.push(scene.getMeshByID(id));
  16616. }
  16617. delete this._waitingRenderList;
  16618. }
  16619. if (this.renderList && this.renderList.length === 0) {
  16620. return;
  16621. }
  16622. // Prepare renderingManager
  16623. this._renderingManager.reset();
  16624. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16625. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16626. var mesh = currentRenderList[meshIndex];
  16627. if (mesh) {
  16628. if (!mesh.isReady()) {
  16629. // Reset _currentRefreshId
  16630. this.resetRefreshCounter();
  16631. continue;
  16632. }
  16633. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16634. mesh._activate(scene.getRenderId());
  16635. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16636. var subMesh = mesh.subMeshes[subIndex];
  16637. scene._activeIndices += subMesh.indexCount;
  16638. this._renderingManager.dispatch(subMesh);
  16639. }
  16640. }
  16641. }
  16642. }
  16643. if (this.isCube) {
  16644. for (var face = 0; face < 6; face++) {
  16645. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16646. }
  16647. }
  16648. else {
  16649. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16650. }
  16651. if (this.onAfterUnbind) {
  16652. this.onAfterUnbind();
  16653. }
  16654. scene.resetCachedMaterial();
  16655. };
  16656. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16657. var scene = this.getScene();
  16658. var engine = scene.getEngine();
  16659. // Bind
  16660. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16661. if (this.isCube) {
  16662. engine.bindFramebuffer(this._texture, faceIndex);
  16663. }
  16664. else {
  16665. engine.bindFramebuffer(this._texture);
  16666. }
  16667. }
  16668. if (this.onBeforeRender) {
  16669. this.onBeforeRender(faceIndex);
  16670. }
  16671. // Clear
  16672. if (this.onClear) {
  16673. this.onClear(engine);
  16674. }
  16675. else {
  16676. engine.clear(scene.clearColor, true, true);
  16677. }
  16678. if (!this._doNotChangeAspectRatio) {
  16679. scene.updateTransformMatrix(true);
  16680. }
  16681. // Render
  16682. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16683. if (useCameraPostProcess) {
  16684. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16685. }
  16686. if (!this._doNotChangeAspectRatio) {
  16687. scene.updateTransformMatrix(true);
  16688. }
  16689. if (this.onAfterRender) {
  16690. this.onAfterRender(faceIndex);
  16691. }
  16692. // Dump ?
  16693. if (dumpForDebug) {
  16694. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16695. }
  16696. // Unbind
  16697. if (!this.isCube || faceIndex === 5) {
  16698. if (this.isCube) {
  16699. if (faceIndex === 5) {
  16700. engine.generateMipMapsForCubemap(this._texture);
  16701. }
  16702. }
  16703. engine.unBindFramebuffer(this._texture, this.isCube);
  16704. }
  16705. };
  16706. RenderTargetTexture.prototype.clone = function () {
  16707. var textureSize = this.getSize();
  16708. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16709. // Base texture
  16710. newTexture.hasAlpha = this.hasAlpha;
  16711. newTexture.level = this.level;
  16712. // RenderTarget Texture
  16713. newTexture.coordinatesMode = this.coordinatesMode;
  16714. newTexture.renderList = this.renderList.slice(0);
  16715. return newTexture;
  16716. };
  16717. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16718. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16719. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16720. return RenderTargetTexture;
  16721. })(BABYLON.Texture);
  16722. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16723. })(BABYLON || (BABYLON = {}));
  16724. var BABYLON;
  16725. (function (BABYLON) {
  16726. var ProceduralTexture = (function (_super) {
  16727. __extends(ProceduralTexture, _super);
  16728. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16729. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16730. _super.call(this, null, scene, !generateMipMaps);
  16731. this.isEnabled = true;
  16732. this._currentRefreshId = -1;
  16733. this._refreshRate = 1;
  16734. this._vertexDeclaration = [2];
  16735. this._vertexStrideSize = 2 * 4;
  16736. this._uniforms = new Array();
  16737. this._samplers = new Array();
  16738. this._textures = new Array();
  16739. this._floats = new Array();
  16740. this._floatsArrays = {};
  16741. this._colors3 = new Array();
  16742. this._colors4 = new Array();
  16743. this._vectors2 = new Array();
  16744. this._vectors3 = new Array();
  16745. this._matrices = new Array();
  16746. this._fallbackTextureUsed = false;
  16747. scene._proceduralTextures.push(this);
  16748. this.name = name;
  16749. this.isRenderTarget = true;
  16750. this._size = size;
  16751. this._generateMipMaps = generateMipMaps;
  16752. this.setFragment(fragment);
  16753. this._fallbackTexture = fallbackTexture;
  16754. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16755. // VBO
  16756. var vertices = [];
  16757. vertices.push(1, 1);
  16758. vertices.push(-1, 1);
  16759. vertices.push(-1, -1);
  16760. vertices.push(1, -1);
  16761. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16762. // Indices
  16763. var indices = [];
  16764. indices.push(0);
  16765. indices.push(1);
  16766. indices.push(2);
  16767. indices.push(0);
  16768. indices.push(2);
  16769. indices.push(3);
  16770. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16771. }
  16772. ProceduralTexture.prototype.reset = function () {
  16773. if (this._effect === undefined) {
  16774. return;
  16775. }
  16776. var engine = this.getScene().getEngine();
  16777. engine._releaseEffect(this._effect);
  16778. };
  16779. ProceduralTexture.prototype.isReady = function () {
  16780. var _this = this;
  16781. var engine = this.getScene().getEngine();
  16782. var shaders;
  16783. if (!this._fragment) {
  16784. return false;
  16785. }
  16786. if (this._fallbackTextureUsed) {
  16787. return true;
  16788. }
  16789. if (this._fragment.fragmentElement !== undefined) {
  16790. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16791. }
  16792. else {
  16793. shaders = { vertex: "procedural", fragment: this._fragment };
  16794. }
  16795. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16796. _this.releaseInternalTexture();
  16797. if (_this._fallbackTexture) {
  16798. _this._texture = _this._fallbackTexture._texture;
  16799. _this._texture.references++;
  16800. }
  16801. _this._fallbackTextureUsed = true;
  16802. });
  16803. return this._effect.isReady();
  16804. };
  16805. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16806. this._currentRefreshId = -1;
  16807. };
  16808. ProceduralTexture.prototype.setFragment = function (fragment) {
  16809. this._fragment = fragment;
  16810. };
  16811. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16812. get: function () {
  16813. return this._refreshRate;
  16814. },
  16815. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16816. set: function (value) {
  16817. this._refreshRate = value;
  16818. this.resetRefreshCounter();
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. ProceduralTexture.prototype._shouldRender = function () {
  16824. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16825. return false;
  16826. }
  16827. if (this._fallbackTextureUsed) {
  16828. return false;
  16829. }
  16830. if (this._currentRefreshId === -1) {
  16831. this._currentRefreshId = 1;
  16832. return true;
  16833. }
  16834. if (this.refreshRate === this._currentRefreshId) {
  16835. this._currentRefreshId = 1;
  16836. return true;
  16837. }
  16838. this._currentRefreshId++;
  16839. return false;
  16840. };
  16841. ProceduralTexture.prototype.getRenderSize = function () {
  16842. return this._size;
  16843. };
  16844. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16845. if (this._fallbackTextureUsed) {
  16846. return;
  16847. }
  16848. this.releaseInternalTexture();
  16849. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16850. };
  16851. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16852. if (this._uniforms.indexOf(uniformName) === -1) {
  16853. this._uniforms.push(uniformName);
  16854. }
  16855. };
  16856. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16857. if (this._samplers.indexOf(name) === -1) {
  16858. this._samplers.push(name);
  16859. }
  16860. this._textures[name] = texture;
  16861. return this;
  16862. };
  16863. ProceduralTexture.prototype.setFloat = function (name, value) {
  16864. this._checkUniform(name);
  16865. this._floats[name] = value;
  16866. return this;
  16867. };
  16868. ProceduralTexture.prototype.setFloats = function (name, value) {
  16869. this._checkUniform(name);
  16870. this._floatsArrays[name] = value;
  16871. return this;
  16872. };
  16873. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16874. this._checkUniform(name);
  16875. this._colors3[name] = value;
  16876. return this;
  16877. };
  16878. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16879. this._checkUniform(name);
  16880. this._colors4[name] = value;
  16881. return this;
  16882. };
  16883. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16884. this._checkUniform(name);
  16885. this._vectors2[name] = value;
  16886. return this;
  16887. };
  16888. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16889. this._checkUniform(name);
  16890. this._vectors3[name] = value;
  16891. return this;
  16892. };
  16893. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16894. this._checkUniform(name);
  16895. this._matrices[name] = value;
  16896. return this;
  16897. };
  16898. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16899. var scene = this.getScene();
  16900. var engine = scene.getEngine();
  16901. engine.bindFramebuffer(this._texture);
  16902. // Clear
  16903. engine.clear(scene.clearColor, true, true);
  16904. // Render
  16905. engine.enableEffect(this._effect);
  16906. engine.setState(false);
  16907. // Texture
  16908. for (var name in this._textures) {
  16909. this._effect.setTexture(name, this._textures[name]);
  16910. }
  16911. // Float
  16912. for (name in this._floats) {
  16913. this._effect.setFloat(name, this._floats[name]);
  16914. }
  16915. // Floats
  16916. for (name in this._floatsArrays) {
  16917. this._effect.setArray(name, this._floatsArrays[name]);
  16918. }
  16919. // Color3
  16920. for (name in this._colors3) {
  16921. this._effect.setColor3(name, this._colors3[name]);
  16922. }
  16923. // Color4
  16924. for (name in this._colors4) {
  16925. var color = this._colors4[name];
  16926. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16927. }
  16928. // Vector2
  16929. for (name in this._vectors2) {
  16930. this._effect.setVector2(name, this._vectors2[name]);
  16931. }
  16932. // Vector3
  16933. for (name in this._vectors3) {
  16934. this._effect.setVector3(name, this._vectors3[name]);
  16935. }
  16936. // Matrix
  16937. for (name in this._matrices) {
  16938. this._effect.setMatrix(name, this._matrices[name]);
  16939. }
  16940. // VBOs
  16941. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16942. // Draw order
  16943. engine.draw(true, 0, 6);
  16944. // Unbind
  16945. engine.unBindFramebuffer(this._texture);
  16946. };
  16947. ProceduralTexture.prototype.clone = function () {
  16948. var textureSize = this.getSize();
  16949. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16950. // Base texture
  16951. newTexture.hasAlpha = this.hasAlpha;
  16952. newTexture.level = this.level;
  16953. // RenderTarget Texture
  16954. newTexture.coordinatesMode = this.coordinatesMode;
  16955. return newTexture;
  16956. };
  16957. ProceduralTexture.prototype.dispose = function () {
  16958. var index = this.getScene()._proceduralTextures.indexOf(this);
  16959. if (index >= 0) {
  16960. this.getScene()._proceduralTextures.splice(index, 1);
  16961. }
  16962. _super.prototype.dispose.call(this);
  16963. };
  16964. return ProceduralTexture;
  16965. })(BABYLON.Texture);
  16966. BABYLON.ProceduralTexture = ProceduralTexture;
  16967. })(BABYLON || (BABYLON = {}));
  16968. var BABYLON;
  16969. (function (BABYLON) {
  16970. var MirrorTexture = (function (_super) {
  16971. __extends(MirrorTexture, _super);
  16972. function MirrorTexture(name, size, scene, generateMipMaps) {
  16973. var _this = this;
  16974. _super.call(this, name, size, scene, generateMipMaps, true);
  16975. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16976. this._transformMatrix = BABYLON.Matrix.Zero();
  16977. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16978. this.onBeforeRender = function () {
  16979. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16980. _this._savedViewMatrix = scene.getViewMatrix();
  16981. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16982. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16983. scene.clipPlane = _this.mirrorPlane;
  16984. scene.getEngine().cullBackFaces = false;
  16985. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  16986. };
  16987. this.onAfterRender = function () {
  16988. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16989. scene.getEngine().cullBackFaces = true;
  16990. scene._mirroredCameraPosition = null;
  16991. delete scene.clipPlane;
  16992. };
  16993. }
  16994. MirrorTexture.prototype.clone = function () {
  16995. var textureSize = this.getSize();
  16996. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16997. // Base texture
  16998. newTexture.hasAlpha = this.hasAlpha;
  16999. newTexture.level = this.level;
  17000. // Mirror Texture
  17001. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17002. newTexture.renderList = this.renderList.slice(0);
  17003. return newTexture;
  17004. };
  17005. return MirrorTexture;
  17006. })(BABYLON.RenderTargetTexture);
  17007. BABYLON.MirrorTexture = MirrorTexture;
  17008. })(BABYLON || (BABYLON = {}));
  17009. var BABYLON;
  17010. (function (BABYLON) {
  17011. var DynamicTexture = (function (_super) {
  17012. __extends(DynamicTexture, _super);
  17013. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17015. _super.call(this, null, scene, !generateMipMaps);
  17016. this.name = name;
  17017. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17018. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17019. this._generateMipMaps = generateMipMaps;
  17020. if (options.getContext) {
  17021. this._canvas = options;
  17022. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17023. }
  17024. else {
  17025. this._canvas = document.createElement("canvas");
  17026. if (options.width) {
  17027. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17028. }
  17029. else {
  17030. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17031. }
  17032. }
  17033. var textureSize = this.getSize();
  17034. this._canvas.width = textureSize.width;
  17035. this._canvas.height = textureSize.height;
  17036. this._context = this._canvas.getContext("2d");
  17037. }
  17038. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17039. get: function () {
  17040. return true;
  17041. },
  17042. enumerable: true,
  17043. configurable: true
  17044. });
  17045. DynamicTexture.prototype.scale = function (ratio) {
  17046. var textureSize = this.getSize();
  17047. textureSize.width *= ratio;
  17048. textureSize.height *= ratio;
  17049. this._canvas.width = textureSize.width;
  17050. this._canvas.height = textureSize.height;
  17051. this.releaseInternalTexture();
  17052. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17053. };
  17054. DynamicTexture.prototype.getContext = function () {
  17055. return this._context;
  17056. };
  17057. DynamicTexture.prototype.clear = function () {
  17058. var size = this.getSize();
  17059. this._context.fillRect(0, 0, size.width, size.height);
  17060. };
  17061. DynamicTexture.prototype.update = function (invertY) {
  17062. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17063. };
  17064. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17065. if (update === void 0) { update = true; }
  17066. var size = this.getSize();
  17067. if (clearColor) {
  17068. this._context.fillStyle = clearColor;
  17069. this._context.fillRect(0, 0, size.width, size.height);
  17070. }
  17071. this._context.font = font;
  17072. if (x === null) {
  17073. var textSize = this._context.measureText(text);
  17074. x = (size.width - textSize.width) / 2;
  17075. }
  17076. this._context.fillStyle = color;
  17077. this._context.fillText(text, x, y);
  17078. if (update) {
  17079. this.update(invertY);
  17080. }
  17081. };
  17082. DynamicTexture.prototype.clone = function () {
  17083. var textureSize = this.getSize();
  17084. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17085. // Base texture
  17086. newTexture.hasAlpha = this.hasAlpha;
  17087. newTexture.level = this.level;
  17088. // Dynamic Texture
  17089. newTexture.wrapU = this.wrapU;
  17090. newTexture.wrapV = this.wrapV;
  17091. return newTexture;
  17092. };
  17093. return DynamicTexture;
  17094. })(BABYLON.Texture);
  17095. BABYLON.DynamicTexture = DynamicTexture;
  17096. })(BABYLON || (BABYLON = {}));
  17097. var BABYLON;
  17098. (function (BABYLON) {
  17099. var VideoTexture = (function (_super) {
  17100. __extends(VideoTexture, _super);
  17101. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17102. var _this = this;
  17103. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17104. if (invertY === void 0) { invertY = false; }
  17105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17106. _super.call(this, null, scene, !generateMipMaps, invertY);
  17107. this._autoLaunch = true;
  17108. this.name = name;
  17109. this.video = document.createElement("video");
  17110. this.video.autoplay = false;
  17111. this.video.loop = true;
  17112. this.video.addEventListener("canplaythrough", function () {
  17113. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17114. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17115. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17116. }
  17117. else {
  17118. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17119. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17120. generateMipMaps = false;
  17121. }
  17122. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17123. _this._texture.isReady = true;
  17124. });
  17125. urls.forEach(function (url) {
  17126. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17127. var source = document.createElement("source");
  17128. source.src = url;
  17129. _this.video.appendChild(source);
  17130. });
  17131. this._lastUpdate = BABYLON.Tools.Now;
  17132. }
  17133. VideoTexture.prototype.update = function () {
  17134. if (this._autoLaunch) {
  17135. this._autoLaunch = false;
  17136. this.video.play();
  17137. }
  17138. var now = BABYLON.Tools.Now;
  17139. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17140. return false;
  17141. }
  17142. this._lastUpdate = now;
  17143. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17144. return true;
  17145. };
  17146. return VideoTexture;
  17147. })(BABYLON.Texture);
  17148. BABYLON.VideoTexture = VideoTexture;
  17149. })(BABYLON || (BABYLON = {}));
  17150. var BABYLON;
  17151. (function (BABYLON) {
  17152. var CustomProceduralTexture = (function (_super) {
  17153. __extends(CustomProceduralTexture, _super);
  17154. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17155. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17156. this._animate = true;
  17157. this._time = 0;
  17158. this._texturePath = texturePath;
  17159. //Try to load json
  17160. this.loadJson(texturePath);
  17161. this.refreshRate = 1;
  17162. }
  17163. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17164. var _this = this;
  17165. var that = this;
  17166. function noConfigFile() {
  17167. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17168. try {
  17169. that.setFragment(that._texturePath);
  17170. }
  17171. catch (ex) {
  17172. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17173. }
  17174. }
  17175. var configFileUrl = jsonUrl + "/config.json";
  17176. var xhr = new XMLHttpRequest();
  17177. xhr.open("GET", configFileUrl, true);
  17178. xhr.addEventListener("load", function () {
  17179. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17180. try {
  17181. _this._config = JSON.parse(xhr.response);
  17182. _this.updateShaderUniforms();
  17183. _this.updateTextures();
  17184. _this.setFragment(_this._texturePath + "/custom");
  17185. _this._animate = _this._config.animate;
  17186. _this.refreshRate = _this._config.refreshrate;
  17187. }
  17188. catch (ex) {
  17189. noConfigFile();
  17190. }
  17191. }
  17192. else {
  17193. noConfigFile();
  17194. }
  17195. }, false);
  17196. xhr.addEventListener("error", function () {
  17197. noConfigFile();
  17198. }, false);
  17199. try {
  17200. xhr.send();
  17201. }
  17202. catch (ex) {
  17203. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17204. }
  17205. };
  17206. CustomProceduralTexture.prototype.isReady = function () {
  17207. if (!_super.prototype.isReady.call(this)) {
  17208. return false;
  17209. }
  17210. for (var name in this._textures) {
  17211. var texture = this._textures[name];
  17212. if (!texture.isReady()) {
  17213. return false;
  17214. }
  17215. }
  17216. return true;
  17217. };
  17218. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17219. if (this._animate) {
  17220. this._time += this.getScene().getAnimationRatio() * 0.03;
  17221. this.updateShaderUniforms();
  17222. }
  17223. _super.prototype.render.call(this, useCameraPostProcess);
  17224. };
  17225. CustomProceduralTexture.prototype.updateTextures = function () {
  17226. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17227. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17228. }
  17229. };
  17230. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17231. if (this._config) {
  17232. for (var j = 0; j < this._config.uniforms.length; j++) {
  17233. var uniform = this._config.uniforms[j];
  17234. switch (uniform.type) {
  17235. case "float":
  17236. this.setFloat(uniform.name, uniform.value);
  17237. break;
  17238. case "color3":
  17239. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17240. break;
  17241. case "color4":
  17242. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17243. break;
  17244. case "vector2":
  17245. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17246. break;
  17247. case "vector3":
  17248. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17249. break;
  17250. }
  17251. }
  17252. }
  17253. this.setFloat("time", this._time);
  17254. };
  17255. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17256. get: function () {
  17257. return this._animate;
  17258. },
  17259. set: function (value) {
  17260. this._animate = value;
  17261. },
  17262. enumerable: true,
  17263. configurable: true
  17264. });
  17265. return CustomProceduralTexture;
  17266. })(BABYLON.ProceduralTexture);
  17267. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17268. })(BABYLON || (BABYLON = {}));
  17269. var BABYLON;
  17270. (function (BABYLON) {
  17271. var WoodProceduralTexture = (function (_super) {
  17272. __extends(WoodProceduralTexture, _super);
  17273. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17274. _super.call(this, name, size, "woodtexture", scene, fallbackTexture, generateMipMaps);
  17275. this._ampScale = 100.0;
  17276. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17277. this.updateShaderUniforms();
  17278. this.refreshRate = 0;
  17279. }
  17280. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17281. this.setFloat("ampScale", this._ampScale);
  17282. this.setColor3("woodColor", this._woodColor);
  17283. };
  17284. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17285. get: function () {
  17286. return this._ampScale;
  17287. },
  17288. set: function (value) {
  17289. this._ampScale = value;
  17290. this.updateShaderUniforms();
  17291. },
  17292. enumerable: true,
  17293. configurable: true
  17294. });
  17295. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17296. get: function () {
  17297. return this._woodColor;
  17298. },
  17299. set: function (value) {
  17300. this._woodColor = value;
  17301. this.updateShaderUniforms();
  17302. },
  17303. enumerable: true,
  17304. configurable: true
  17305. });
  17306. return WoodProceduralTexture;
  17307. })(BABYLON.ProceduralTexture);
  17308. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17309. var FireProceduralTexture = (function (_super) {
  17310. __extends(FireProceduralTexture, _super);
  17311. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17312. _super.call(this, name, size, "firetexture", scene, fallbackTexture, generateMipMaps);
  17313. this._time = 0.0;
  17314. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17315. this._autoGenerateTime = true;
  17316. this._alphaThreshold = 0.5;
  17317. this._fireColors = FireProceduralTexture.RedFireColors;
  17318. this.updateShaderUniforms();
  17319. this.refreshRate = 1;
  17320. }
  17321. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17322. this.setFloat("time", this._time);
  17323. this.setVector2("speed", this._speed);
  17324. this.setColor3("c1", this._fireColors[0]);
  17325. this.setColor3("c2", this._fireColors[1]);
  17326. this.setColor3("c3", this._fireColors[2]);
  17327. this.setColor3("c4", this._fireColors[3]);
  17328. this.setColor3("c5", this._fireColors[4]);
  17329. this.setColor3("c6", this._fireColors[5]);
  17330. this.setFloat("alphaThreshold", this._alphaThreshold);
  17331. };
  17332. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17333. if (this._autoGenerateTime) {
  17334. this._time += this.getScene().getAnimationRatio() * 0.03;
  17335. this.updateShaderUniforms();
  17336. }
  17337. _super.prototype.render.call(this, useCameraPostProcess);
  17338. };
  17339. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17340. get: function () {
  17341. return [
  17342. new BABYLON.Color3(0.5, 0.0, 1.0),
  17343. new BABYLON.Color3(0.9, 0.0, 1.0),
  17344. new BABYLON.Color3(0.2, 0.0, 1.0),
  17345. new BABYLON.Color3(1.0, 0.9, 1.0),
  17346. new BABYLON.Color3(0.1, 0.1, 1.0),
  17347. new BABYLON.Color3(0.9, 0.9, 1.0)
  17348. ];
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17354. get: function () {
  17355. return [
  17356. new BABYLON.Color3(0.5, 1.0, 0.0),
  17357. new BABYLON.Color3(0.5, 1.0, 0.0),
  17358. new BABYLON.Color3(0.3, 0.4, 0.0),
  17359. new BABYLON.Color3(0.5, 1.0, 0.0),
  17360. new BABYLON.Color3(0.2, 0.0, 0.0),
  17361. new BABYLON.Color3(0.5, 1.0, 0.0)
  17362. ];
  17363. },
  17364. enumerable: true,
  17365. configurable: true
  17366. });
  17367. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17368. get: function () {
  17369. return [
  17370. new BABYLON.Color3(0.5, 0.0, 0.1),
  17371. new BABYLON.Color3(0.9, 0.0, 0.0),
  17372. new BABYLON.Color3(0.2, 0.0, 0.0),
  17373. new BABYLON.Color3(1.0, 0.9, 0.0),
  17374. new BABYLON.Color3(0.1, 0.1, 0.1),
  17375. new BABYLON.Color3(0.9, 0.9, 0.9)
  17376. ];
  17377. },
  17378. enumerable: true,
  17379. configurable: true
  17380. });
  17381. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17382. get: function () {
  17383. return [
  17384. new BABYLON.Color3(0.1, 0.0, 0.5),
  17385. new BABYLON.Color3(0.0, 0.0, 0.5),
  17386. new BABYLON.Color3(0.1, 0.0, 0.2),
  17387. new BABYLON.Color3(0.0, 0.0, 1.0),
  17388. new BABYLON.Color3(0.1, 0.2, 0.3),
  17389. new BABYLON.Color3(0.0, 0.2, 0.9)
  17390. ];
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17396. get: function () {
  17397. return this._fireColors;
  17398. },
  17399. set: function (value) {
  17400. this._fireColors = value;
  17401. this.updateShaderUniforms();
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17407. get: function () {
  17408. return this._time;
  17409. },
  17410. set: function (value) {
  17411. this._time = value;
  17412. this.updateShaderUniforms();
  17413. },
  17414. enumerable: true,
  17415. configurable: true
  17416. });
  17417. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17418. get: function () {
  17419. return this._speed;
  17420. },
  17421. set: function (value) {
  17422. this._speed = value;
  17423. this.updateShaderUniforms();
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17429. get: function () {
  17430. return this._alphaThreshold;
  17431. },
  17432. set: function (value) {
  17433. this._alphaThreshold = value;
  17434. this.updateShaderUniforms();
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. return FireProceduralTexture;
  17440. })(BABYLON.ProceduralTexture);
  17441. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17442. var CloudProceduralTexture = (function (_super) {
  17443. __extends(CloudProceduralTexture, _super);
  17444. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17445. _super.call(this, name, size, "cloudtexture", scene, fallbackTexture, generateMipMaps);
  17446. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17447. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17448. this.updateShaderUniforms();
  17449. this.refreshRate = 0;
  17450. }
  17451. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17452. this.setColor4("skyColor", this._skyColor);
  17453. this.setColor4("cloudColor", this._cloudColor);
  17454. };
  17455. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17456. get: function () {
  17457. return this._skyColor;
  17458. },
  17459. set: function (value) {
  17460. this._skyColor = value;
  17461. this.updateShaderUniforms();
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17467. get: function () {
  17468. return this._cloudColor;
  17469. },
  17470. set: function (value) {
  17471. this._cloudColor = value;
  17472. this.updateShaderUniforms();
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. return CloudProceduralTexture;
  17478. })(BABYLON.ProceduralTexture);
  17479. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17480. var GrassProceduralTexture = (function (_super) {
  17481. __extends(GrassProceduralTexture, _super);
  17482. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17483. _super.call(this, name, size, "grasstexture", scene, fallbackTexture, generateMipMaps);
  17484. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17485. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17486. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17487. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17488. this._grassColors = [
  17489. new BABYLON.Color3(0.29, 0.38, 0.02),
  17490. new BABYLON.Color3(0.36, 0.49, 0.09),
  17491. new BABYLON.Color3(0.51, 0.6, 0.28)
  17492. ];
  17493. this.updateShaderUniforms();
  17494. this.refreshRate = 0;
  17495. }
  17496. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17497. this.setColor3("herb1Color", this._grassColors[0]);
  17498. this.setColor3("herb2Color", this._grassColors[1]);
  17499. this.setColor3("herb3Color", this._grassColors[2]);
  17500. this.setColor3("groundColor", this._groundColor);
  17501. };
  17502. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17503. get: function () {
  17504. return this._grassColors;
  17505. },
  17506. set: function (value) {
  17507. this._grassColors = value;
  17508. this.updateShaderUniforms();
  17509. },
  17510. enumerable: true,
  17511. configurable: true
  17512. });
  17513. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17514. get: function () {
  17515. return this._groundColor;
  17516. },
  17517. set: function (value) {
  17518. this.groundColor = value;
  17519. this.updateShaderUniforms();
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. return GrassProceduralTexture;
  17525. })(BABYLON.ProceduralTexture);
  17526. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17527. var RoadProceduralTexture = (function (_super) {
  17528. __extends(RoadProceduralTexture, _super);
  17529. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17530. _super.call(this, name, size, "roadtexture", scene, fallbackTexture, generateMipMaps);
  17531. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17532. this.updateShaderUniforms();
  17533. this.refreshRate = 0;
  17534. }
  17535. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17536. this.setColor3("roadColor", this._roadColor);
  17537. };
  17538. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17539. get: function () {
  17540. return this._roadColor;
  17541. },
  17542. set: function (value) {
  17543. this._roadColor = value;
  17544. this.updateShaderUniforms();
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. return RoadProceduralTexture;
  17550. })(BABYLON.ProceduralTexture);
  17551. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17552. var BrickProceduralTexture = (function (_super) {
  17553. __extends(BrickProceduralTexture, _super);
  17554. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17555. _super.call(this, name, size, "bricktexture", scene, fallbackTexture, generateMipMaps);
  17556. this._numberOfBricksHeight = 15;
  17557. this._numberOfBricksWidth = 5;
  17558. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17559. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17560. this.updateShaderUniforms();
  17561. this.refreshRate = 0;
  17562. }
  17563. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17564. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17565. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17566. this.setColor3("brickColor", this._brickColor);
  17567. this.setColor3("jointColor", this._jointColor);
  17568. };
  17569. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17570. get: function () {
  17571. return this._numberOfBricksHeight;
  17572. },
  17573. set: function (value) {
  17574. this._numberOfBricksHeight = value;
  17575. this.updateShaderUniforms();
  17576. },
  17577. enumerable: true,
  17578. configurable: true
  17579. });
  17580. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17581. get: function () {
  17582. return this._numberOfBricksWidth;
  17583. },
  17584. set: function (value) {
  17585. this._numberOfBricksWidth = value;
  17586. this.updateShaderUniforms();
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17592. get: function () {
  17593. return this._jointColor;
  17594. },
  17595. set: function (value) {
  17596. this._jointColor = value;
  17597. this.updateShaderUniforms();
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17603. get: function () {
  17604. return this._brickColor;
  17605. },
  17606. set: function (value) {
  17607. this._brickColor = value;
  17608. this.updateShaderUniforms();
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. return BrickProceduralTexture;
  17614. })(BABYLON.ProceduralTexture);
  17615. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17616. var MarbleProceduralTexture = (function (_super) {
  17617. __extends(MarbleProceduralTexture, _super);
  17618. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17619. _super.call(this, name, size, "marbletexture", scene, fallbackTexture, generateMipMaps);
  17620. this._numberOfTilesHeight = 3;
  17621. this._numberOfTilesWidth = 3;
  17622. this._amplitude = 9.0;
  17623. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17624. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17625. this.updateShaderUniforms();
  17626. this.refreshRate = 0;
  17627. }
  17628. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17629. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17630. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17631. this.setFloat("amplitude", this._amplitude);
  17632. this.setColor3("marbleColor", this._marbleColor);
  17633. this.setColor3("jointColor", this._jointColor);
  17634. };
  17635. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17636. get: function () {
  17637. return this._numberOfTilesHeight;
  17638. },
  17639. set: function (value) {
  17640. this._numberOfTilesHeight = value;
  17641. this.updateShaderUniforms();
  17642. },
  17643. enumerable: true,
  17644. configurable: true
  17645. });
  17646. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17647. get: function () {
  17648. return this._numberOfTilesWidth;
  17649. },
  17650. set: function (value) {
  17651. this._numberOfTilesWidth = value;
  17652. this.updateShaderUniforms();
  17653. },
  17654. enumerable: true,
  17655. configurable: true
  17656. });
  17657. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17658. get: function () {
  17659. return this._jointColor;
  17660. },
  17661. set: function (value) {
  17662. this._jointColor = value;
  17663. this.updateShaderUniforms();
  17664. },
  17665. enumerable: true,
  17666. configurable: true
  17667. });
  17668. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17669. get: function () {
  17670. return this._marbleColor;
  17671. },
  17672. set: function (value) {
  17673. this._marbleColor = value;
  17674. this.updateShaderUniforms();
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. return MarbleProceduralTexture;
  17680. })(BABYLON.ProceduralTexture);
  17681. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17682. })(BABYLON || (BABYLON = {}));
  17683. var BABYLON;
  17684. (function (BABYLON) {
  17685. var EffectFallbacks = (function () {
  17686. function EffectFallbacks() {
  17687. this._defines = {};
  17688. this._currentRank = 32;
  17689. this._maxRank = -1;
  17690. }
  17691. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17692. if (!this._defines[rank]) {
  17693. if (rank < this._currentRank) {
  17694. this._currentRank = rank;
  17695. }
  17696. if (rank > this._maxRank) {
  17697. this._maxRank = rank;
  17698. }
  17699. this._defines[rank] = new Array();
  17700. }
  17701. this._defines[rank].push(define);
  17702. };
  17703. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  17704. this._meshRank = rank;
  17705. this._mesh = mesh;
  17706. if (rank > this._maxRank) {
  17707. this._maxRank = rank;
  17708. }
  17709. };
  17710. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17711. get: function () {
  17712. return this._currentRank <= this._maxRank;
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17718. var currentFallbacks = this._defines[this._currentRank];
  17719. for (var index = 0; index < currentFallbacks.length; index++) {
  17720. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17721. }
  17722. if (this._mesh && this._currentRank === this._meshRank) {
  17723. this._mesh.computeBonesUsingShaders = false;
  17724. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  17725. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  17726. }
  17727. this._currentRank++;
  17728. return currentDefines;
  17729. };
  17730. return EffectFallbacks;
  17731. })();
  17732. BABYLON.EffectFallbacks = EffectFallbacks;
  17733. var Effect = (function () {
  17734. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17735. var _this = this;
  17736. this._isReady = false;
  17737. this._compilationError = "";
  17738. this._valueCache = [];
  17739. this._engine = engine;
  17740. this.name = baseName;
  17741. this.defines = defines;
  17742. this._uniformsNames = uniformsNames.concat(samplers);
  17743. this._samplers = samplers;
  17744. this._attributesNames = attributesNames;
  17745. this.onError = onError;
  17746. this.onCompiled = onCompiled;
  17747. var vertexSource;
  17748. var fragmentSource;
  17749. if (baseName.vertexElement) {
  17750. vertexSource = document.getElementById(baseName.vertexElement);
  17751. if (!vertexSource) {
  17752. vertexSource = baseName.vertexElement;
  17753. }
  17754. }
  17755. else {
  17756. vertexSource = baseName.vertex || baseName;
  17757. }
  17758. if (baseName.fragmentElement) {
  17759. fragmentSource = document.getElementById(baseName.fragmentElement);
  17760. if (!fragmentSource) {
  17761. fragmentSource = baseName.fragmentElement;
  17762. }
  17763. }
  17764. else {
  17765. fragmentSource = baseName.fragment || baseName;
  17766. }
  17767. this._loadVertexShader(vertexSource, function (vertexCode) {
  17768. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17769. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17770. });
  17771. });
  17772. }
  17773. // Properties
  17774. Effect.prototype.isReady = function () {
  17775. return this._isReady;
  17776. };
  17777. Effect.prototype.getProgram = function () {
  17778. return this._program;
  17779. };
  17780. Effect.prototype.getAttributesNames = function () {
  17781. return this._attributesNames;
  17782. };
  17783. Effect.prototype.getAttributeLocation = function (index) {
  17784. return this._attributes[index];
  17785. };
  17786. Effect.prototype.getAttributeLocationByName = function (name) {
  17787. var index = this._attributesNames.indexOf(name);
  17788. return this._attributes[index];
  17789. };
  17790. Effect.prototype.getAttributesCount = function () {
  17791. return this._attributes.length;
  17792. };
  17793. Effect.prototype.getUniformIndex = function (uniformName) {
  17794. return this._uniformsNames.indexOf(uniformName);
  17795. };
  17796. Effect.prototype.getUniform = function (uniformName) {
  17797. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17798. };
  17799. Effect.prototype.getSamplers = function () {
  17800. return this._samplers;
  17801. };
  17802. Effect.prototype.getCompilationError = function () {
  17803. return this._compilationError;
  17804. };
  17805. // Methods
  17806. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17807. // DOM element ?
  17808. if (vertex instanceof HTMLElement) {
  17809. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17810. callback(vertexCode);
  17811. return;
  17812. }
  17813. // Is in local store ?
  17814. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17815. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17816. return;
  17817. }
  17818. var vertexShaderUrl;
  17819. if (vertex[0] === "." || vertex[0] === "/") {
  17820. vertexShaderUrl = vertex;
  17821. }
  17822. else {
  17823. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17824. }
  17825. // Vertex shader
  17826. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17827. };
  17828. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17829. // DOM element ?
  17830. if (fragment instanceof HTMLElement) {
  17831. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17832. callback(fragmentCode);
  17833. return;
  17834. }
  17835. // Is in local store ?
  17836. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17837. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17838. return;
  17839. }
  17840. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17841. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17842. return;
  17843. }
  17844. var fragmentShaderUrl;
  17845. if (fragment[0] === "." || fragment[0] === "/") {
  17846. fragmentShaderUrl = fragment;
  17847. }
  17848. else {
  17849. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17850. }
  17851. // Fragment shader
  17852. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17853. };
  17854. Effect.prototype._dumpShadersName = function () {
  17855. if (this.name.vertexElement) {
  17856. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17857. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17858. }
  17859. else if (this.name.vertex) {
  17860. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17861. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17862. }
  17863. else {
  17864. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17865. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17866. }
  17867. };
  17868. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17869. try {
  17870. var engine = this._engine;
  17871. if (!engine.getCaps().highPrecisionShaderSupported) {
  17872. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17873. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17874. }
  17875. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17876. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17877. this._attributes = engine.getAttributes(this._program, attributesNames);
  17878. for (var index = 0; index < this._samplers.length; index++) {
  17879. var sampler = this.getUniform(this._samplers[index]);
  17880. if (sampler == null) {
  17881. this._samplers.splice(index, 1);
  17882. index--;
  17883. }
  17884. }
  17885. engine.bindSamplers(this);
  17886. this._isReady = true;
  17887. if (this.onCompiled) {
  17888. this.onCompiled(this);
  17889. }
  17890. }
  17891. catch (e) {
  17892. // Is it a problem with precision?
  17893. if (e.message.indexOf("highp") !== -1) {
  17894. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17895. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17896. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17897. return;
  17898. }
  17899. // Let's go through fallbacks then
  17900. if (fallbacks && fallbacks.isMoreFallbacks) {
  17901. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  17902. this._dumpShadersName();
  17903. defines = fallbacks.reduce(defines);
  17904. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17905. }
  17906. else {
  17907. BABYLON.Tools.Error("Unable to compile effect: ");
  17908. this._dumpShadersName();
  17909. BABYLON.Tools.Error("Defines: " + defines);
  17910. BABYLON.Tools.Error("Error: " + e.message);
  17911. this._compilationError = e.message;
  17912. if (this.onError) {
  17913. this.onError(this, this._compilationError);
  17914. }
  17915. }
  17916. }
  17917. };
  17918. Object.defineProperty(Effect.prototype, "isSupported", {
  17919. get: function () {
  17920. return this._compilationError === "";
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Effect.prototype._bindTexture = function (channel, texture) {
  17926. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17927. };
  17928. Effect.prototype.setTexture = function (channel, texture) {
  17929. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17930. };
  17931. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17932. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17933. };
  17934. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17935. if (!this._valueCache[uniformName]) {
  17936. this._valueCache[uniformName] = new BABYLON.Matrix();
  17937. }
  17938. for (var index = 0; index < 16; index++) {
  17939. this._valueCache[uniformName].m[index] = matrix.m[index];
  17940. }
  17941. };
  17942. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17943. if (!this._valueCache[uniformName]) {
  17944. this._valueCache[uniformName] = [x, y];
  17945. return;
  17946. }
  17947. this._valueCache[uniformName][0] = x;
  17948. this._valueCache[uniformName][1] = y;
  17949. };
  17950. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17951. if (!this._valueCache[uniformName]) {
  17952. this._valueCache[uniformName] = [x, y, z];
  17953. return;
  17954. }
  17955. this._valueCache[uniformName][0] = x;
  17956. this._valueCache[uniformName][1] = y;
  17957. this._valueCache[uniformName][2] = z;
  17958. };
  17959. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17960. if (!this._valueCache[uniformName]) {
  17961. this._valueCache[uniformName] = [x, y, z, w];
  17962. return;
  17963. }
  17964. this._valueCache[uniformName][0] = x;
  17965. this._valueCache[uniformName][1] = y;
  17966. this._valueCache[uniformName][2] = z;
  17967. this._valueCache[uniformName][3] = w;
  17968. };
  17969. Effect.prototype.setArray = function (uniformName, array) {
  17970. this._engine.setArray(this.getUniform(uniformName), array);
  17971. return this;
  17972. };
  17973. Effect.prototype.setArray2 = function (uniformName, array) {
  17974. this._engine.setArray2(this.getUniform(uniformName), array);
  17975. return this;
  17976. };
  17977. Effect.prototype.setArray3 = function (uniformName, array) {
  17978. this._engine.setArray3(this.getUniform(uniformName), array);
  17979. return this;
  17980. };
  17981. Effect.prototype.setArray4 = function (uniformName, array) {
  17982. this._engine.setArray4(this.getUniform(uniformName), array);
  17983. return this;
  17984. };
  17985. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17986. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17987. return this;
  17988. };
  17989. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17990. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17991. return this;
  17992. this._cacheMatrix(uniformName, matrix);
  17993. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17994. return this;
  17995. };
  17996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  17997. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  17998. return this;
  17999. };
  18000. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18001. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18002. return this;
  18003. };
  18004. Effect.prototype.setFloat = function (uniformName, value) {
  18005. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18006. return this;
  18007. this._valueCache[uniformName] = value;
  18008. this._engine.setFloat(this.getUniform(uniformName), value);
  18009. return this;
  18010. };
  18011. Effect.prototype.setBool = function (uniformName, bool) {
  18012. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18013. return this;
  18014. this._valueCache[uniformName] = bool;
  18015. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18016. return this;
  18017. };
  18018. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18019. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18020. return this;
  18021. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18022. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18023. return this;
  18024. };
  18025. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18026. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18027. return this;
  18028. this._cacheFloat2(uniformName, x, y);
  18029. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18030. return this;
  18031. };
  18032. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18033. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18034. return this;
  18035. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18036. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18037. return this;
  18038. };
  18039. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18040. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18041. return this;
  18042. this._cacheFloat3(uniformName, x, y, z);
  18043. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18044. return this;
  18045. };
  18046. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18047. 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)
  18048. return this;
  18049. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18050. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18051. return this;
  18052. };
  18053. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18054. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18055. return this;
  18056. this._cacheFloat4(uniformName, x, y, z, w);
  18057. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18058. return this;
  18059. };
  18060. Effect.prototype.setColor3 = function (uniformName, color3) {
  18061. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18062. return this;
  18063. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18064. this._engine.setColor3(this.getUniform(uniformName), color3);
  18065. return this;
  18066. };
  18067. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18068. 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)
  18069. return this;
  18070. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18071. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18072. return this;
  18073. };
  18074. // Statics
  18075. Effect.ShadersStore = {};
  18076. return Effect;
  18077. })();
  18078. BABYLON.Effect = Effect;
  18079. })(BABYLON || (BABYLON = {}));
  18080. var BABYLON;
  18081. (function (BABYLON) {
  18082. var MaterialDefines = (function () {
  18083. function MaterialDefines() {
  18084. }
  18085. MaterialDefines.prototype.isEqual = function (other) {
  18086. for (var index = 0; index < this._keys.length; index++) {
  18087. var prop = this._keys[index];
  18088. if (this[prop] !== other[prop]) {
  18089. return false;
  18090. }
  18091. }
  18092. return true;
  18093. };
  18094. MaterialDefines.prototype.cloneTo = function (other) {
  18095. for (var index = 0; index < this._keys.length; index++) {
  18096. var prop = this._keys[index];
  18097. other[prop] = this[prop];
  18098. }
  18099. };
  18100. MaterialDefines.prototype.reset = function () {
  18101. for (var index = 0; index < this._keys.length; index++) {
  18102. var prop = this._keys[index];
  18103. if (typeof (this[prop]) === "number") {
  18104. this[prop] = 0;
  18105. }
  18106. else {
  18107. this[prop] = false;
  18108. }
  18109. }
  18110. };
  18111. MaterialDefines.prototype.toString = function () {
  18112. var result = "";
  18113. for (var index = 0; index < this._keys.length; index++) {
  18114. var prop = this._keys[index];
  18115. if (typeof (this[prop]) === "number") {
  18116. result += "#define " + prop + " " + this[prop] + "\n";
  18117. }
  18118. else if (this[prop]) {
  18119. result += "#define " + prop + "\n";
  18120. }
  18121. }
  18122. return result;
  18123. };
  18124. return MaterialDefines;
  18125. })();
  18126. BABYLON.MaterialDefines = MaterialDefines;
  18127. var Material = (function () {
  18128. function Material(name, scene, doNotAdd) {
  18129. this.name = name;
  18130. this.checkReadyOnEveryCall = false;
  18131. this.checkReadyOnlyOnce = false;
  18132. this.state = "";
  18133. this.alpha = 1.0;
  18134. this.backFaceCulling = true;
  18135. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18136. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18137. this.disableDepthWrite = false;
  18138. this.fogEnabled = true;
  18139. this._wasPreviouslyReady = false;
  18140. this._fillMode = Material.TriangleFillMode;
  18141. this.pointSize = 1.0;
  18142. this.zOffset = 0;
  18143. this.id = name;
  18144. this._scene = scene;
  18145. if (!doNotAdd) {
  18146. scene.materials.push(this);
  18147. }
  18148. }
  18149. Object.defineProperty(Material, "TriangleFillMode", {
  18150. get: function () {
  18151. return Material._TriangleFillMode;
  18152. },
  18153. enumerable: true,
  18154. configurable: true
  18155. });
  18156. Object.defineProperty(Material, "WireFrameFillMode", {
  18157. get: function () {
  18158. return Material._WireFrameFillMode;
  18159. },
  18160. enumerable: true,
  18161. configurable: true
  18162. });
  18163. Object.defineProperty(Material, "PointFillMode", {
  18164. get: function () {
  18165. return Material._PointFillMode;
  18166. },
  18167. enumerable: true,
  18168. configurable: true
  18169. });
  18170. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18171. get: function () {
  18172. return Material._ClockWiseSideOrientation;
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18178. get: function () {
  18179. return Material._CounterClockWiseSideOrientation;
  18180. },
  18181. enumerable: true,
  18182. configurable: true
  18183. });
  18184. Object.defineProperty(Material.prototype, "wireframe", {
  18185. get: function () {
  18186. return this._fillMode === Material.WireFrameFillMode;
  18187. },
  18188. set: function (value) {
  18189. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18190. },
  18191. enumerable: true,
  18192. configurable: true
  18193. });
  18194. Object.defineProperty(Material.prototype, "pointsCloud", {
  18195. get: function () {
  18196. return this._fillMode === Material.PointFillMode;
  18197. },
  18198. set: function (value) {
  18199. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18200. },
  18201. enumerable: true,
  18202. configurable: true
  18203. });
  18204. Object.defineProperty(Material.prototype, "fillMode", {
  18205. get: function () {
  18206. return this._fillMode;
  18207. },
  18208. set: function (value) {
  18209. this._fillMode = value;
  18210. },
  18211. enumerable: true,
  18212. configurable: true
  18213. });
  18214. Material.prototype.isReady = function (mesh, useInstances) {
  18215. return true;
  18216. };
  18217. Material.prototype.getEffect = function () {
  18218. return this._effect;
  18219. };
  18220. Material.prototype.getScene = function () {
  18221. return this._scene;
  18222. };
  18223. Material.prototype.needAlphaBlending = function () {
  18224. return (this.alpha < 1.0);
  18225. };
  18226. Material.prototype.needAlphaTesting = function () {
  18227. return false;
  18228. };
  18229. Material.prototype.getAlphaTestTexture = function () {
  18230. return null;
  18231. };
  18232. Material.prototype.trackCreation = function (onCompiled, onError) {
  18233. };
  18234. Material.prototype._preBind = function () {
  18235. var engine = this._scene.getEngine();
  18236. engine.enableEffect(this._effect);
  18237. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18238. };
  18239. Material.prototype.bind = function (world, mesh) {
  18240. this._scene._cachedMaterial = this;
  18241. if (this.onBind) {
  18242. this.onBind(this, mesh);
  18243. }
  18244. if (this.disableDepthWrite) {
  18245. var engine = this._scene.getEngine();
  18246. this._cachedDepthWriteState = engine.getDepthWrite();
  18247. engine.setDepthWrite(false);
  18248. }
  18249. };
  18250. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18251. };
  18252. Material.prototype.unbind = function () {
  18253. if (this.disableDepthWrite) {
  18254. var engine = this._scene.getEngine();
  18255. engine.setDepthWrite(this._cachedDepthWriteState);
  18256. }
  18257. };
  18258. Material.prototype.clone = function (name) {
  18259. return null;
  18260. };
  18261. Material.prototype.getBindedMeshes = function () {
  18262. var result = new Array();
  18263. for (var index = 0; index < this._scene.meshes.length; index++) {
  18264. var mesh = this._scene.meshes[index];
  18265. if (mesh.material === this) {
  18266. result.push(mesh);
  18267. }
  18268. }
  18269. return result;
  18270. };
  18271. Material.prototype.dispose = function (forceDisposeEffect) {
  18272. // Animations
  18273. this.getScene().stopAnimation(this);
  18274. // Remove from scene
  18275. var index = this._scene.materials.indexOf(this);
  18276. if (index >= 0) {
  18277. this._scene.materials.splice(index, 1);
  18278. }
  18279. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18280. if (forceDisposeEffect && this._effect) {
  18281. this._scene.getEngine()._releaseEffect(this._effect);
  18282. this._effect = null;
  18283. }
  18284. // Remove from meshes
  18285. for (index = 0; index < this._scene.meshes.length; index++) {
  18286. var mesh = this._scene.meshes[index];
  18287. if (mesh.material === this) {
  18288. mesh.material = null;
  18289. }
  18290. }
  18291. // Callback
  18292. if (this.onDispose) {
  18293. this.onDispose();
  18294. }
  18295. };
  18296. Material.prototype.copyTo = function (other) {
  18297. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18298. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18299. other.alpha = this.alpha;
  18300. other.fillMode = this.fillMode;
  18301. other.backFaceCulling = this.backFaceCulling;
  18302. other.wireframe = this.wireframe;
  18303. other.fogEnabled = this.fogEnabled;
  18304. other.wireframe = this.wireframe;
  18305. other.zOffset = this.zOffset;
  18306. other.alphaMode = this.alphaMode;
  18307. other.sideOrientation = this.sideOrientation;
  18308. other.disableDepthWrite = this.disableDepthWrite;
  18309. other.pointSize = this.pointSize;
  18310. other.pointsCloud = this.pointsCloud;
  18311. };
  18312. Material._TriangleFillMode = 0;
  18313. Material._WireFrameFillMode = 1;
  18314. Material._PointFillMode = 2;
  18315. Material._ClockWiseSideOrientation = 0;
  18316. Material._CounterClockWiseSideOrientation = 1;
  18317. return Material;
  18318. })();
  18319. BABYLON.Material = Material;
  18320. })(BABYLON || (BABYLON = {}));
  18321. var BABYLON;
  18322. (function (BABYLON) {
  18323. var maxSimultaneousLights = 4;
  18324. var FresnelParameters = (function () {
  18325. function FresnelParameters() {
  18326. this.isEnabled = true;
  18327. this.leftColor = BABYLON.Color3.White();
  18328. this.rightColor = BABYLON.Color3.Black();
  18329. this.bias = 0;
  18330. this.power = 1;
  18331. }
  18332. FresnelParameters.prototype.clone = function () {
  18333. var newFresnelParameters = new FresnelParameters();
  18334. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18335. return new FresnelParameters;
  18336. };
  18337. return FresnelParameters;
  18338. })();
  18339. BABYLON.FresnelParameters = FresnelParameters;
  18340. var StandardMaterialDefines = (function (_super) {
  18341. __extends(StandardMaterialDefines, _super);
  18342. function StandardMaterialDefines() {
  18343. _super.call(this);
  18344. this.DIFFUSE = false;
  18345. this.AMBIENT = false;
  18346. this.OPACITY = false;
  18347. this.OPACITYRGB = false;
  18348. this.REFLECTION = false;
  18349. this.EMISSIVE = false;
  18350. this.SPECULAR = false;
  18351. this.BUMP = false;
  18352. this.SPECULAROVERALPHA = false;
  18353. this.CLIPPLANE = false;
  18354. this.ALPHATEST = false;
  18355. this.ALPHAFROMDIFFUSE = false;
  18356. this.POINTSIZE = false;
  18357. this.FOG = false;
  18358. this.LIGHT0 = false;
  18359. this.LIGHT1 = false;
  18360. this.LIGHT2 = false;
  18361. this.LIGHT3 = false;
  18362. this.SPOTLIGHT0 = false;
  18363. this.SPOTLIGHT1 = false;
  18364. this.SPOTLIGHT2 = false;
  18365. this.SPOTLIGHT3 = false;
  18366. this.HEMILIGHT0 = false;
  18367. this.HEMILIGHT1 = false;
  18368. this.HEMILIGHT2 = false;
  18369. this.HEMILIGHT3 = false;
  18370. this.POINTLIGHT0 = false;
  18371. this.POINTLIGHT1 = false;
  18372. this.POINTLIGHT2 = false;
  18373. this.POINTLIGHT3 = false;
  18374. this.DIRLIGHT0 = false;
  18375. this.DIRLIGHT1 = false;
  18376. this.DIRLIGHT2 = false;
  18377. this.DIRLIGHT3 = false;
  18378. this.SPECULARTERM = false;
  18379. this.SHADOW0 = false;
  18380. this.SHADOW1 = false;
  18381. this.SHADOW2 = false;
  18382. this.SHADOW3 = false;
  18383. this.SHADOWS = false;
  18384. this.SHADOWVSM0 = false;
  18385. this.SHADOWVSM1 = false;
  18386. this.SHADOWVSM2 = false;
  18387. this.SHADOWVSM3 = false;
  18388. this.SHADOWPCF0 = false;
  18389. this.SHADOWPCF1 = false;
  18390. this.SHADOWPCF2 = false;
  18391. this.SHADOWPCF3 = false;
  18392. this.DIFFUSEFRESNEL = false;
  18393. this.OPACITYFRESNEL = false;
  18394. this.REFLECTIONFRESNEL = false;
  18395. this.EMISSIVEFRESNEL = false;
  18396. this.FRESNEL = false;
  18397. this.NORMAL = false;
  18398. this.UV1 = false;
  18399. this.UV2 = false;
  18400. this.VERTEXCOLOR = false;
  18401. this.VERTEXALPHA = false;
  18402. this.NUM_BONE_INFLUENCERS = 0;
  18403. this.BonesPerMesh = 0;
  18404. this.INSTANCES = false;
  18405. this.GLOSSINESS = false;
  18406. this.ROUGHNESS = false;
  18407. this.EMISSIVEASILLUMINATION = false;
  18408. this.LINKEMISSIVEWITHDIFFUSE = false;
  18409. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18410. this.LIGHTMAP = false;
  18411. this.USELIGHTMAPASSHADOWMAP = false;
  18412. this.REFLECTIONMAP_3D = false;
  18413. this.REFLECTIONMAP_SPHERICAL = false;
  18414. this.REFLECTIONMAP_PLANAR = false;
  18415. this.REFLECTIONMAP_CUBIC = false;
  18416. this.REFLECTIONMAP_PROJECTION = false;
  18417. this.REFLECTIONMAP_SKYBOX = false;
  18418. this.REFLECTIONMAP_EXPLICIT = false;
  18419. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18420. this.INVERTCUBICMAP = false;
  18421. this._keys = Object.keys(this);
  18422. }
  18423. return StandardMaterialDefines;
  18424. })(BABYLON.MaterialDefines);
  18425. var StandardMaterial = (function (_super) {
  18426. __extends(StandardMaterial, _super);
  18427. function StandardMaterial(name, scene) {
  18428. var _this = this;
  18429. _super.call(this, name, scene);
  18430. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18431. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18432. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18433. this.specularPower = 64;
  18434. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18435. this.useAlphaFromDiffuseTexture = false;
  18436. this.useEmissiveAsIllumination = false;
  18437. this.linkEmissiveWithDiffuse = false;
  18438. this.useReflectionFresnelFromSpecular = false;
  18439. this.useSpecularOverAlpha = true;
  18440. this.disableLighting = false;
  18441. this.roughness = 0;
  18442. this.useLightmapAsShadowmap = false;
  18443. this.useGlossinessFromSpecularMapAlpha = false;
  18444. this._renderTargets = new BABYLON.SmartArray(16);
  18445. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18446. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18447. this._defines = new StandardMaterialDefines();
  18448. this._cachedDefines = new StandardMaterialDefines();
  18449. this._cachedDefines.BonesPerMesh = -1;
  18450. this.getRenderTargetTextures = function () {
  18451. _this._renderTargets.reset();
  18452. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18453. _this._renderTargets.push(_this.reflectionTexture);
  18454. }
  18455. return _this._renderTargets;
  18456. };
  18457. }
  18458. StandardMaterial.prototype.needAlphaBlending = function () {
  18459. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18460. };
  18461. StandardMaterial.prototype.needAlphaTesting = function () {
  18462. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18463. };
  18464. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18465. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18466. };
  18467. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18468. return this.diffuseTexture;
  18469. };
  18470. // Methods
  18471. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18472. if (!mesh) {
  18473. return true;
  18474. }
  18475. if (this._defines.INSTANCES !== useInstances) {
  18476. return false;
  18477. }
  18478. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18479. return true;
  18480. }
  18481. return false;
  18482. };
  18483. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18484. var lightIndex = 0;
  18485. var needNormals = false;
  18486. for (var index = 0; index < scene.lights.length; index++) {
  18487. var light = scene.lights[index];
  18488. if (!light.isEnabled()) {
  18489. continue;
  18490. }
  18491. // Excluded check
  18492. if (light._excludedMeshesIds.length > 0) {
  18493. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18494. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18495. if (excludedMesh) {
  18496. light.excludedMeshes.push(excludedMesh);
  18497. }
  18498. }
  18499. light._excludedMeshesIds = [];
  18500. }
  18501. // Included check
  18502. if (light._includedOnlyMeshesIds.length > 0) {
  18503. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18504. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18505. if (includedOnlyMesh) {
  18506. light.includedOnlyMeshes.push(includedOnlyMesh);
  18507. }
  18508. }
  18509. light._includedOnlyMeshesIds = [];
  18510. }
  18511. if (!light.canAffectMesh(mesh)) {
  18512. continue;
  18513. }
  18514. needNormals = true;
  18515. defines["LIGHT" + lightIndex] = true;
  18516. var type;
  18517. if (light instanceof BABYLON.SpotLight) {
  18518. type = "SPOTLIGHT" + lightIndex;
  18519. }
  18520. else if (light instanceof BABYLON.HemisphericLight) {
  18521. type = "HEMILIGHT" + lightIndex;
  18522. }
  18523. else if (light instanceof BABYLON.PointLight) {
  18524. type = "POINTLIGHT" + lightIndex;
  18525. }
  18526. else {
  18527. type = "DIRLIGHT" + lightIndex;
  18528. }
  18529. defines[type] = true;
  18530. // Specular
  18531. if (!light.specular.equalsFloats(0, 0, 0)) {
  18532. defines["SPECULARTERM"] = true;
  18533. }
  18534. // Shadows
  18535. if (scene.shadowsEnabled) {
  18536. var shadowGenerator = light.getShadowGenerator();
  18537. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18538. defines["SHADOW" + lightIndex] = true;
  18539. defines["SHADOWS"] = true;
  18540. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18541. defines["SHADOWVSM" + lightIndex] = true;
  18542. }
  18543. if (shadowGenerator.usePoissonSampling) {
  18544. defines["SHADOWPCF" + lightIndex] = true;
  18545. }
  18546. }
  18547. }
  18548. lightIndex++;
  18549. if (lightIndex === maxSimultaneousLights)
  18550. break;
  18551. }
  18552. return needNormals;
  18553. };
  18554. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18555. var lightIndex = 0;
  18556. for (var index = 0; index < scene.lights.length; index++) {
  18557. var light = scene.lights[index];
  18558. if (!light.isEnabled()) {
  18559. continue;
  18560. }
  18561. if (!light.canAffectMesh(mesh)) {
  18562. continue;
  18563. }
  18564. if (light instanceof BABYLON.PointLight) {
  18565. // Point Light
  18566. light.transferToEffect(effect, "vLightData" + lightIndex);
  18567. }
  18568. else if (light instanceof BABYLON.DirectionalLight) {
  18569. // Directional Light
  18570. light.transferToEffect(effect, "vLightData" + lightIndex);
  18571. }
  18572. else if (light instanceof BABYLON.SpotLight) {
  18573. // Spot Light
  18574. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18575. }
  18576. else if (light instanceof BABYLON.HemisphericLight) {
  18577. // Hemispheric Light
  18578. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18579. }
  18580. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18581. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18582. if (defines["SPECULARTERM"]) {
  18583. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18584. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18585. }
  18586. // Shadows
  18587. if (scene.shadowsEnabled) {
  18588. var shadowGenerator = light.getShadowGenerator();
  18589. if (mesh.receiveShadows && shadowGenerator) {
  18590. if (!light.needCube()) {
  18591. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18592. }
  18593. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18594. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18595. }
  18596. }
  18597. lightIndex++;
  18598. if (lightIndex === maxSimultaneousLights)
  18599. break;
  18600. }
  18601. };
  18602. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18603. if (this.checkReadyOnlyOnce) {
  18604. if (this._wasPreviouslyReady) {
  18605. return true;
  18606. }
  18607. }
  18608. var scene = this.getScene();
  18609. if (!this.checkReadyOnEveryCall) {
  18610. if (this._renderId === scene.getRenderId()) {
  18611. if (this._checkCache(scene, mesh, useInstances)) {
  18612. return true;
  18613. }
  18614. }
  18615. }
  18616. var engine = scene.getEngine();
  18617. var needNormals = false;
  18618. var needUVs = false;
  18619. this._defines.reset();
  18620. // Textures
  18621. if (scene.texturesEnabled) {
  18622. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18623. if (!this.diffuseTexture.isReady()) {
  18624. return false;
  18625. }
  18626. else {
  18627. needUVs = true;
  18628. this._defines.DIFFUSE = true;
  18629. }
  18630. }
  18631. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18632. if (!this.ambientTexture.isReady()) {
  18633. return false;
  18634. }
  18635. else {
  18636. needUVs = true;
  18637. this._defines.AMBIENT = true;
  18638. }
  18639. }
  18640. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18641. if (!this.opacityTexture.isReady()) {
  18642. return false;
  18643. }
  18644. else {
  18645. needUVs = true;
  18646. this._defines.OPACITY = true;
  18647. if (this.opacityTexture.getAlphaFromRGB) {
  18648. this._defines.OPACITYRGB = true;
  18649. }
  18650. }
  18651. }
  18652. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18653. if (!this.reflectionTexture.isReady()) {
  18654. return false;
  18655. }
  18656. else {
  18657. needNormals = true;
  18658. this._defines.REFLECTION = true;
  18659. if (this.roughness > 0) {
  18660. this._defines.ROUGHNESS = true;
  18661. }
  18662. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18663. this._defines.INVERTCUBICMAP = true;
  18664. }
  18665. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18666. switch (this.reflectionTexture.coordinatesMode) {
  18667. case BABYLON.Texture.CUBIC_MODE:
  18668. case BABYLON.Texture.INVCUBIC_MODE:
  18669. this._defines.REFLECTIONMAP_CUBIC = true;
  18670. break;
  18671. case BABYLON.Texture.EXPLICIT_MODE:
  18672. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18673. break;
  18674. case BABYLON.Texture.PLANAR_MODE:
  18675. this._defines.REFLECTIONMAP_PLANAR = true;
  18676. break;
  18677. case BABYLON.Texture.PROJECTION_MODE:
  18678. this._defines.REFLECTIONMAP_PROJECTION = true;
  18679. break;
  18680. case BABYLON.Texture.SKYBOX_MODE:
  18681. this._defines.REFLECTIONMAP_SKYBOX = true;
  18682. break;
  18683. case BABYLON.Texture.SPHERICAL_MODE:
  18684. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18685. break;
  18686. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18687. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18688. break;
  18689. }
  18690. }
  18691. }
  18692. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18693. if (!this.emissiveTexture.isReady()) {
  18694. return false;
  18695. }
  18696. else {
  18697. needUVs = true;
  18698. this._defines.EMISSIVE = true;
  18699. }
  18700. }
  18701. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18702. if (!this.lightmapTexture.isReady()) {
  18703. return false;
  18704. }
  18705. else {
  18706. needUVs = true;
  18707. this._defines.LIGHTMAP = true;
  18708. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18709. }
  18710. }
  18711. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18712. if (!this.specularTexture.isReady()) {
  18713. return false;
  18714. }
  18715. else {
  18716. needUVs = true;
  18717. this._defines.SPECULAR = true;
  18718. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18719. }
  18720. }
  18721. }
  18722. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18723. if (!this.bumpTexture.isReady()) {
  18724. return false;
  18725. }
  18726. else {
  18727. needUVs = true;
  18728. this._defines.BUMP = true;
  18729. }
  18730. }
  18731. // Effect
  18732. if (scene.clipPlane) {
  18733. this._defines.CLIPPLANE = true;
  18734. }
  18735. if (engine.getAlphaTesting()) {
  18736. this._defines.ALPHATEST = true;
  18737. }
  18738. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18739. this._defines.ALPHAFROMDIFFUSE = true;
  18740. }
  18741. if (this.useEmissiveAsIllumination) {
  18742. this._defines.EMISSIVEASILLUMINATION = true;
  18743. }
  18744. if (this.linkEmissiveWithDiffuse) {
  18745. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18746. }
  18747. if (this.useReflectionFresnelFromSpecular) {
  18748. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18749. }
  18750. // Point size
  18751. if (this.pointsCloud || scene.forcePointsCloud) {
  18752. this._defines.POINTSIZE = true;
  18753. }
  18754. // Fog
  18755. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18756. this._defines.FOG = true;
  18757. }
  18758. if (scene.lightsEnabled && !this.disableLighting) {
  18759. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  18760. }
  18761. if (StandardMaterial.FresnelEnabled) {
  18762. // Fresnel
  18763. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18764. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18765. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18766. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18767. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18768. this._defines.DIFFUSEFRESNEL = true;
  18769. }
  18770. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18771. this._defines.OPACITYFRESNEL = true;
  18772. }
  18773. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18774. this._defines.REFLECTIONFRESNEL = true;
  18775. }
  18776. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18777. this._defines.EMISSIVEFRESNEL = true;
  18778. }
  18779. needNormals = true;
  18780. this._defines.FRESNEL = true;
  18781. }
  18782. }
  18783. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18784. this._defines.SPECULAROVERALPHA = true;
  18785. }
  18786. // Attribs
  18787. if (mesh) {
  18788. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18789. this._defines.NORMAL = true;
  18790. }
  18791. if (needUVs) {
  18792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18793. this._defines.UV1 = true;
  18794. }
  18795. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18796. this._defines.UV2 = true;
  18797. }
  18798. }
  18799. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18800. this._defines.VERTEXCOLOR = true;
  18801. if (mesh.hasVertexAlpha) {
  18802. this._defines.VERTEXALPHA = true;
  18803. }
  18804. }
  18805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18806. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  18807. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18808. }
  18809. // Instances
  18810. if (useInstances) {
  18811. this._defines.INSTANCES = true;
  18812. }
  18813. }
  18814. // Get correct effect
  18815. if (!this._defines.isEqual(this._cachedDefines)) {
  18816. this._defines.cloneTo(this._cachedDefines);
  18817. scene.resetCachedMaterial();
  18818. // Fallbacks
  18819. var fallbacks = new BABYLON.EffectFallbacks();
  18820. if (this._defines.REFLECTION) {
  18821. fallbacks.addFallback(0, "REFLECTION");
  18822. }
  18823. if (this._defines.SPECULAR) {
  18824. fallbacks.addFallback(0, "SPECULAR");
  18825. }
  18826. if (this._defines.BUMP) {
  18827. fallbacks.addFallback(0, "BUMP");
  18828. }
  18829. if (this._defines.SPECULAROVERALPHA) {
  18830. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18831. }
  18832. if (this._defines.FOG) {
  18833. fallbacks.addFallback(1, "FOG");
  18834. }
  18835. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18836. if (!this._defines["LIGHT" + lightIndex]) {
  18837. continue;
  18838. }
  18839. if (lightIndex > 0) {
  18840. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18841. }
  18842. if (this._defines["SHADOW" + lightIndex]) {
  18843. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18844. }
  18845. if (this._defines["SHADOWPCF" + lightIndex]) {
  18846. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18847. }
  18848. if (this._defines["SHADOWVSM" + lightIndex]) {
  18849. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18850. }
  18851. }
  18852. if (this._defines.SPECULARTERM) {
  18853. fallbacks.addFallback(0, "SPECULARTERM");
  18854. }
  18855. if (this._defines.DIFFUSEFRESNEL) {
  18856. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18857. }
  18858. if (this._defines.OPACITYFRESNEL) {
  18859. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18860. }
  18861. if (this._defines.REFLECTIONFRESNEL) {
  18862. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18863. }
  18864. if (this._defines.EMISSIVEFRESNEL) {
  18865. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18866. }
  18867. if (this._defines.FRESNEL) {
  18868. fallbacks.addFallback(4, "FRESNEL");
  18869. }
  18870. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18871. fallbacks.addCPUSkinningFallback(0, mesh);
  18872. }
  18873. //Attributes
  18874. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18875. if (this._defines.NORMAL) {
  18876. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18877. }
  18878. if (this._defines.UV1) {
  18879. attribs.push(BABYLON.VertexBuffer.UVKind);
  18880. }
  18881. if (this._defines.UV2) {
  18882. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18883. }
  18884. if (this._defines.VERTEXCOLOR) {
  18885. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18886. }
  18887. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18888. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18889. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18890. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  18891. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  18892. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  18893. }
  18894. }
  18895. if (this._defines.INSTANCES) {
  18896. attribs.push("world0");
  18897. attribs.push("world1");
  18898. attribs.push("world2");
  18899. attribs.push("world3");
  18900. }
  18901. // Legacy browser patch
  18902. var shaderName = "default";
  18903. if (!scene.getEngine().getCaps().standardDerivatives) {
  18904. shaderName = "legacydefault";
  18905. }
  18906. var join = this._defines.toString();
  18907. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18908. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18909. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18910. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18911. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18912. "vFogInfos", "vFogColor", "pointSize",
  18913. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18914. "mBones",
  18915. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18916. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18917. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18918. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18919. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18920. ], join, fallbacks, this.onCompiled, this.onError);
  18921. }
  18922. if (!this._effect.isReady()) {
  18923. return false;
  18924. }
  18925. this._renderId = scene.getRenderId();
  18926. this._wasPreviouslyReady = true;
  18927. if (mesh) {
  18928. if (!mesh._materialDefines) {
  18929. mesh._materialDefines = new StandardMaterialDefines();
  18930. }
  18931. this._defines.cloneTo(mesh._materialDefines);
  18932. }
  18933. return true;
  18934. };
  18935. StandardMaterial.prototype.unbind = function () {
  18936. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18937. this._effect.setTexture("reflection2DSampler", null);
  18938. }
  18939. _super.prototype.unbind.call(this);
  18940. };
  18941. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18942. this._effect.setMatrix("world", world);
  18943. };
  18944. StandardMaterial.prototype.bind = function (world, mesh) {
  18945. var scene = this.getScene();
  18946. // Matrices
  18947. this.bindOnlyWorldMatrix(world);
  18948. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18949. // Bones
  18950. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18951. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18952. }
  18953. if (scene.getCachedMaterial() !== this) {
  18954. if (StandardMaterial.FresnelEnabled) {
  18955. // Fresnel
  18956. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18957. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18958. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18959. }
  18960. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18961. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18962. }
  18963. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18964. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18965. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18966. }
  18967. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18968. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18969. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18970. }
  18971. }
  18972. // Textures
  18973. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18974. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18975. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18976. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18977. }
  18978. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18979. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18980. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18981. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18982. }
  18983. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18984. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18985. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18986. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18987. }
  18988. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18989. if (this.reflectionTexture.isCube) {
  18990. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18991. }
  18992. else {
  18993. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18994. }
  18995. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18996. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18997. }
  18998. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18999. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19000. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19001. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19002. }
  19003. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19004. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19005. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19006. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19007. }
  19008. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19009. this._effect.setTexture("specularSampler", this.specularTexture);
  19010. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19011. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19012. }
  19013. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19014. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19015. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19016. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19017. }
  19018. // Clip plane
  19019. if (scene.clipPlane) {
  19020. var clipPlane = scene.clipPlane;
  19021. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19022. }
  19023. // Point size
  19024. if (this.pointsCloud) {
  19025. this._effect.setFloat("pointSize", this.pointSize);
  19026. }
  19027. // Colors
  19028. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19029. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19030. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19031. if (this._defines.SPECULARTERM) {
  19032. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19033. }
  19034. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19035. }
  19036. // Diffuse
  19037. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19038. // Lights
  19039. if (scene.lightsEnabled && !this.disableLighting) {
  19040. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19041. }
  19042. // View
  19043. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19044. this._effect.setMatrix("view", scene.getViewMatrix());
  19045. }
  19046. // Fog
  19047. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19048. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19049. this._effect.setColor3("vFogColor", scene.fogColor);
  19050. }
  19051. _super.prototype.bind.call(this, world, mesh);
  19052. };
  19053. StandardMaterial.prototype.getAnimatables = function () {
  19054. var results = [];
  19055. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19056. results.push(this.diffuseTexture);
  19057. }
  19058. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19059. results.push(this.ambientTexture);
  19060. }
  19061. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19062. results.push(this.opacityTexture);
  19063. }
  19064. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19065. results.push(this.reflectionTexture);
  19066. }
  19067. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19068. results.push(this.emissiveTexture);
  19069. }
  19070. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19071. results.push(this.specularTexture);
  19072. }
  19073. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19074. results.push(this.bumpTexture);
  19075. }
  19076. return results;
  19077. };
  19078. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19079. if (this.diffuseTexture) {
  19080. this.diffuseTexture.dispose();
  19081. }
  19082. if (this.ambientTexture) {
  19083. this.ambientTexture.dispose();
  19084. }
  19085. if (this.opacityTexture) {
  19086. this.opacityTexture.dispose();
  19087. }
  19088. if (this.reflectionTexture) {
  19089. this.reflectionTexture.dispose();
  19090. }
  19091. if (this.emissiveTexture) {
  19092. this.emissiveTexture.dispose();
  19093. }
  19094. if (this.specularTexture) {
  19095. this.specularTexture.dispose();
  19096. }
  19097. if (this.bumpTexture) {
  19098. this.bumpTexture.dispose();
  19099. }
  19100. _super.prototype.dispose.call(this, forceDisposeEffect);
  19101. };
  19102. StandardMaterial.prototype.clone = function (name) {
  19103. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19104. // Base material
  19105. this.copyTo(newStandardMaterial);
  19106. // Standard material
  19107. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19108. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19109. }
  19110. if (this.ambientTexture && this.ambientTexture.clone) {
  19111. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19112. }
  19113. if (this.opacityTexture && this.opacityTexture.clone) {
  19114. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19115. }
  19116. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19117. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19118. }
  19119. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19120. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19121. }
  19122. if (this.specularTexture && this.specularTexture.clone) {
  19123. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19124. }
  19125. if (this.bumpTexture && this.bumpTexture.clone) {
  19126. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19127. }
  19128. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19129. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19130. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19131. }
  19132. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19133. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19134. newStandardMaterial.specularColor = this.specularColor.clone();
  19135. newStandardMaterial.specularPower = this.specularPower;
  19136. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19137. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19138. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19139. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19140. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19141. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19142. newStandardMaterial.roughness = this.roughness;
  19143. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19144. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19145. }
  19146. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19147. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19148. }
  19149. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19150. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19151. }
  19152. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19153. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19154. }
  19155. return newStandardMaterial;
  19156. };
  19157. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19158. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19159. // Statics
  19160. // Flags used to enable or disable a type of texture for all Standard Materials
  19161. StandardMaterial.DiffuseTextureEnabled = true;
  19162. StandardMaterial.AmbientTextureEnabled = true;
  19163. StandardMaterial.OpacityTextureEnabled = true;
  19164. StandardMaterial.ReflectionTextureEnabled = true;
  19165. StandardMaterial.EmissiveTextureEnabled = true;
  19166. StandardMaterial.SpecularTextureEnabled = true;
  19167. StandardMaterial.BumpTextureEnabled = true;
  19168. StandardMaterial.FresnelEnabled = true;
  19169. StandardMaterial.LightmapEnabled = true;
  19170. return StandardMaterial;
  19171. })(BABYLON.Material);
  19172. BABYLON.StandardMaterial = StandardMaterial;
  19173. })(BABYLON || (BABYLON = {}));
  19174. var BABYLON;
  19175. (function (BABYLON) {
  19176. var MultiMaterial = (function (_super) {
  19177. __extends(MultiMaterial, _super);
  19178. function MultiMaterial(name, scene) {
  19179. _super.call(this, name, scene, true);
  19180. this.subMaterials = new Array();
  19181. scene.multiMaterials.push(this);
  19182. }
  19183. // Properties
  19184. MultiMaterial.prototype.getSubMaterial = function (index) {
  19185. if (index < 0 || index >= this.subMaterials.length) {
  19186. return this.getScene().defaultMaterial;
  19187. }
  19188. return this.subMaterials[index];
  19189. };
  19190. // Methods
  19191. MultiMaterial.prototype.isReady = function (mesh) {
  19192. for (var index = 0; index < this.subMaterials.length; index++) {
  19193. var subMaterial = this.subMaterials[index];
  19194. if (subMaterial) {
  19195. if (!this.subMaterials[index].isReady(mesh)) {
  19196. return false;
  19197. }
  19198. }
  19199. }
  19200. return true;
  19201. };
  19202. MultiMaterial.prototype.clone = function (name) {
  19203. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19204. for (var index = 0; index < this.subMaterials.length; index++) {
  19205. var subMaterial = this.subMaterials[index];
  19206. newMultiMaterial.subMaterials.push(subMaterial);
  19207. }
  19208. return newMultiMaterial;
  19209. };
  19210. return MultiMaterial;
  19211. })(BABYLON.Material);
  19212. BABYLON.MultiMaterial = MultiMaterial;
  19213. })(BABYLON || (BABYLON = {}));
  19214. var BABYLON;
  19215. (function (BABYLON) {
  19216. var SceneLoader = (function () {
  19217. function SceneLoader() {
  19218. }
  19219. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19220. get: function () {
  19221. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19222. },
  19223. set: function (value) {
  19224. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19230. get: function () {
  19231. return SceneLoader._ShowLoadingScreen;
  19232. },
  19233. set: function (value) {
  19234. SceneLoader._ShowLoadingScreen = value;
  19235. },
  19236. enumerable: true,
  19237. configurable: true
  19238. });
  19239. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19240. var dotPosition = sceneFilename.lastIndexOf(".");
  19241. var queryStringPosition = sceneFilename.indexOf("?");
  19242. if (queryStringPosition === -1) {
  19243. queryStringPosition = sceneFilename.length;
  19244. }
  19245. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19246. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19247. var plugin = this._registeredPlugins[index];
  19248. if (plugin.extensions.indexOf(extension) !== -1) {
  19249. return plugin;
  19250. }
  19251. }
  19252. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19253. };
  19254. // Public functions
  19255. SceneLoader.RegisterPlugin = function (plugin) {
  19256. plugin.extensions = plugin.extensions.toLowerCase();
  19257. SceneLoader._registeredPlugins.push(plugin);
  19258. };
  19259. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19260. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19261. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19262. return;
  19263. }
  19264. var loadingToken = {};
  19265. scene._addPendingData(loadingToken);
  19266. var manifestChecked = function (success) {
  19267. scene.database = database;
  19268. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19269. var importMeshFromData = function (data) {
  19270. var meshes = [];
  19271. var particleSystems = [];
  19272. var skeletons = [];
  19273. try {
  19274. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19275. if (onerror) {
  19276. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19277. }
  19278. scene._removePendingData(loadingToken);
  19279. return;
  19280. }
  19281. }
  19282. catch (e) {
  19283. if (onerror) {
  19284. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19285. }
  19286. scene._removePendingData(loadingToken);
  19287. return;
  19288. }
  19289. if (onsuccess) {
  19290. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19291. onsuccess(meshes, particleSystems, skeletons);
  19292. scene._removePendingData(loadingToken);
  19293. }
  19294. };
  19295. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19296. // Direct load
  19297. importMeshFromData(sceneFilename.substr(5));
  19298. return;
  19299. }
  19300. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19301. importMeshFromData(data);
  19302. }, progressCallBack, database);
  19303. };
  19304. if (scene.getEngine().enableOfflineSupport) {
  19305. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19306. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19307. }
  19308. else {
  19309. manifestChecked(true);
  19310. }
  19311. };
  19312. /**
  19313. * Load a scene
  19314. * @param rootUrl a string that defines the root url for scene and resources
  19315. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19316. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19317. */
  19318. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19319. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19320. };
  19321. /**
  19322. * Append a scene
  19323. * @param rootUrl a string that defines the root url for scene and resources
  19324. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19325. * @param scene is the instance of BABYLON.Scene to append to
  19326. */
  19327. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19328. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19329. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19330. return;
  19331. }
  19332. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19333. var database;
  19334. var loadingToken = {};
  19335. scene._addPendingData(loadingToken);
  19336. if (SceneLoader.ShowLoadingScreen) {
  19337. scene.getEngine().displayLoadingUI();
  19338. }
  19339. var loadSceneFromData = function (data) {
  19340. scene.database = database;
  19341. if (!plugin.load(scene, data, rootUrl)) {
  19342. if (onerror) {
  19343. onerror(scene);
  19344. }
  19345. scene._removePendingData(loadingToken);
  19346. scene.getEngine().hideLoadingUI();
  19347. return;
  19348. }
  19349. if (onsuccess) {
  19350. onsuccess(scene);
  19351. }
  19352. scene._removePendingData(loadingToken);
  19353. if (SceneLoader.ShowLoadingScreen) {
  19354. scene.executeWhenReady(function () {
  19355. scene.getEngine().hideLoadingUI();
  19356. });
  19357. }
  19358. };
  19359. var manifestChecked = function (success) {
  19360. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19361. };
  19362. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19363. // Direct load
  19364. loadSceneFromData(sceneFilename.substr(5));
  19365. return;
  19366. }
  19367. if (rootUrl.indexOf("file:") === -1) {
  19368. if (scene.getEngine().enableOfflineSupport) {
  19369. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19370. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19371. }
  19372. else {
  19373. manifestChecked(true);
  19374. }
  19375. }
  19376. else {
  19377. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19378. }
  19379. };
  19380. // Flags
  19381. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19382. SceneLoader._ShowLoadingScreen = true;
  19383. // Members
  19384. SceneLoader._registeredPlugins = new Array();
  19385. return SceneLoader;
  19386. })();
  19387. BABYLON.SceneLoader = SceneLoader;
  19388. ;
  19389. })(BABYLON || (BABYLON = {}));
  19390. var BABYLON;
  19391. (function (BABYLON) {
  19392. var Internals;
  19393. (function (Internals) {
  19394. var checkColors4 = function (colors, count) {
  19395. // Check if color3 was used
  19396. if (colors.length === count * 3) {
  19397. var colors4 = [];
  19398. for (var index = 0; index < colors.length; index += 3) {
  19399. var newIndex = (index / 3) * 4;
  19400. colors4[newIndex] = colors[index];
  19401. colors4[newIndex + 1] = colors[index + 1];
  19402. colors4[newIndex + 2] = colors[index + 2];
  19403. colors4[newIndex + 3] = 1.0;
  19404. }
  19405. return colors4;
  19406. }
  19407. return colors;
  19408. };
  19409. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19410. var texture = null;
  19411. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19412. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19413. texture.name = parsedTexture.name;
  19414. texture.hasAlpha = parsedTexture.hasAlpha;
  19415. texture.level = parsedTexture.level;
  19416. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19417. }
  19418. return texture;
  19419. };
  19420. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19421. if (parsedTexture.isCube) {
  19422. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19423. }
  19424. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19425. return null;
  19426. }
  19427. var texture;
  19428. if (parsedTexture.mirrorPlane) {
  19429. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19430. texture._waitingRenderList = parsedTexture.renderList;
  19431. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19432. }
  19433. else if (parsedTexture.isRenderTarget) {
  19434. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19435. texture._waitingRenderList = parsedTexture.renderList;
  19436. }
  19437. else {
  19438. if (parsedTexture.base64String) {
  19439. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19440. }
  19441. else {
  19442. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19443. }
  19444. }
  19445. texture.name = parsedTexture.name;
  19446. texture.hasAlpha = parsedTexture.hasAlpha;
  19447. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19448. texture.level = parsedTexture.level;
  19449. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19450. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19451. texture.uOffset = parsedTexture.uOffset;
  19452. texture.vOffset = parsedTexture.vOffset;
  19453. texture.uScale = parsedTexture.uScale;
  19454. texture.vScale = parsedTexture.vScale;
  19455. texture.uAng = parsedTexture.uAng;
  19456. texture.vAng = parsedTexture.vAng;
  19457. texture.wAng = parsedTexture.wAng;
  19458. texture.wrapU = parsedTexture.wrapU;
  19459. texture.wrapV = parsedTexture.wrapV;
  19460. // Animations
  19461. if (parsedTexture.animations) {
  19462. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19463. var parsedAnimation = parsedTexture.animations[animationIndex];
  19464. texture.animations.push(parseAnimation(parsedAnimation));
  19465. }
  19466. }
  19467. return texture;
  19468. };
  19469. var parseSkeleton = function (parsedSkeleton, scene) {
  19470. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19471. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19472. var parsedBone = parsedSkeleton.bones[index];
  19473. var parentBone = null;
  19474. if (parsedBone.parentBoneIndex > -1) {
  19475. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19476. }
  19477. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19478. if (parsedBone.animation) {
  19479. bone.animations.push(parseAnimation(parsedBone.animation));
  19480. }
  19481. }
  19482. return skeleton;
  19483. };
  19484. var parseFresnelParameters = function (parsedFresnelParameters) {
  19485. var fresnelParameters = new BABYLON.FresnelParameters();
  19486. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19487. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19488. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19489. fresnelParameters.bias = parsedFresnelParameters.bias;
  19490. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19491. return fresnelParameters;
  19492. };
  19493. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19494. var material;
  19495. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19496. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19497. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19498. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19499. material.specularPower = parsedMaterial.specularPower;
  19500. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19501. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19502. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19503. material.alpha = parsedMaterial.alpha;
  19504. material.id = parsedMaterial.id;
  19505. if (parsedMaterial.disableDepthWrite) {
  19506. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19507. }
  19508. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19509. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19510. material.wireframe = parsedMaterial.wireframe;
  19511. if (parsedMaterial.diffuseTexture) {
  19512. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19513. }
  19514. if (parsedMaterial.diffuseFresnelParameters) {
  19515. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19516. }
  19517. if (parsedMaterial.ambientTexture) {
  19518. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19519. }
  19520. if (parsedMaterial.opacityTexture) {
  19521. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19522. }
  19523. if (parsedMaterial.opacityFresnelParameters) {
  19524. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19525. }
  19526. if (parsedMaterial.reflectionTexture) {
  19527. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19528. }
  19529. if (parsedMaterial.reflectionFresnelParameters) {
  19530. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19531. }
  19532. if (parsedMaterial.emissiveTexture) {
  19533. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19534. }
  19535. if (parsedMaterial.lightmapTexture) {
  19536. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19537. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19538. }
  19539. if (parsedMaterial.emissiveFresnelParameters) {
  19540. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19541. }
  19542. if (parsedMaterial.specularTexture) {
  19543. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19544. }
  19545. if (parsedMaterial.bumpTexture) {
  19546. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19547. }
  19548. if (parsedMaterial.checkReadyOnlyOnce) {
  19549. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19550. }
  19551. return material;
  19552. };
  19553. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19554. for (var index = 0; index < parsedData.materials.length; index++) {
  19555. var parsedMaterial = parsedData.materials[index];
  19556. if (parsedMaterial.id === id) {
  19557. return parseMaterial(parsedMaterial, scene, rootUrl);
  19558. }
  19559. }
  19560. return null;
  19561. };
  19562. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19563. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19564. multiMaterial.id = parsedMultiMaterial.id;
  19565. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19566. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19567. var subMatId = parsedMultiMaterial.materials[matIndex];
  19568. if (subMatId) {
  19569. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19570. }
  19571. else {
  19572. multiMaterial.subMaterials.push(null);
  19573. }
  19574. }
  19575. return multiMaterial;
  19576. };
  19577. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19578. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19579. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19580. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19581. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19582. var parsedFlare = parsedLensFlareSystem.flares[index];
  19583. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19584. }
  19585. return lensFlareSystem;
  19586. };
  19587. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19588. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19589. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19590. if (parsedParticleSystem.textureName) {
  19591. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19592. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19593. }
  19594. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19595. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19596. particleSystem.minSize = parsedParticleSystem.minSize;
  19597. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19598. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19599. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19600. particleSystem.emitter = emitter;
  19601. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19602. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19603. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19604. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19605. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19606. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19607. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19608. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19609. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19610. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19611. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19612. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19613. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19614. particleSystem.start();
  19615. return particleSystem;
  19616. };
  19617. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19618. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19619. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19620. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19621. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19622. shadowGenerator.getShadowMap().renderList.push(mesh);
  19623. }
  19624. if (parsedShadowGenerator.usePoissonSampling) {
  19625. shadowGenerator.usePoissonSampling = true;
  19626. }
  19627. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19628. shadowGenerator.useVarianceShadowMap = true;
  19629. }
  19630. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19631. shadowGenerator.useBlurVarianceShadowMap = true;
  19632. if (parsedShadowGenerator.blurScale) {
  19633. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19634. }
  19635. if (parsedShadowGenerator.blurBoxOffset) {
  19636. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19637. }
  19638. }
  19639. if (parsedShadowGenerator.bias !== undefined) {
  19640. shadowGenerator.bias = parsedShadowGenerator.bias;
  19641. }
  19642. return shadowGenerator;
  19643. };
  19644. var parseAnimation = function (parsedAnimation) {
  19645. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19646. var dataType = parsedAnimation.dataType;
  19647. var keys = [];
  19648. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19649. var key = parsedAnimation.keys[index];
  19650. var data;
  19651. switch (dataType) {
  19652. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19653. data = key.values[0];
  19654. break;
  19655. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19656. data = BABYLON.Quaternion.FromArray(key.values);
  19657. break;
  19658. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19659. data = BABYLON.Matrix.FromArray(key.values);
  19660. break;
  19661. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19662. default:
  19663. data = BABYLON.Vector3.FromArray(key.values);
  19664. break;
  19665. }
  19666. keys.push({
  19667. frame: key.frame,
  19668. value: data
  19669. });
  19670. }
  19671. animation.setKeys(keys);
  19672. return animation;
  19673. };
  19674. var parseLight = function (parsedLight, scene) {
  19675. var light;
  19676. switch (parsedLight.type) {
  19677. case 0:
  19678. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19679. break;
  19680. case 1:
  19681. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19682. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19683. break;
  19684. case 2:
  19685. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19686. break;
  19687. case 3:
  19688. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19689. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19690. break;
  19691. }
  19692. light.id = parsedLight.id;
  19693. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19694. if (parsedLight.intensity !== undefined) {
  19695. light.intensity = parsedLight.intensity;
  19696. }
  19697. if (parsedLight.range) {
  19698. light.range = parsedLight.range;
  19699. }
  19700. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19701. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19702. if (parsedLight.excludedMeshesIds) {
  19703. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19704. }
  19705. // Parent
  19706. if (parsedLight.parentId) {
  19707. light._waitingParentId = parsedLight.parentId;
  19708. }
  19709. if (parsedLight.includedOnlyMeshesIds) {
  19710. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19711. }
  19712. // Animations
  19713. if (parsedLight.animations) {
  19714. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19715. var parsedAnimation = parsedLight.animations[animationIndex];
  19716. light.animations.push(parseAnimation(parsedAnimation));
  19717. }
  19718. }
  19719. if (parsedLight.autoAnimate) {
  19720. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19721. }
  19722. };
  19723. var parseCamera = function (parsedCamera, scene) {
  19724. var camera;
  19725. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19726. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19727. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19728. var alpha = parsedCamera.alpha;
  19729. var beta = parsedCamera.beta;
  19730. var radius = parsedCamera.radius;
  19731. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19732. var interaxial_distance = parsedCamera.interaxial_distance;
  19733. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19734. }
  19735. else {
  19736. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19737. }
  19738. }
  19739. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19740. interaxial_distance = parsedCamera.interaxial_distance;
  19741. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19742. }
  19743. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19744. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19745. }
  19746. else if (parsedCamera.type === "FollowCamera") {
  19747. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19748. camera.heightOffset = parsedCamera.heightOffset;
  19749. camera.radius = parsedCamera.radius;
  19750. camera.rotationOffset = parsedCamera.rotationOffset;
  19751. if (lockedTargetMesh)
  19752. camera.target = lockedTargetMesh;
  19753. }
  19754. else if (parsedCamera.type === "GamepadCamera") {
  19755. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19756. }
  19757. else if (parsedCamera.type === "TouchCamera") {
  19758. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19759. }
  19760. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19761. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19762. }
  19763. else if (parsedCamera.type === "WebVRFreeCamera") {
  19764. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19765. }
  19766. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19767. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19768. }
  19769. else {
  19770. // Free Camera is the default value
  19771. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19772. }
  19773. // apply 3d rig, when found
  19774. if (parsedCamera.cameraRigMode) {
  19775. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19776. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19777. }
  19778. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19779. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19780. camera.lockedTarget = lockedTargetMesh;
  19781. }
  19782. camera.id = parsedCamera.id;
  19783. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19784. // Parent
  19785. if (parsedCamera.parentId) {
  19786. camera._waitingParentId = parsedCamera.parentId;
  19787. }
  19788. // Target
  19789. if (parsedCamera.target) {
  19790. if (camera.setTarget) {
  19791. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19792. }
  19793. else {
  19794. //For ArcRotate
  19795. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19796. }
  19797. }
  19798. else {
  19799. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19800. }
  19801. camera.fov = parsedCamera.fov;
  19802. camera.minZ = parsedCamera.minZ;
  19803. camera.maxZ = parsedCamera.maxZ;
  19804. camera.speed = parsedCamera.speed;
  19805. camera.inertia = parsedCamera.inertia;
  19806. camera.checkCollisions = parsedCamera.checkCollisions;
  19807. camera.applyGravity = parsedCamera.applyGravity;
  19808. if (parsedCamera.ellipsoid) {
  19809. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19810. }
  19811. // Animations
  19812. if (parsedCamera.animations) {
  19813. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19814. var parsedAnimation = parsedCamera.animations[animationIndex];
  19815. camera.animations.push(parseAnimation(parsedAnimation));
  19816. }
  19817. }
  19818. if (parsedCamera.autoAnimate) {
  19819. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19820. }
  19821. // Layer Mask
  19822. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19823. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19824. }
  19825. else {
  19826. camera.layerMask = 0x0FFFFFFF;
  19827. }
  19828. return camera;
  19829. };
  19830. var parseGeometry = function (parsedGeometry, scene) {
  19831. var id = parsedGeometry.id;
  19832. return scene.getGeometryByID(id);
  19833. };
  19834. var parseBox = function (parsedBox, scene) {
  19835. if (parseGeometry(parsedBox, scene)) {
  19836. return null; // null since geometry could be something else than a box...
  19837. }
  19838. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19839. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19840. scene.pushGeometry(box, true);
  19841. return box;
  19842. };
  19843. var parseSphere = function (parsedSphere, scene) {
  19844. if (parseGeometry(parsedSphere, scene)) {
  19845. return null; // null since geometry could be something else than a sphere...
  19846. }
  19847. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19848. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19849. scene.pushGeometry(sphere, true);
  19850. return sphere;
  19851. };
  19852. var parseCylinder = function (parsedCylinder, scene) {
  19853. if (parseGeometry(parsedCylinder, scene)) {
  19854. return null; // null since geometry could be something else than a cylinder...
  19855. }
  19856. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19857. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19858. scene.pushGeometry(cylinder, true);
  19859. return cylinder;
  19860. };
  19861. var parseTorus = function (parsedTorus, scene) {
  19862. if (parseGeometry(parsedTorus, scene)) {
  19863. return null; // null since geometry could be something else than a torus...
  19864. }
  19865. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19866. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19867. scene.pushGeometry(torus, true);
  19868. return torus;
  19869. };
  19870. var parseGround = function (parsedGround, scene) {
  19871. if (parseGeometry(parsedGround, scene)) {
  19872. return null; // null since geometry could be something else than a ground...
  19873. }
  19874. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19875. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19876. scene.pushGeometry(ground, true);
  19877. return ground;
  19878. };
  19879. var parsePlane = function (parsedPlane, scene) {
  19880. if (parseGeometry(parsedPlane, scene)) {
  19881. return null; // null since geometry could be something else than a plane...
  19882. }
  19883. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19884. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19885. scene.pushGeometry(plane, true);
  19886. return plane;
  19887. };
  19888. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19889. if (parseGeometry(parsedTorusKnot, scene)) {
  19890. return null; // null since geometry could be something else than a torusKnot...
  19891. }
  19892. 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);
  19893. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19894. scene.pushGeometry(torusKnot, true);
  19895. return torusKnot;
  19896. };
  19897. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19898. if (parseGeometry(parsedVertexData, scene)) {
  19899. return null; // null since geometry could be a primitive
  19900. }
  19901. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19902. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19903. if (parsedVertexData.delayLoadingFile) {
  19904. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19905. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19906. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19907. geometry._delayInfo = [];
  19908. if (parsedVertexData.hasUVs) {
  19909. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19910. }
  19911. if (parsedVertexData.hasUVs2) {
  19912. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19913. }
  19914. if (parsedVertexData.hasUVs3) {
  19915. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19916. }
  19917. if (parsedVertexData.hasUVs4) {
  19918. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19919. }
  19920. if (parsedVertexData.hasUVs5) {
  19921. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19922. }
  19923. if (parsedVertexData.hasUVs6) {
  19924. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19925. }
  19926. if (parsedVertexData.hasColors) {
  19927. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19928. }
  19929. if (parsedVertexData.hasMatricesIndices) {
  19930. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19931. }
  19932. if (parsedVertexData.hasMatricesWeights) {
  19933. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19934. }
  19935. geometry._delayLoadingFunction = importVertexData;
  19936. }
  19937. else {
  19938. importVertexData(parsedVertexData, geometry);
  19939. }
  19940. scene.pushGeometry(geometry, true);
  19941. return geometry;
  19942. };
  19943. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19944. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19945. mesh.id = parsedMesh.id;
  19946. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19947. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19948. if (parsedMesh.rotationQuaternion) {
  19949. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19950. }
  19951. else if (parsedMesh.rotation) {
  19952. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19953. }
  19954. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19955. if (parsedMesh.localMatrix) {
  19956. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19957. }
  19958. else if (parsedMesh.pivotMatrix) {
  19959. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19960. }
  19961. mesh.setEnabled(parsedMesh.isEnabled);
  19962. mesh.isVisible = parsedMesh.isVisible;
  19963. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19964. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19965. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19966. if (parsedMesh.applyFog !== undefined) {
  19967. mesh.applyFog = parsedMesh.applyFog;
  19968. }
  19969. if (parsedMesh.pickable !== undefined) {
  19970. mesh.isPickable = parsedMesh.pickable;
  19971. }
  19972. if (parsedMesh.alphaIndex !== undefined) {
  19973. mesh.alphaIndex = parsedMesh.alphaIndex;
  19974. }
  19975. mesh.receiveShadows = parsedMesh.receiveShadows;
  19976. mesh.billboardMode = parsedMesh.billboardMode;
  19977. if (parsedMesh.visibility !== undefined) {
  19978. mesh.visibility = parsedMesh.visibility;
  19979. }
  19980. mesh.checkCollisions = parsedMesh.checkCollisions;
  19981. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19982. // freezeWorldMatrix
  19983. if (parsedMesh.freezeWorldMatrix) {
  19984. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19985. }
  19986. // Parent
  19987. if (parsedMesh.parentId) {
  19988. mesh._waitingParentId = parsedMesh.parentId;
  19989. }
  19990. // Actions
  19991. if (parsedMesh.actions !== undefined) {
  19992. mesh._waitingActions = parsedMesh.actions;
  19993. }
  19994. // Geometry
  19995. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19996. if (parsedMesh.delayLoadingFile) {
  19997. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19998. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19999. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20000. if (parsedMesh._binaryInfo) {
  20001. mesh._binaryInfo = parsedMesh._binaryInfo;
  20002. }
  20003. mesh._delayInfo = [];
  20004. if (parsedMesh.hasUVs) {
  20005. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20006. }
  20007. if (parsedMesh.hasUVs2) {
  20008. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20009. }
  20010. if (parsedMesh.hasUVs3) {
  20011. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20012. }
  20013. if (parsedMesh.hasUVs4) {
  20014. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20015. }
  20016. if (parsedMesh.hasUVs5) {
  20017. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20018. }
  20019. if (parsedMesh.hasUVs6) {
  20020. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20021. }
  20022. if (parsedMesh.hasColors) {
  20023. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20024. }
  20025. if (parsedMesh.hasMatricesIndices) {
  20026. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20027. }
  20028. if (parsedMesh.hasMatricesWeights) {
  20029. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20030. }
  20031. mesh._delayLoadingFunction = importGeometry;
  20032. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20033. mesh._checkDelayState();
  20034. }
  20035. }
  20036. else {
  20037. importGeometry(parsedMesh, mesh);
  20038. }
  20039. // Material
  20040. if (parsedMesh.materialId) {
  20041. mesh.setMaterialByID(parsedMesh.materialId);
  20042. }
  20043. else {
  20044. mesh.material = null;
  20045. }
  20046. // Skeleton
  20047. if (parsedMesh.skeletonId > -1) {
  20048. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20049. if (parsedMesh.numBoneInfluencers) {
  20050. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20051. }
  20052. }
  20053. // Physics
  20054. if (parsedMesh.physicsImpostor) {
  20055. if (!scene.isPhysicsEnabled()) {
  20056. scene.enablePhysics();
  20057. }
  20058. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20059. }
  20060. // Animations
  20061. if (parsedMesh.animations) {
  20062. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20063. var parsedAnimation = parsedMesh.animations[animationIndex];
  20064. mesh.animations.push(parseAnimation(parsedAnimation));
  20065. }
  20066. }
  20067. if (parsedMesh.autoAnimate) {
  20068. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20069. }
  20070. // Layer Mask
  20071. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20072. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20073. }
  20074. else {
  20075. mesh.layerMask = 0x0FFFFFFF;
  20076. }
  20077. // Instances
  20078. if (parsedMesh.instances) {
  20079. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20080. var parsedInstance = parsedMesh.instances[index];
  20081. var instance = mesh.createInstance(parsedInstance.name);
  20082. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20083. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20084. if (parsedInstance.rotationQuaternion) {
  20085. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20086. }
  20087. else if (parsedInstance.rotation) {
  20088. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20089. }
  20090. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20091. instance.checkCollisions = mesh.checkCollisions;
  20092. if (parsedMesh.animations) {
  20093. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20094. parsedAnimation = parsedMesh.animations[animationIndex];
  20095. instance.animations.push(parseAnimation(parsedAnimation));
  20096. }
  20097. }
  20098. }
  20099. }
  20100. return mesh;
  20101. };
  20102. var parseActions = function (parsedActions, object, scene) {
  20103. var actionManager = new BABYLON.ActionManager(scene);
  20104. if (object === null)
  20105. scene.actionManager = actionManager;
  20106. else
  20107. object.actionManager = actionManager;
  20108. // instanciate a new object
  20109. var instanciate = function (name, params) {
  20110. var newInstance = Object.create(BABYLON[name].prototype);
  20111. newInstance.constructor.apply(newInstance, params);
  20112. return newInstance;
  20113. };
  20114. var parseParameter = function (name, value, target, propertyPath) {
  20115. if (propertyPath === null) {
  20116. // String, boolean or float
  20117. var floatValue = parseFloat(value);
  20118. if (value === "true" || value === "false")
  20119. return value === "true";
  20120. else
  20121. return isNaN(floatValue) ? value : floatValue;
  20122. }
  20123. var effectiveTarget = propertyPath.split(".");
  20124. var values = value.split(",");
  20125. // Get effective Target
  20126. for (var i = 0; i < effectiveTarget.length; i++) {
  20127. target = target[effectiveTarget[i]];
  20128. }
  20129. // Return appropriate value with its type
  20130. if (typeof (target) === "boolean")
  20131. return values[0] === "true";
  20132. if (typeof (target) === "string")
  20133. return values[0];
  20134. // Parameters with multiple values such as Vector3 etc.
  20135. var split = new Array();
  20136. for (var i = 0; i < values.length; i++)
  20137. split.push(parseFloat(values[i]));
  20138. if (target instanceof BABYLON.Vector3)
  20139. return BABYLON.Vector3.FromArray(split);
  20140. if (target instanceof BABYLON.Vector4)
  20141. return BABYLON.Vector4.FromArray(split);
  20142. if (target instanceof BABYLON.Color3)
  20143. return BABYLON.Color3.FromArray(split);
  20144. if (target instanceof BABYLON.Color4)
  20145. return BABYLON.Color4.FromArray(split);
  20146. return parseFloat(values[0]);
  20147. };
  20148. // traverse graph per trigger
  20149. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20150. if (combineArray === void 0) { combineArray = null; }
  20151. if (parsedAction.detached)
  20152. return;
  20153. var parameters = new Array();
  20154. var target = null;
  20155. var propertyPath = null;
  20156. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20157. // Parameters
  20158. if (parsedAction.type === 2)
  20159. parameters.push(actionManager);
  20160. else
  20161. parameters.push(trigger);
  20162. if (combine) {
  20163. var actions = new Array();
  20164. for (var j = 0; j < parsedAction.combine.length; j++) {
  20165. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20166. }
  20167. parameters.push(actions);
  20168. }
  20169. else {
  20170. for (var i = 0; i < parsedAction.properties.length; i++) {
  20171. var value = parsedAction.properties[i].value;
  20172. var name = parsedAction.properties[i].name;
  20173. var targetType = parsedAction.properties[i].targetType;
  20174. if (name === "target")
  20175. if (targetType !== null && targetType === "SceneProperties")
  20176. value = target = scene;
  20177. else
  20178. value = target = scene.getNodeByName(value);
  20179. else if (name === "parent")
  20180. value = scene.getNodeByName(value);
  20181. else if (name === "sound")
  20182. value = scene.getSoundByName(value);
  20183. else if (name !== "propertyPath") {
  20184. if (parsedAction.type === 2 && name === "operator")
  20185. value = BABYLON.ValueCondition[value];
  20186. else
  20187. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20188. }
  20189. else {
  20190. propertyPath = value;
  20191. }
  20192. parameters.push(value);
  20193. }
  20194. }
  20195. if (combineArray === null) {
  20196. parameters.push(condition);
  20197. }
  20198. else {
  20199. parameters.push(null);
  20200. }
  20201. // If interpolate value action
  20202. if (parsedAction.name === "InterpolateValueAction") {
  20203. var param = parameters[parameters.length - 2];
  20204. parameters[parameters.length - 1] = param;
  20205. parameters[parameters.length - 2] = condition;
  20206. }
  20207. // Action or condition(s) and not CombineAction
  20208. var newAction = instanciate(parsedAction.name, parameters);
  20209. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20210. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20211. if (action)
  20212. action.then(nothing);
  20213. else
  20214. actionManager.registerAction(nothing);
  20215. action = nothing;
  20216. }
  20217. if (combineArray === null) {
  20218. if (newAction instanceof BABYLON.Condition) {
  20219. condition = newAction;
  20220. newAction = action;
  20221. }
  20222. else {
  20223. condition = null;
  20224. if (action)
  20225. action.then(newAction);
  20226. else
  20227. actionManager.registerAction(newAction);
  20228. }
  20229. }
  20230. else {
  20231. combineArray.push(newAction);
  20232. }
  20233. for (var i = 0; i < parsedAction.children.length; i++)
  20234. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20235. };
  20236. // triggers
  20237. for (var i = 0; i < parsedActions.children.length; i++) {
  20238. var triggerParams;
  20239. var trigger = parsedActions.children[i];
  20240. if (trigger.properties.length > 0) {
  20241. var param = trigger.properties[0].value;
  20242. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20243. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20244. }
  20245. else
  20246. triggerParams = BABYLON.ActionManager[trigger.name];
  20247. for (var j = 0; j < trigger.children.length; j++) {
  20248. if (!trigger.detached)
  20249. traverse(trigger.children[j], triggerParams, null, null);
  20250. }
  20251. }
  20252. };
  20253. var parseSound = function (parsedSound, scene, rootUrl) {
  20254. var soundName = parsedSound.name;
  20255. var soundUrl = rootUrl + soundName;
  20256. var options = {
  20257. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20258. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20259. rolloffFactor: parsedSound.rolloffFactor,
  20260. refDistance: parsedSound.refDistance,
  20261. distanceModel: parsedSound.distanceModel,
  20262. playbackRate: parsedSound.playbackRate
  20263. };
  20264. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20265. scene._addPendingData(newSound);
  20266. if (parsedSound.position) {
  20267. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20268. newSound.setPosition(soundPosition);
  20269. }
  20270. if (parsedSound.isDirectional) {
  20271. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20272. if (parsedSound.localDirectionToMesh) {
  20273. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20274. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20275. }
  20276. }
  20277. if (parsedSound.connectedMeshId) {
  20278. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20279. if (connectedMesh) {
  20280. newSound.attachToMesh(connectedMesh);
  20281. }
  20282. }
  20283. };
  20284. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20285. names = (names instanceof Array) ? names : [names];
  20286. for (var i in names) {
  20287. if (mesh.name === names[i]) {
  20288. hierarchyIds.push(mesh.id);
  20289. return true;
  20290. }
  20291. }
  20292. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20293. hierarchyIds.push(mesh.id);
  20294. return true;
  20295. }
  20296. return false;
  20297. };
  20298. var importVertexData = function (parsedVertexData, geometry) {
  20299. var vertexData = new BABYLON.VertexData();
  20300. // positions
  20301. var positions = parsedVertexData.positions;
  20302. if (positions) {
  20303. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20304. }
  20305. // normals
  20306. var normals = parsedVertexData.normals;
  20307. if (normals) {
  20308. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20309. }
  20310. // uvs
  20311. var uvs = parsedVertexData.uvs;
  20312. if (uvs) {
  20313. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20314. }
  20315. // uv2s
  20316. var uv2s = parsedVertexData.uv2s;
  20317. if (uv2s) {
  20318. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20319. }
  20320. // uv3s
  20321. var uv3s = parsedVertexData.uv3s;
  20322. if (uv3s) {
  20323. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20324. }
  20325. // uv4s
  20326. var uv4s = parsedVertexData.uv4s;
  20327. if (uv4s) {
  20328. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20329. }
  20330. // uv5s
  20331. var uv5s = parsedVertexData.uv5s;
  20332. if (uv5s) {
  20333. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20334. }
  20335. // uv6s
  20336. var uv6s = parsedVertexData.uv6s;
  20337. if (uv6s) {
  20338. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20339. }
  20340. // colors
  20341. var colors = parsedVertexData.colors;
  20342. if (colors) {
  20343. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20344. }
  20345. // matricesIndices
  20346. var matricesIndices = parsedVertexData.matricesIndices;
  20347. if (matricesIndices) {
  20348. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20349. }
  20350. // matricesWeights
  20351. var matricesWeights = parsedVertexData.matricesWeights;
  20352. if (matricesWeights) {
  20353. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20354. }
  20355. // indices
  20356. var indices = parsedVertexData.indices;
  20357. if (indices) {
  20358. vertexData.indices = indices;
  20359. }
  20360. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20361. };
  20362. var importGeometry = function (parsedGeometry, mesh) {
  20363. var scene = mesh.getScene();
  20364. // Geometry
  20365. var geometryId = parsedGeometry.geometryId;
  20366. if (geometryId) {
  20367. var geometry = scene.getGeometryByID(geometryId);
  20368. if (geometry) {
  20369. geometry.applyToMesh(mesh);
  20370. }
  20371. }
  20372. else if (parsedGeometry instanceof ArrayBuffer) {
  20373. var binaryInfo = mesh._binaryInfo;
  20374. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20375. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20376. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20377. }
  20378. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20379. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20380. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20381. }
  20382. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20383. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20384. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20385. }
  20386. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20387. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20388. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20389. }
  20390. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20391. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20392. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20393. }
  20394. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20395. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20396. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20397. }
  20398. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20399. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20400. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20401. }
  20402. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20403. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20404. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20405. }
  20406. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20407. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20408. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20409. }
  20410. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20411. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20412. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20413. }
  20414. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20415. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20416. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20417. }
  20418. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20419. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20420. mesh.setIndices(indicesData);
  20421. }
  20422. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20423. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20424. mesh.subMeshes = [];
  20425. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20426. var materialIndex = subMeshesData[(i * 5) + 0];
  20427. var verticesStart = subMeshesData[(i * 5) + 1];
  20428. var verticesCount = subMeshesData[(i * 5) + 2];
  20429. var indexStart = subMeshesData[(i * 5) + 3];
  20430. var indexCount = subMeshesData[(i * 5) + 4];
  20431. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20432. }
  20433. }
  20434. }
  20435. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20436. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20437. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20438. if (parsedGeometry.uvs) {
  20439. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20440. }
  20441. if (parsedGeometry.uvs2) {
  20442. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20443. }
  20444. if (parsedGeometry.uvs3) {
  20445. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20446. }
  20447. if (parsedGeometry.uvs4) {
  20448. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20449. }
  20450. if (parsedGeometry.uvs5) {
  20451. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20452. }
  20453. if (parsedGeometry.uvs6) {
  20454. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20455. }
  20456. if (parsedGeometry.colors) {
  20457. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20458. }
  20459. if (parsedGeometry.matricesIndices) {
  20460. if (!parsedGeometry.matricesIndices._isExpanded) {
  20461. var floatIndices = [];
  20462. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20463. var matricesIndex = parsedGeometry.matricesIndices[i];
  20464. floatIndices.push(matricesIndex & 0x000000FF);
  20465. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20466. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20467. floatIndices.push(matricesIndex >> 24);
  20468. }
  20469. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20470. }
  20471. else {
  20472. delete parsedGeometry.matricesIndices._isExpanded;
  20473. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20474. }
  20475. }
  20476. if (parsedGeometry.matricesIndicesExtra) {
  20477. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  20478. var floatIndices = [];
  20479. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  20480. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  20481. floatIndices.push(matricesIndex & 0x000000FF);
  20482. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20483. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20484. floatIndices.push(matricesIndex >> 24);
  20485. }
  20486. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  20487. }
  20488. else {
  20489. delete parsedGeometry.matricesIndices._isExpanded;
  20490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  20491. }
  20492. }
  20493. if (parsedGeometry.matricesWeights) {
  20494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20495. }
  20496. if (parsedGeometry.matricesWeightsExtra) {
  20497. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  20498. }
  20499. mesh.setIndices(parsedGeometry.indices);
  20500. }
  20501. // SubMeshes
  20502. if (parsedGeometry.subMeshes) {
  20503. mesh.subMeshes = [];
  20504. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20505. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20506. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20507. }
  20508. }
  20509. // Flat shading
  20510. if (mesh._shouldGenerateFlatShading) {
  20511. mesh.convertToFlatShadedMesh();
  20512. delete mesh._shouldGenerateFlatShading;
  20513. }
  20514. // Update
  20515. mesh.computeWorldMatrix(true);
  20516. // Octree
  20517. if (scene._selectionOctree) {
  20518. scene._selectionOctree.addMesh(mesh);
  20519. }
  20520. };
  20521. BABYLON.SceneLoader.RegisterPlugin({
  20522. extensions: ".babylon",
  20523. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20524. var parsedData = JSON.parse(data);
  20525. var loadedSkeletonsIds = [];
  20526. var loadedMaterialsIds = [];
  20527. var hierarchyIds = [];
  20528. for (var index = 0; index < parsedData.meshes.length; index++) {
  20529. var parsedMesh = parsedData.meshes[index];
  20530. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20531. if (meshesNames instanceof Array) {
  20532. // Remove found mesh name from list.
  20533. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20534. }
  20535. //Geometry?
  20536. if (parsedMesh.geometryId) {
  20537. //does the file contain geometries?
  20538. if (parsedData.geometries) {
  20539. //find the correct geometry and add it to the scene
  20540. var found = false;
  20541. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20542. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20543. return;
  20544. }
  20545. else {
  20546. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20547. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20548. switch (geometryType) {
  20549. case "boxes":
  20550. parseBox(parsedGeometryData, scene);
  20551. break;
  20552. case "spheres":
  20553. parseSphere(parsedGeometryData, scene);
  20554. break;
  20555. case "cylinders":
  20556. parseCylinder(parsedGeometryData, scene);
  20557. break;
  20558. case "toruses":
  20559. parseTorus(parsedGeometryData, scene);
  20560. break;
  20561. case "grounds":
  20562. parseGround(parsedGeometryData, scene);
  20563. break;
  20564. case "planes":
  20565. parsePlane(parsedGeometryData, scene);
  20566. break;
  20567. case "torusKnots":
  20568. parseTorusKnot(parsedGeometryData, scene);
  20569. break;
  20570. case "vertexData":
  20571. parseVertexData(parsedGeometryData, scene, rootUrl);
  20572. break;
  20573. }
  20574. found = true;
  20575. }
  20576. });
  20577. }
  20578. });
  20579. if (!found) {
  20580. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20581. }
  20582. }
  20583. }
  20584. // Material ?
  20585. if (parsedMesh.materialId) {
  20586. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20587. if (!materialFound && parsedData.multiMaterials) {
  20588. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20589. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20590. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20591. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20592. var subMatId = parsedMultiMaterial.materials[matIndex];
  20593. loadedMaterialsIds.push(subMatId);
  20594. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20595. }
  20596. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20597. parseMultiMaterial(parsedMultiMaterial, scene);
  20598. materialFound = true;
  20599. break;
  20600. }
  20601. }
  20602. }
  20603. if (!materialFound) {
  20604. loadedMaterialsIds.push(parsedMesh.materialId);
  20605. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20606. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20607. }
  20608. }
  20609. }
  20610. // Skeleton ?
  20611. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20612. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20613. if (!skeletonAlreadyLoaded) {
  20614. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20615. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20616. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20617. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20618. loadedSkeletonsIds.push(parsedSkeleton.id);
  20619. }
  20620. }
  20621. }
  20622. }
  20623. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20624. meshes.push(mesh);
  20625. }
  20626. }
  20627. // Connecting parents
  20628. for (index = 0; index < scene.meshes.length; index++) {
  20629. var currentMesh = scene.meshes[index];
  20630. if (currentMesh._waitingParentId) {
  20631. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20632. currentMesh._waitingParentId = undefined;
  20633. }
  20634. }
  20635. // freeze world matrix application
  20636. for (index = 0; index < scene.meshes.length; index++) {
  20637. var currentMesh = scene.meshes[index];
  20638. if (currentMesh._waitingFreezeWorldMatrix) {
  20639. currentMesh.freezeWorldMatrix();
  20640. currentMesh._waitingFreezeWorldMatrix = undefined;
  20641. }
  20642. }
  20643. // Particles
  20644. if (parsedData.particleSystems) {
  20645. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20646. var parsedParticleSystem = parsedData.particleSystems[index];
  20647. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20648. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20649. }
  20650. }
  20651. }
  20652. return true;
  20653. },
  20654. load: function (scene, data, rootUrl) {
  20655. var parsedData = JSON.parse(data);
  20656. // Scene
  20657. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20658. scene.autoClear = parsedData.autoClear;
  20659. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20660. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20661. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20662. // Fog
  20663. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20664. scene.fogMode = parsedData.fogMode;
  20665. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20666. scene.fogStart = parsedData.fogStart;
  20667. scene.fogEnd = parsedData.fogEnd;
  20668. scene.fogDensity = parsedData.fogDensity;
  20669. }
  20670. // Lights
  20671. for (var index = 0; index < parsedData.lights.length; index++) {
  20672. var parsedLight = parsedData.lights[index];
  20673. parseLight(parsedLight, scene);
  20674. }
  20675. // Materials
  20676. if (parsedData.materials) {
  20677. for (index = 0; index < parsedData.materials.length; index++) {
  20678. var parsedMaterial = parsedData.materials[index];
  20679. parseMaterial(parsedMaterial, scene, rootUrl);
  20680. }
  20681. }
  20682. if (parsedData.multiMaterials) {
  20683. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20684. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20685. parseMultiMaterial(parsedMultiMaterial, scene);
  20686. }
  20687. }
  20688. // Skeletons
  20689. if (parsedData.skeletons) {
  20690. for (index = 0; index < parsedData.skeletons.length; index++) {
  20691. var parsedSkeleton = parsedData.skeletons[index];
  20692. parseSkeleton(parsedSkeleton, scene);
  20693. }
  20694. }
  20695. // Geometries
  20696. var geometries = parsedData.geometries;
  20697. if (geometries) {
  20698. // Boxes
  20699. var boxes = geometries.boxes;
  20700. if (boxes) {
  20701. for (index = 0; index < boxes.length; index++) {
  20702. var parsedBox = boxes[index];
  20703. parseBox(parsedBox, scene);
  20704. }
  20705. }
  20706. // Spheres
  20707. var spheres = geometries.spheres;
  20708. if (spheres) {
  20709. for (index = 0; index < spheres.length; index++) {
  20710. var parsedSphere = spheres[index];
  20711. parseSphere(parsedSphere, scene);
  20712. }
  20713. }
  20714. // Cylinders
  20715. var cylinders = geometries.cylinders;
  20716. if (cylinders) {
  20717. for (index = 0; index < cylinders.length; index++) {
  20718. var parsedCylinder = cylinders[index];
  20719. parseCylinder(parsedCylinder, scene);
  20720. }
  20721. }
  20722. // Toruses
  20723. var toruses = geometries.toruses;
  20724. if (toruses) {
  20725. for (index = 0; index < toruses.length; index++) {
  20726. var parsedTorus = toruses[index];
  20727. parseTorus(parsedTorus, scene);
  20728. }
  20729. }
  20730. // Grounds
  20731. var grounds = geometries.grounds;
  20732. if (grounds) {
  20733. for (index = 0; index < grounds.length; index++) {
  20734. var parsedGround = grounds[index];
  20735. parseGround(parsedGround, scene);
  20736. }
  20737. }
  20738. // Planes
  20739. var planes = geometries.planes;
  20740. if (planes) {
  20741. for (index = 0; index < planes.length; index++) {
  20742. var parsedPlane = planes[index];
  20743. parsePlane(parsedPlane, scene);
  20744. }
  20745. }
  20746. // TorusKnots
  20747. var torusKnots = geometries.torusKnots;
  20748. if (torusKnots) {
  20749. for (index = 0; index < torusKnots.length; index++) {
  20750. var parsedTorusKnot = torusKnots[index];
  20751. parseTorusKnot(parsedTorusKnot, scene);
  20752. }
  20753. }
  20754. // VertexData
  20755. var vertexData = geometries.vertexData;
  20756. if (vertexData) {
  20757. for (index = 0; index < vertexData.length; index++) {
  20758. var parsedVertexData = vertexData[index];
  20759. parseVertexData(parsedVertexData, scene, rootUrl);
  20760. }
  20761. }
  20762. }
  20763. // Meshes
  20764. for (index = 0; index < parsedData.meshes.length; index++) {
  20765. var parsedMesh = parsedData.meshes[index];
  20766. parseMesh(parsedMesh, scene, rootUrl);
  20767. }
  20768. // Cameras
  20769. for (index = 0; index < parsedData.cameras.length; index++) {
  20770. var parsedCamera = parsedData.cameras[index];
  20771. parseCamera(parsedCamera, scene);
  20772. }
  20773. if (parsedData.activeCameraID) {
  20774. scene.setActiveCameraByID(parsedData.activeCameraID);
  20775. }
  20776. // Browsing all the graph to connect the dots
  20777. for (index = 0; index < scene.cameras.length; index++) {
  20778. var camera = scene.cameras[index];
  20779. if (camera._waitingParentId) {
  20780. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20781. camera._waitingParentId = undefined;
  20782. }
  20783. }
  20784. for (index = 0; index < scene.lights.length; index++) {
  20785. var light = scene.lights[index];
  20786. if (light._waitingParentId) {
  20787. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20788. light._waitingParentId = undefined;
  20789. }
  20790. }
  20791. // Sounds
  20792. if (BABYLON.AudioEngine && parsedData.sounds) {
  20793. for (index = 0; index < parsedData.sounds.length; index++) {
  20794. var parsedSound = parsedData.sounds[index];
  20795. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20796. parseSound(parsedSound, scene, rootUrl);
  20797. }
  20798. else {
  20799. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20800. }
  20801. }
  20802. }
  20803. // Connect parents & children and parse actions
  20804. for (index = 0; index < scene.meshes.length; index++) {
  20805. var mesh = scene.meshes[index];
  20806. if (mesh._waitingParentId) {
  20807. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20808. mesh._waitingParentId = undefined;
  20809. }
  20810. if (mesh._waitingActions) {
  20811. parseActions(mesh._waitingActions, mesh, scene);
  20812. mesh._waitingActions = undefined;
  20813. }
  20814. }
  20815. // freeze world matrix application
  20816. for (index = 0; index < scene.meshes.length; index++) {
  20817. var currentMesh = scene.meshes[index];
  20818. if (currentMesh._waitingFreezeWorldMatrix) {
  20819. currentMesh.freezeWorldMatrix();
  20820. currentMesh._waitingFreezeWorldMatrix = undefined;
  20821. }
  20822. }
  20823. // Particles Systems
  20824. if (parsedData.particleSystems) {
  20825. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20826. var parsedParticleSystem = parsedData.particleSystems[index];
  20827. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20828. }
  20829. }
  20830. // Lens flares
  20831. if (parsedData.lensFlareSystems) {
  20832. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20833. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20834. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20835. }
  20836. }
  20837. // Shadows
  20838. if (parsedData.shadowGenerators) {
  20839. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20840. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20841. parseShadowGenerator(parsedShadowGenerator, scene);
  20842. }
  20843. }
  20844. // Actions (scene)
  20845. if (parsedData.actions) {
  20846. parseActions(parsedData.actions, null, scene);
  20847. }
  20848. // Finish
  20849. return true;
  20850. }
  20851. });
  20852. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20853. })(BABYLON || (BABYLON = {}));
  20854. var BABYLON;
  20855. (function (BABYLON) {
  20856. var SpriteManager = (function () {
  20857. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20859. this.name = name;
  20860. this.cellSize = cellSize;
  20861. this.sprites = new Array();
  20862. this.renderingGroupId = 0;
  20863. this.layerMask = 0x0FFFFFFF;
  20864. this.fogEnabled = true;
  20865. this.isPickable = false;
  20866. this._vertexDeclaration = [4, 4, 4, 4];
  20867. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20868. this._capacity = capacity;
  20869. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20870. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20871. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20872. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20873. this._scene = scene;
  20874. this._scene.spriteManagers.push(this);
  20875. // VBO
  20876. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20877. var indices = [];
  20878. var index = 0;
  20879. for (var count = 0; count < capacity; count++) {
  20880. indices.push(index);
  20881. indices.push(index + 1);
  20882. indices.push(index + 2);
  20883. indices.push(index);
  20884. indices.push(index + 2);
  20885. indices.push(index + 3);
  20886. index += 4;
  20887. }
  20888. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20889. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20890. // Effects
  20891. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20892. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20893. }
  20894. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20895. var arrayOffset = index * 16;
  20896. if (offsetX === 0)
  20897. offsetX = this._epsilon;
  20898. else if (offsetX === 1)
  20899. offsetX = 1 - this._epsilon;
  20900. if (offsetY === 0)
  20901. offsetY = this._epsilon;
  20902. else if (offsetY === 1)
  20903. offsetY = 1 - this._epsilon;
  20904. this._vertices[arrayOffset] = sprite.position.x;
  20905. this._vertices[arrayOffset + 1] = sprite.position.y;
  20906. this._vertices[arrayOffset + 2] = sprite.position.z;
  20907. this._vertices[arrayOffset + 3] = sprite.angle;
  20908. this._vertices[arrayOffset + 4] = sprite.width;
  20909. this._vertices[arrayOffset + 5] = sprite.height;
  20910. this._vertices[arrayOffset + 6] = offsetX;
  20911. this._vertices[arrayOffset + 7] = offsetY;
  20912. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20913. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20914. var offset = (sprite.cellIndex / rowSize) >> 0;
  20915. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20916. this._vertices[arrayOffset + 11] = offset;
  20917. // Color
  20918. this._vertices[arrayOffset + 12] = sprite.color.r;
  20919. this._vertices[arrayOffset + 13] = sprite.color.g;
  20920. this._vertices[arrayOffset + 14] = sprite.color.b;
  20921. this._vertices[arrayOffset + 15] = sprite.color.a;
  20922. };
  20923. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20924. var count = Math.min(this._capacity, this.sprites.length);
  20925. var min = BABYLON.Vector3.Zero();
  20926. var max = BABYLON.Vector3.Zero();
  20927. var distance = Number.MAX_VALUE;
  20928. var currentSprite;
  20929. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20930. var cameraView = camera.getViewMatrix();
  20931. for (var index = 0; index < count; index++) {
  20932. var sprite = this.sprites[index];
  20933. if (!sprite) {
  20934. continue;
  20935. }
  20936. if (predicate) {
  20937. if (!predicate(sprite)) {
  20938. continue;
  20939. }
  20940. }
  20941. else if (!sprite.isPickable) {
  20942. continue;
  20943. }
  20944. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20945. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20946. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20947. if (ray.intersectsBoxMinMax(min, max)) {
  20948. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20949. if (distance > currentDistance) {
  20950. distance = currentDistance;
  20951. currentSprite = sprite;
  20952. if (fastCheck) {
  20953. break;
  20954. }
  20955. }
  20956. }
  20957. }
  20958. if (currentSprite) {
  20959. var result = new BABYLON.PickingInfo();
  20960. result.hit = true;
  20961. result.pickedSprite = currentSprite;
  20962. result.distance = distance;
  20963. return result;
  20964. }
  20965. return null;
  20966. };
  20967. SpriteManager.prototype.render = function () {
  20968. // Check
  20969. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20970. return;
  20971. var engine = this._scene.getEngine();
  20972. var baseSize = this._spriteTexture.getBaseSize();
  20973. // Sprites
  20974. var deltaTime = engine.getDeltaTime();
  20975. var max = Math.min(this._capacity, this.sprites.length);
  20976. var rowSize = baseSize.width / this.cellSize;
  20977. var offset = 0;
  20978. for (var index = 0; index < max; index++) {
  20979. var sprite = this.sprites[index];
  20980. if (!sprite) {
  20981. continue;
  20982. }
  20983. sprite._animate(deltaTime);
  20984. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20985. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20986. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20987. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20988. }
  20989. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20990. // Render
  20991. var effect = this._effectBase;
  20992. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20993. effect = this._effectFog;
  20994. }
  20995. engine.enableEffect(effect);
  20996. var viewMatrix = this._scene.getViewMatrix();
  20997. effect.setTexture("diffuseSampler", this._spriteTexture);
  20998. effect.setMatrix("view", viewMatrix);
  20999. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21000. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21001. // Fog
  21002. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21003. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21004. effect.setColor3("vFogColor", this._scene.fogColor);
  21005. }
  21006. // VBOs
  21007. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21008. // Draw order
  21009. engine.setDepthFunctionToLessOrEqual();
  21010. effect.setBool("alphaTest", true);
  21011. engine.setColorWrite(false);
  21012. engine.draw(true, 0, max * 6);
  21013. engine.setColorWrite(true);
  21014. effect.setBool("alphaTest", false);
  21015. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21016. engine.draw(true, 0, max * 6);
  21017. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21018. };
  21019. SpriteManager.prototype.dispose = function () {
  21020. if (this._vertexBuffer) {
  21021. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21022. this._vertexBuffer = null;
  21023. }
  21024. if (this._indexBuffer) {
  21025. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21026. this._indexBuffer = null;
  21027. }
  21028. if (this._spriteTexture) {
  21029. this._spriteTexture.dispose();
  21030. this._spriteTexture = null;
  21031. }
  21032. // Remove from scene
  21033. var index = this._scene.spriteManagers.indexOf(this);
  21034. this._scene.spriteManagers.splice(index, 1);
  21035. // Callback
  21036. if (this.onDispose) {
  21037. this.onDispose();
  21038. }
  21039. };
  21040. return SpriteManager;
  21041. })();
  21042. BABYLON.SpriteManager = SpriteManager;
  21043. })(BABYLON || (BABYLON = {}));
  21044. var BABYLON;
  21045. (function (BABYLON) {
  21046. var Sprite = (function () {
  21047. function Sprite(name, manager) {
  21048. this.name = name;
  21049. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21050. this.width = 1.0;
  21051. this.height = 1.0;
  21052. this.angle = 0;
  21053. this.cellIndex = 0;
  21054. this.invertU = 0;
  21055. this.invertV = 0;
  21056. this.animations = new Array();
  21057. this.isPickable = false;
  21058. this._animationStarted = false;
  21059. this._loopAnimation = false;
  21060. this._fromIndex = 0;
  21061. this._toIndex = 0;
  21062. this._delay = 0;
  21063. this._direction = 1;
  21064. this._frameCount = 0;
  21065. this._time = 0;
  21066. this._manager = manager;
  21067. this._manager.sprites.push(this);
  21068. this.position = BABYLON.Vector3.Zero();
  21069. }
  21070. Object.defineProperty(Sprite.prototype, "size", {
  21071. get: function () {
  21072. return this.width;
  21073. },
  21074. set: function (value) {
  21075. this.width = value;
  21076. this.height = value;
  21077. },
  21078. enumerable: true,
  21079. configurable: true
  21080. });
  21081. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21082. this._fromIndex = from;
  21083. this._toIndex = to;
  21084. this._loopAnimation = loop;
  21085. this._delay = delay;
  21086. this._animationStarted = true;
  21087. this._direction = from < to ? 1 : -1;
  21088. this.cellIndex = from;
  21089. this._time = 0;
  21090. };
  21091. Sprite.prototype.stopAnimation = function () {
  21092. this._animationStarted = false;
  21093. };
  21094. Sprite.prototype._animate = function (deltaTime) {
  21095. if (!this._animationStarted)
  21096. return;
  21097. this._time += deltaTime;
  21098. if (this._time > this._delay) {
  21099. this._time = this._time % this._delay;
  21100. this.cellIndex += this._direction;
  21101. if (this.cellIndex == this._toIndex) {
  21102. if (this._loopAnimation) {
  21103. this.cellIndex = this._fromIndex;
  21104. }
  21105. else {
  21106. this._animationStarted = false;
  21107. if (this.disposeWhenFinishedAnimating) {
  21108. this.dispose();
  21109. }
  21110. }
  21111. }
  21112. }
  21113. };
  21114. Sprite.prototype.dispose = function () {
  21115. for (var i = 0; i < this._manager.sprites.length; i++) {
  21116. if (this._manager.sprites[i] == this) {
  21117. this._manager.sprites.splice(i, 1);
  21118. }
  21119. }
  21120. };
  21121. return Sprite;
  21122. })();
  21123. BABYLON.Sprite = Sprite;
  21124. })(BABYLON || (BABYLON = {}));
  21125. var BABYLON;
  21126. (function (BABYLON) {
  21127. var Layer = (function () {
  21128. function Layer(name, imgUrl, scene, isBackground, color) {
  21129. this.name = name;
  21130. this._vertexDeclaration = [2];
  21131. this._vertexStrideSize = 2 * 4;
  21132. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21133. this.isBackground = isBackground === undefined ? true : isBackground;
  21134. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21135. this._scene = scene;
  21136. this._scene.layers.push(this);
  21137. // VBO
  21138. var vertices = [];
  21139. vertices.push(1, 1);
  21140. vertices.push(-1, 1);
  21141. vertices.push(-1, -1);
  21142. vertices.push(1, -1);
  21143. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21144. // Indices
  21145. var indices = [];
  21146. indices.push(0);
  21147. indices.push(1);
  21148. indices.push(2);
  21149. indices.push(0);
  21150. indices.push(2);
  21151. indices.push(3);
  21152. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21153. // Effects
  21154. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21155. }
  21156. Layer.prototype.render = function () {
  21157. // Check
  21158. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21159. return;
  21160. var engine = this._scene.getEngine();
  21161. // Render
  21162. engine.enableEffect(this._effect);
  21163. engine.setState(false);
  21164. // Texture
  21165. this._effect.setTexture("textureSampler", this.texture);
  21166. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21167. // Color
  21168. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21169. // VBOs
  21170. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21171. // Draw order
  21172. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21173. engine.draw(true, 0, 6);
  21174. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21175. };
  21176. Layer.prototype.dispose = function () {
  21177. if (this._vertexBuffer) {
  21178. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21179. this._vertexBuffer = null;
  21180. }
  21181. if (this._indexBuffer) {
  21182. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21183. this._indexBuffer = null;
  21184. }
  21185. if (this.texture) {
  21186. this.texture.dispose();
  21187. this.texture = null;
  21188. }
  21189. // Remove from scene
  21190. var index = this._scene.layers.indexOf(this);
  21191. this._scene.layers.splice(index, 1);
  21192. // Callback
  21193. if (this.onDispose) {
  21194. this.onDispose();
  21195. }
  21196. };
  21197. return Layer;
  21198. })();
  21199. BABYLON.Layer = Layer;
  21200. })(BABYLON || (BABYLON = {}));
  21201. var BABYLON;
  21202. (function (BABYLON) {
  21203. var Particle = (function () {
  21204. function Particle() {
  21205. this.position = BABYLON.Vector3.Zero();
  21206. this.direction = BABYLON.Vector3.Zero();
  21207. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21208. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21209. this.lifeTime = 1.0;
  21210. this.age = 0;
  21211. this.size = 0;
  21212. this.angle = 0;
  21213. this.angularSpeed = 0;
  21214. }
  21215. Particle.prototype.copyTo = function (other) {
  21216. other.position.copyFrom(this.position);
  21217. other.direction.copyFrom(this.direction);
  21218. other.color.copyFrom(this.color);
  21219. other.colorStep.copyFrom(this.colorStep);
  21220. other.lifeTime = this.lifeTime;
  21221. other.age = this.age;
  21222. other.size = this.size;
  21223. other.angle = this.angle;
  21224. other.angularSpeed = this.angularSpeed;
  21225. };
  21226. return Particle;
  21227. })();
  21228. BABYLON.Particle = Particle;
  21229. })(BABYLON || (BABYLON = {}));
  21230. var BABYLON;
  21231. (function (BABYLON) {
  21232. var randomNumber = function (min, max) {
  21233. if (min === max) {
  21234. return (min);
  21235. }
  21236. var random = Math.random();
  21237. return ((random * (max - min)) + min);
  21238. };
  21239. var ParticleSystem = (function () {
  21240. function ParticleSystem(name, capacity, scene, customEffect) {
  21241. var _this = this;
  21242. this.name = name;
  21243. this.renderingGroupId = 0;
  21244. this.emitter = null;
  21245. this.emitRate = 10;
  21246. this.manualEmitCount = -1;
  21247. this.updateSpeed = 0.01;
  21248. this.targetStopDuration = 0;
  21249. this.disposeOnStop = false;
  21250. this.minEmitPower = 1;
  21251. this.maxEmitPower = 1;
  21252. this.minLifeTime = 1;
  21253. this.maxLifeTime = 1;
  21254. this.minSize = 1;
  21255. this.maxSize = 1;
  21256. this.minAngularSpeed = 0;
  21257. this.maxAngularSpeed = 0;
  21258. this.layerMask = 0x0FFFFFFF;
  21259. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21260. this.forceDepthWrite = false;
  21261. this.gravity = BABYLON.Vector3.Zero();
  21262. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21263. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21264. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21265. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21266. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21267. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21268. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21269. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21270. this.particles = new Array();
  21271. this._vertexDeclaration = [3, 4, 4];
  21272. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21273. this._stockParticles = new Array();
  21274. this._newPartsExcess = 0;
  21275. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21276. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21277. this._scaledDirection = BABYLON.Vector3.Zero();
  21278. this._scaledGravity = BABYLON.Vector3.Zero();
  21279. this._currentRenderId = -1;
  21280. this._started = false;
  21281. this._stopped = false;
  21282. this._actualFrame = 0;
  21283. this.id = name;
  21284. this._capacity = capacity;
  21285. this._scene = scene;
  21286. this._customEffect = customEffect;
  21287. scene.particleSystems.push(this);
  21288. // VBO
  21289. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21290. var indices = [];
  21291. var index = 0;
  21292. for (var count = 0; count < capacity; count++) {
  21293. indices.push(index);
  21294. indices.push(index + 1);
  21295. indices.push(index + 2);
  21296. indices.push(index);
  21297. indices.push(index + 2);
  21298. indices.push(index + 3);
  21299. index += 4;
  21300. }
  21301. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21302. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21303. // Default behaviors
  21304. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21305. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21306. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21307. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21308. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21309. };
  21310. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21311. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21312. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21313. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21315. };
  21316. this.updateFunction = function (particles) {
  21317. for (var index = 0; index < particles.length; index++) {
  21318. var particle = particles[index];
  21319. particle.age += _this._scaledUpdateSpeed;
  21320. if (particle.age >= particle.lifeTime) {
  21321. _this.recycleParticle(particle);
  21322. index--;
  21323. continue;
  21324. }
  21325. else {
  21326. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21327. particle.color.addInPlace(_this._scaledColorStep);
  21328. if (particle.color.a < 0)
  21329. particle.color.a = 0;
  21330. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21331. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21332. particle.position.addInPlace(_this._scaledDirection);
  21333. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21334. particle.direction.addInPlace(_this._scaledGravity);
  21335. }
  21336. }
  21337. };
  21338. }
  21339. ParticleSystem.prototype.recycleParticle = function (particle) {
  21340. var lastParticle = this.particles.pop();
  21341. if (lastParticle !== particle) {
  21342. lastParticle.copyTo(particle);
  21343. this._stockParticles.push(lastParticle);
  21344. }
  21345. };
  21346. ParticleSystem.prototype.getCapacity = function () {
  21347. return this._capacity;
  21348. };
  21349. ParticleSystem.prototype.isAlive = function () {
  21350. return this._alive;
  21351. };
  21352. ParticleSystem.prototype.isStarted = function () {
  21353. return this._started;
  21354. };
  21355. ParticleSystem.prototype.start = function () {
  21356. this._started = true;
  21357. this._stopped = false;
  21358. this._actualFrame = 0;
  21359. };
  21360. ParticleSystem.prototype.stop = function () {
  21361. this._stopped = true;
  21362. };
  21363. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21364. var offset = index * 11;
  21365. this._vertices[offset] = particle.position.x;
  21366. this._vertices[offset + 1] = particle.position.y;
  21367. this._vertices[offset + 2] = particle.position.z;
  21368. this._vertices[offset + 3] = particle.color.r;
  21369. this._vertices[offset + 4] = particle.color.g;
  21370. this._vertices[offset + 5] = particle.color.b;
  21371. this._vertices[offset + 6] = particle.color.a;
  21372. this._vertices[offset + 7] = particle.angle;
  21373. this._vertices[offset + 8] = particle.size;
  21374. this._vertices[offset + 9] = offsetX;
  21375. this._vertices[offset + 10] = offsetY;
  21376. };
  21377. ParticleSystem.prototype._update = function (newParticles) {
  21378. // Update current
  21379. this._alive = this.particles.length > 0;
  21380. this.updateFunction(this.particles);
  21381. // Add new ones
  21382. var worldMatrix;
  21383. if (this.emitter.position) {
  21384. worldMatrix = this.emitter.getWorldMatrix();
  21385. }
  21386. else {
  21387. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21388. }
  21389. for (var index = 0; index < newParticles; index++) {
  21390. if (this.particles.length === this._capacity) {
  21391. break;
  21392. }
  21393. if (this._stockParticles.length !== 0) {
  21394. var particle = this._stockParticles.pop();
  21395. particle.age = 0;
  21396. }
  21397. else {
  21398. particle = new BABYLON.Particle();
  21399. }
  21400. this.particles.push(particle);
  21401. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21402. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21403. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21404. particle.size = randomNumber(this.minSize, this.maxSize);
  21405. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21406. this.startPositionFunction(worldMatrix, particle.position);
  21407. var step = randomNumber(0, 1.0);
  21408. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21409. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21410. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21411. }
  21412. };
  21413. ParticleSystem.prototype._getEffect = function () {
  21414. if (this._customEffect) {
  21415. return this._customEffect;
  21416. }
  21417. ;
  21418. var defines = [];
  21419. if (this._scene.clipPlane) {
  21420. defines.push("#define CLIPPLANE");
  21421. }
  21422. // Effect
  21423. var join = defines.join("\n");
  21424. if (this._cachedDefines !== join) {
  21425. this._cachedDefines = join;
  21426. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21427. }
  21428. return this._effect;
  21429. };
  21430. ParticleSystem.prototype.animate = function () {
  21431. if (!this._started)
  21432. return;
  21433. var effect = this._getEffect();
  21434. // Check
  21435. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21436. return;
  21437. if (this._currentRenderId === this._scene.getRenderId()) {
  21438. return;
  21439. }
  21440. this._currentRenderId = this._scene.getRenderId();
  21441. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21442. // determine the number of particles we need to create
  21443. var emitCout;
  21444. if (this.manualEmitCount > -1) {
  21445. emitCout = this.manualEmitCount;
  21446. this.manualEmitCount = 0;
  21447. }
  21448. else {
  21449. emitCout = this.emitRate;
  21450. }
  21451. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21452. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21453. if (this._newPartsExcess > 1.0) {
  21454. newParticles += this._newPartsExcess >> 0;
  21455. this._newPartsExcess -= this._newPartsExcess >> 0;
  21456. }
  21457. this._alive = false;
  21458. if (!this._stopped) {
  21459. this._actualFrame += this._scaledUpdateSpeed;
  21460. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21461. this.stop();
  21462. }
  21463. else {
  21464. newParticles = 0;
  21465. }
  21466. this._update(newParticles);
  21467. // Stopped?
  21468. if (this._stopped) {
  21469. if (!this._alive) {
  21470. this._started = false;
  21471. if (this.disposeOnStop) {
  21472. this._scene._toBeDisposed.push(this);
  21473. }
  21474. }
  21475. }
  21476. // Update VBO
  21477. var offset = 0;
  21478. for (var index = 0; index < this.particles.length; index++) {
  21479. var particle = this.particles[index];
  21480. this._appendParticleVertex(offset++, particle, 0, 0);
  21481. this._appendParticleVertex(offset++, particle, 1, 0);
  21482. this._appendParticleVertex(offset++, particle, 1, 1);
  21483. this._appendParticleVertex(offset++, particle, 0, 1);
  21484. }
  21485. var engine = this._scene.getEngine();
  21486. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21487. };
  21488. ParticleSystem.prototype.render = function () {
  21489. var effect = this._getEffect();
  21490. // Check
  21491. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21492. return 0;
  21493. var engine = this._scene.getEngine();
  21494. // Render
  21495. engine.enableEffect(effect);
  21496. engine.setState(false);
  21497. var viewMatrix = this._scene.getViewMatrix();
  21498. effect.setTexture("diffuseSampler", this.particleTexture);
  21499. effect.setMatrix("view", viewMatrix);
  21500. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21501. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21502. if (this._scene.clipPlane) {
  21503. var clipPlane = this._scene.clipPlane;
  21504. var invView = viewMatrix.clone();
  21505. invView.invert();
  21506. effect.setMatrix("invView", invView);
  21507. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21508. }
  21509. // VBOs
  21510. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21511. // Draw order
  21512. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21513. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21514. }
  21515. else {
  21516. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21517. }
  21518. if (this.forceDepthWrite) {
  21519. engine.setDepthWrite(true);
  21520. }
  21521. engine.draw(true, 0, this.particles.length * 6);
  21522. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21523. return this.particles.length;
  21524. };
  21525. ParticleSystem.prototype.dispose = function () {
  21526. if (this._vertexBuffer) {
  21527. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21528. this._vertexBuffer = null;
  21529. }
  21530. if (this._indexBuffer) {
  21531. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21532. this._indexBuffer = null;
  21533. }
  21534. if (this.particleTexture) {
  21535. this.particleTexture.dispose();
  21536. this.particleTexture = null;
  21537. }
  21538. // Remove from scene
  21539. var index = this._scene.particleSystems.indexOf(this);
  21540. this._scene.particleSystems.splice(index, 1);
  21541. // Callback
  21542. if (this.onDispose) {
  21543. this.onDispose();
  21544. }
  21545. };
  21546. // Clone
  21547. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21548. var result = new ParticleSystem(name, this._capacity, this._scene);
  21549. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21550. if (newEmitter === undefined) {
  21551. newEmitter = this.emitter;
  21552. }
  21553. result.emitter = newEmitter;
  21554. if (this.particleTexture) {
  21555. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21556. }
  21557. result.start();
  21558. return result;
  21559. };
  21560. // Statics
  21561. ParticleSystem.BLENDMODE_ONEONE = 0;
  21562. ParticleSystem.BLENDMODE_STANDARD = 1;
  21563. return ParticleSystem;
  21564. })();
  21565. BABYLON.ParticleSystem = ParticleSystem;
  21566. })(BABYLON || (BABYLON = {}));
  21567. var BABYLON;
  21568. (function (BABYLON) {
  21569. var AnimationRange = (function () {
  21570. function AnimationRange(name, from, to) {
  21571. this.name = name;
  21572. this.from = from;
  21573. this.to = to;
  21574. }
  21575. return AnimationRange;
  21576. })();
  21577. BABYLON.AnimationRange = AnimationRange;
  21578. var Animation = (function () {
  21579. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21580. this.name = name;
  21581. this.targetProperty = targetProperty;
  21582. this.framePerSecond = framePerSecond;
  21583. this.dataType = dataType;
  21584. this.loopMode = loopMode;
  21585. this._offsetsCache = {};
  21586. this._highLimitsCache = {};
  21587. this._stopped = false;
  21588. this.allowMatricesInterpolation = false;
  21589. this._ranges = new Array();
  21590. this.targetPropertyPath = targetProperty.split(".");
  21591. this.dataType = dataType;
  21592. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21593. }
  21594. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21595. var dataType = undefined;
  21596. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21597. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21598. }
  21599. else if (from instanceof BABYLON.Quaternion) {
  21600. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21601. }
  21602. else if (from instanceof BABYLON.Vector3) {
  21603. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21604. }
  21605. else if (from instanceof BABYLON.Vector2) {
  21606. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21607. }
  21608. else if (from instanceof BABYLON.Color3) {
  21609. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21610. }
  21611. if (dataType == undefined) {
  21612. return null;
  21613. }
  21614. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21615. var keys = [];
  21616. keys.push({ frame: 0, value: from });
  21617. keys.push({ frame: totalFrame, value: to });
  21618. animation.setKeys(keys);
  21619. if (easingFunction !== undefined) {
  21620. animation.setEasingFunction(easingFunction);
  21621. }
  21622. mesh.animations.push(animation);
  21623. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21624. };
  21625. // Methods
  21626. Animation.prototype.createRange = function (name, from, to) {
  21627. this._ranges.push(new AnimationRange(name, from, to));
  21628. };
  21629. Animation.prototype.deleteRange = function (name) {
  21630. for (var index = 0; index < this._ranges.length; index++) {
  21631. if (this._ranges[index].name === name) {
  21632. this._ranges.splice(index, 1);
  21633. return;
  21634. }
  21635. }
  21636. };
  21637. Animation.prototype.getRange = function (name) {
  21638. for (var index = 0; index < this._ranges.length; index++) {
  21639. if (this._ranges[index].name === name) {
  21640. return this._ranges[index];
  21641. }
  21642. }
  21643. return null;
  21644. };
  21645. Animation.prototype.reset = function () {
  21646. this._offsetsCache = {};
  21647. this._highLimitsCache = {};
  21648. this.currentFrame = 0;
  21649. };
  21650. Animation.prototype.isStopped = function () {
  21651. return this._stopped;
  21652. };
  21653. Animation.prototype.getKeys = function () {
  21654. return this._keys;
  21655. };
  21656. Animation.prototype.getEasingFunction = function () {
  21657. return this._easingFunction;
  21658. };
  21659. Animation.prototype.setEasingFunction = function (easingFunction) {
  21660. this._easingFunction = easingFunction;
  21661. };
  21662. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21663. return startValue + (endValue - startValue) * gradient;
  21664. };
  21665. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21666. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21667. };
  21668. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21669. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21670. };
  21671. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21672. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21673. };
  21674. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21675. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21676. };
  21677. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21678. var startScale = new BABYLON.Vector3(0, 0, 0);
  21679. var startRotation = new BABYLON.Quaternion();
  21680. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21681. startValue.decompose(startScale, startRotation, startTranslation);
  21682. var endScale = new BABYLON.Vector3(0, 0, 0);
  21683. var endRotation = new BABYLON.Quaternion();
  21684. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21685. endValue.decompose(endScale, endRotation, endTranslation);
  21686. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21687. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21688. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21689. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21690. return result;
  21691. };
  21692. Animation.prototype.clone = function () {
  21693. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21694. if (this._keys) {
  21695. clone.setKeys(this._keys);
  21696. }
  21697. return clone;
  21698. };
  21699. Animation.prototype.setKeys = function (values) {
  21700. this._keys = values.slice(0);
  21701. this._offsetsCache = {};
  21702. this._highLimitsCache = {};
  21703. };
  21704. Animation.prototype._getKeyValue = function (value) {
  21705. if (typeof value === "function") {
  21706. return value();
  21707. }
  21708. return value;
  21709. };
  21710. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21711. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21712. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21713. }
  21714. this.currentFrame = currentFrame;
  21715. // Try to get a hash to find the right key
  21716. 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));
  21717. if (this._keys[startKey].frame >= currentFrame) {
  21718. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21719. startKey--;
  21720. }
  21721. }
  21722. for (var key = startKey; key < this._keys.length; key++) {
  21723. if (this._keys[key + 1].frame >= currentFrame) {
  21724. var startValue = this._getKeyValue(this._keys[key].value);
  21725. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21726. // gradient : percent of currentFrame between the frame inf and the frame sup
  21727. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21728. // check for easingFunction and correction of gradient
  21729. if (this._easingFunction != null) {
  21730. gradient = this._easingFunction.ease(gradient);
  21731. }
  21732. switch (this.dataType) {
  21733. // Float
  21734. case Animation.ANIMATIONTYPE_FLOAT:
  21735. switch (loopMode) {
  21736. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21737. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21738. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21739. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21740. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21741. }
  21742. break;
  21743. // Quaternion
  21744. case Animation.ANIMATIONTYPE_QUATERNION:
  21745. var quaternion = null;
  21746. switch (loopMode) {
  21747. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21748. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21749. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21750. break;
  21751. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21752. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21753. break;
  21754. }
  21755. return quaternion;
  21756. // Vector3
  21757. case Animation.ANIMATIONTYPE_VECTOR3:
  21758. switch (loopMode) {
  21759. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21760. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21761. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21762. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21763. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21764. }
  21765. // Vector2
  21766. case Animation.ANIMATIONTYPE_VECTOR2:
  21767. switch (loopMode) {
  21768. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21769. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21770. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21771. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21772. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21773. }
  21774. // Color3
  21775. case Animation.ANIMATIONTYPE_COLOR3:
  21776. switch (loopMode) {
  21777. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21778. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21779. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21780. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21781. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21782. }
  21783. // Matrix
  21784. case Animation.ANIMATIONTYPE_MATRIX:
  21785. switch (loopMode) {
  21786. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21787. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21788. if (this.allowMatricesInterpolation) {
  21789. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21790. }
  21791. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21792. return startValue;
  21793. }
  21794. default:
  21795. break;
  21796. }
  21797. break;
  21798. }
  21799. }
  21800. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21801. };
  21802. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21803. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21804. this._stopped = true;
  21805. return false;
  21806. }
  21807. var returnValue = true;
  21808. // Adding a start key at frame 0 if missing
  21809. if (this._keys[0].frame !== 0) {
  21810. var newKey = { frame: 0, value: this._keys[0].value };
  21811. this._keys.splice(0, 0, newKey);
  21812. }
  21813. // Check limits
  21814. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21815. from = this._keys[0].frame;
  21816. }
  21817. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21818. to = this._keys[this._keys.length - 1].frame;
  21819. }
  21820. // Compute ratio
  21821. var range = to - from;
  21822. var offsetValue;
  21823. // ratio represents the frame delta between from and to
  21824. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21825. var highLimitValue = 0;
  21826. if (ratio > range && !loop) {
  21827. returnValue = false;
  21828. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21829. }
  21830. else {
  21831. // Get max value if required
  21832. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21833. var keyOffset = to.toString() + from.toString();
  21834. if (!this._offsetsCache[keyOffset]) {
  21835. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21836. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21837. switch (this.dataType) {
  21838. // Float
  21839. case Animation.ANIMATIONTYPE_FLOAT:
  21840. this._offsetsCache[keyOffset] = toValue - fromValue;
  21841. break;
  21842. // Quaternion
  21843. case Animation.ANIMATIONTYPE_QUATERNION:
  21844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21845. break;
  21846. // Vector3
  21847. case Animation.ANIMATIONTYPE_VECTOR3:
  21848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21849. // Vector2
  21850. case Animation.ANIMATIONTYPE_VECTOR2:
  21851. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21852. // Color3
  21853. case Animation.ANIMATIONTYPE_COLOR3:
  21854. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21855. default:
  21856. break;
  21857. }
  21858. this._highLimitsCache[keyOffset] = toValue;
  21859. }
  21860. highLimitValue = this._highLimitsCache[keyOffset];
  21861. offsetValue = this._offsetsCache[keyOffset];
  21862. }
  21863. }
  21864. if (offsetValue === undefined) {
  21865. switch (this.dataType) {
  21866. // Float
  21867. case Animation.ANIMATIONTYPE_FLOAT:
  21868. offsetValue = 0;
  21869. break;
  21870. // Quaternion
  21871. case Animation.ANIMATIONTYPE_QUATERNION:
  21872. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21873. break;
  21874. // Vector3
  21875. case Animation.ANIMATIONTYPE_VECTOR3:
  21876. offsetValue = BABYLON.Vector3.Zero();
  21877. break;
  21878. // Vector2
  21879. case Animation.ANIMATIONTYPE_VECTOR2:
  21880. offsetValue = BABYLON.Vector2.Zero();
  21881. break;
  21882. // Color3
  21883. case Animation.ANIMATIONTYPE_COLOR3:
  21884. offsetValue = BABYLON.Color3.Black();
  21885. }
  21886. }
  21887. // Compute value
  21888. var repeatCount = (ratio / range) >> 0;
  21889. var currentFrame = returnValue ? from + ratio % range : to;
  21890. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21891. // Set value
  21892. if (this.targetPropertyPath.length > 1) {
  21893. var property = this._target[this.targetPropertyPath[0]];
  21894. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21895. property = property[this.targetPropertyPath[index]];
  21896. }
  21897. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21898. }
  21899. else {
  21900. this._target[this.targetPropertyPath[0]] = currentValue;
  21901. }
  21902. if (this._target.markAsDirty) {
  21903. this._target.markAsDirty(this.targetProperty);
  21904. }
  21905. if (!returnValue) {
  21906. this._stopped = true;
  21907. }
  21908. return returnValue;
  21909. };
  21910. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21911. get: function () {
  21912. return Animation._ANIMATIONTYPE_FLOAT;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21918. get: function () {
  21919. return Animation._ANIMATIONTYPE_VECTOR3;
  21920. },
  21921. enumerable: true,
  21922. configurable: true
  21923. });
  21924. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21925. get: function () {
  21926. return Animation._ANIMATIONTYPE_VECTOR2;
  21927. },
  21928. enumerable: true,
  21929. configurable: true
  21930. });
  21931. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21932. get: function () {
  21933. return Animation._ANIMATIONTYPE_QUATERNION;
  21934. },
  21935. enumerable: true,
  21936. configurable: true
  21937. });
  21938. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21939. get: function () {
  21940. return Animation._ANIMATIONTYPE_MATRIX;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21946. get: function () {
  21947. return Animation._ANIMATIONTYPE_COLOR3;
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21953. get: function () {
  21954. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21960. get: function () {
  21961. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21962. },
  21963. enumerable: true,
  21964. configurable: true
  21965. });
  21966. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21967. get: function () {
  21968. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. // Statics
  21974. Animation._ANIMATIONTYPE_FLOAT = 0;
  21975. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21976. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21977. Animation._ANIMATIONTYPE_MATRIX = 3;
  21978. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21979. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21980. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21981. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21982. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21983. return Animation;
  21984. })();
  21985. BABYLON.Animation = Animation;
  21986. })(BABYLON || (BABYLON = {}));
  21987. var BABYLON;
  21988. (function (BABYLON) {
  21989. var Animatable = (function () {
  21990. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21991. if (fromFrame === void 0) { fromFrame = 0; }
  21992. if (toFrame === void 0) { toFrame = 100; }
  21993. if (loopAnimation === void 0) { loopAnimation = false; }
  21994. if (speedRatio === void 0) { speedRatio = 1.0; }
  21995. this.target = target;
  21996. this.fromFrame = fromFrame;
  21997. this.toFrame = toFrame;
  21998. this.loopAnimation = loopAnimation;
  21999. this.speedRatio = speedRatio;
  22000. this.onAnimationEnd = onAnimationEnd;
  22001. this._animations = new Array();
  22002. this._paused = false;
  22003. this.animationStarted = false;
  22004. if (animations) {
  22005. this.appendAnimations(target, animations);
  22006. }
  22007. this._scene = scene;
  22008. scene._activeAnimatables.push(this);
  22009. }
  22010. // Methods
  22011. Animatable.prototype.getAnimations = function () {
  22012. return this._animations;
  22013. };
  22014. Animatable.prototype.appendAnimations = function (target, animations) {
  22015. for (var index = 0; index < animations.length; index++) {
  22016. var animation = animations[index];
  22017. animation._target = target;
  22018. this._animations.push(animation);
  22019. }
  22020. };
  22021. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22022. var animations = this._animations;
  22023. for (var index = 0; index < animations.length; index++) {
  22024. if (animations[index].targetProperty === property) {
  22025. return animations[index];
  22026. }
  22027. }
  22028. return null;
  22029. };
  22030. Animatable.prototype.reset = function () {
  22031. var animations = this._animations;
  22032. for (var index = 0; index < animations.length; index++) {
  22033. animations[index].reset();
  22034. }
  22035. this._localDelayOffset = null;
  22036. this._pausedDelay = null;
  22037. };
  22038. Animatable.prototype.pause = function () {
  22039. if (this._paused) {
  22040. return;
  22041. }
  22042. this._paused = true;
  22043. };
  22044. Animatable.prototype.restart = function () {
  22045. this._paused = false;
  22046. };
  22047. Animatable.prototype.stop = function () {
  22048. var index = this._scene._activeAnimatables.indexOf(this);
  22049. if (index > -1) {
  22050. this._scene._activeAnimatables.splice(index, 1);
  22051. }
  22052. if (this.onAnimationEnd) {
  22053. this.onAnimationEnd();
  22054. }
  22055. };
  22056. Animatable.prototype._animate = function (delay) {
  22057. if (this._paused) {
  22058. if (!this._pausedDelay) {
  22059. this._pausedDelay = delay;
  22060. }
  22061. return true;
  22062. }
  22063. if (!this._localDelayOffset) {
  22064. this._localDelayOffset = delay;
  22065. }
  22066. else if (this._pausedDelay) {
  22067. this._localDelayOffset += delay - this._pausedDelay;
  22068. this._pausedDelay = null;
  22069. }
  22070. // Animating
  22071. var running = false;
  22072. var animations = this._animations;
  22073. for (var index = 0; index < animations.length; index++) {
  22074. var animation = animations[index];
  22075. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22076. running = running || isRunning;
  22077. }
  22078. if (!running) {
  22079. // Remove from active animatables
  22080. index = this._scene._activeAnimatables.indexOf(this);
  22081. this._scene._activeAnimatables.splice(index, 1);
  22082. }
  22083. if (!running && this.onAnimationEnd) {
  22084. this.onAnimationEnd();
  22085. }
  22086. return running;
  22087. };
  22088. return Animatable;
  22089. })();
  22090. BABYLON.Animatable = Animatable;
  22091. })(BABYLON || (BABYLON = {}));
  22092. var BABYLON;
  22093. (function (BABYLON) {
  22094. var EasingFunction = (function () {
  22095. function EasingFunction() {
  22096. // Properties
  22097. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22098. }
  22099. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22100. get: function () {
  22101. return EasingFunction._EASINGMODE_EASEIN;
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22107. get: function () {
  22108. return EasingFunction._EASINGMODE_EASEOUT;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22114. get: function () {
  22115. return EasingFunction._EASINGMODE_EASEINOUT;
  22116. },
  22117. enumerable: true,
  22118. configurable: true
  22119. });
  22120. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22121. var n = Math.min(Math.max(easingMode, 0), 2);
  22122. this._easingMode = n;
  22123. };
  22124. EasingFunction.prototype.getEasingMode = function () {
  22125. return this._easingMode;
  22126. };
  22127. EasingFunction.prototype.easeInCore = function (gradient) {
  22128. throw new Error('You must implement this method');
  22129. };
  22130. EasingFunction.prototype.ease = function (gradient) {
  22131. switch (this._easingMode) {
  22132. case EasingFunction.EASINGMODE_EASEIN:
  22133. return this.easeInCore(gradient);
  22134. case EasingFunction.EASINGMODE_EASEOUT:
  22135. return (1 - this.easeInCore(1 - gradient));
  22136. }
  22137. if (gradient >= 0.5) {
  22138. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22139. }
  22140. return (this.easeInCore(gradient * 2) * 0.5);
  22141. };
  22142. //Statics
  22143. EasingFunction._EASINGMODE_EASEIN = 0;
  22144. EasingFunction._EASINGMODE_EASEOUT = 1;
  22145. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22146. return EasingFunction;
  22147. })();
  22148. BABYLON.EasingFunction = EasingFunction;
  22149. var CircleEase = (function (_super) {
  22150. __extends(CircleEase, _super);
  22151. function CircleEase() {
  22152. _super.apply(this, arguments);
  22153. }
  22154. CircleEase.prototype.easeInCore = function (gradient) {
  22155. gradient = Math.max(0, Math.min(1, gradient));
  22156. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22157. };
  22158. return CircleEase;
  22159. })(EasingFunction);
  22160. BABYLON.CircleEase = CircleEase;
  22161. var BackEase = (function (_super) {
  22162. __extends(BackEase, _super);
  22163. function BackEase(amplitude) {
  22164. if (amplitude === void 0) { amplitude = 1; }
  22165. _super.call(this);
  22166. this.amplitude = amplitude;
  22167. }
  22168. BackEase.prototype.easeInCore = function (gradient) {
  22169. var num = Math.max(0, this.amplitude);
  22170. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22171. };
  22172. return BackEase;
  22173. })(EasingFunction);
  22174. BABYLON.BackEase = BackEase;
  22175. var BounceEase = (function (_super) {
  22176. __extends(BounceEase, _super);
  22177. function BounceEase(bounces, bounciness) {
  22178. if (bounces === void 0) { bounces = 3; }
  22179. if (bounciness === void 0) { bounciness = 2; }
  22180. _super.call(this);
  22181. this.bounces = bounces;
  22182. this.bounciness = bounciness;
  22183. }
  22184. BounceEase.prototype.easeInCore = function (gradient) {
  22185. var y = Math.max(0.0, this.bounces);
  22186. var bounciness = this.bounciness;
  22187. if (bounciness <= 1.0) {
  22188. bounciness = 1.001;
  22189. }
  22190. var num9 = Math.pow(bounciness, y);
  22191. var num5 = 1.0 - bounciness;
  22192. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22193. var num15 = gradient * num4;
  22194. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22195. var num3 = Math.floor(num65);
  22196. var num13 = num3 + 1.0;
  22197. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22198. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22199. var num7 = (num8 + num12) * 0.5;
  22200. var num6 = gradient - num7;
  22201. var num2 = num7 - num8;
  22202. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22203. };
  22204. return BounceEase;
  22205. })(EasingFunction);
  22206. BABYLON.BounceEase = BounceEase;
  22207. var CubicEase = (function (_super) {
  22208. __extends(CubicEase, _super);
  22209. function CubicEase() {
  22210. _super.apply(this, arguments);
  22211. }
  22212. CubicEase.prototype.easeInCore = function (gradient) {
  22213. return (gradient * gradient * gradient);
  22214. };
  22215. return CubicEase;
  22216. })(EasingFunction);
  22217. BABYLON.CubicEase = CubicEase;
  22218. var ElasticEase = (function (_super) {
  22219. __extends(ElasticEase, _super);
  22220. function ElasticEase(oscillations, springiness) {
  22221. if (oscillations === void 0) { oscillations = 3; }
  22222. if (springiness === void 0) { springiness = 3; }
  22223. _super.call(this);
  22224. this.oscillations = oscillations;
  22225. this.springiness = springiness;
  22226. }
  22227. ElasticEase.prototype.easeInCore = function (gradient) {
  22228. var num2;
  22229. var num3 = Math.max(0.0, this.oscillations);
  22230. var num = Math.max(0.0, this.springiness);
  22231. if (num == 0) {
  22232. num2 = gradient;
  22233. }
  22234. else {
  22235. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22236. }
  22237. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22238. };
  22239. return ElasticEase;
  22240. })(EasingFunction);
  22241. BABYLON.ElasticEase = ElasticEase;
  22242. var ExponentialEase = (function (_super) {
  22243. __extends(ExponentialEase, _super);
  22244. function ExponentialEase(exponent) {
  22245. if (exponent === void 0) { exponent = 2; }
  22246. _super.call(this);
  22247. this.exponent = exponent;
  22248. }
  22249. ExponentialEase.prototype.easeInCore = function (gradient) {
  22250. if (this.exponent <= 0) {
  22251. return gradient;
  22252. }
  22253. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22254. };
  22255. return ExponentialEase;
  22256. })(EasingFunction);
  22257. BABYLON.ExponentialEase = ExponentialEase;
  22258. var PowerEase = (function (_super) {
  22259. __extends(PowerEase, _super);
  22260. function PowerEase(power) {
  22261. if (power === void 0) { power = 2; }
  22262. _super.call(this);
  22263. this.power = power;
  22264. }
  22265. PowerEase.prototype.easeInCore = function (gradient) {
  22266. var y = Math.max(0.0, this.power);
  22267. return Math.pow(gradient, y);
  22268. };
  22269. return PowerEase;
  22270. })(EasingFunction);
  22271. BABYLON.PowerEase = PowerEase;
  22272. var QuadraticEase = (function (_super) {
  22273. __extends(QuadraticEase, _super);
  22274. function QuadraticEase() {
  22275. _super.apply(this, arguments);
  22276. }
  22277. QuadraticEase.prototype.easeInCore = function (gradient) {
  22278. return (gradient * gradient);
  22279. };
  22280. return QuadraticEase;
  22281. })(EasingFunction);
  22282. BABYLON.QuadraticEase = QuadraticEase;
  22283. var QuarticEase = (function (_super) {
  22284. __extends(QuarticEase, _super);
  22285. function QuarticEase() {
  22286. _super.apply(this, arguments);
  22287. }
  22288. QuarticEase.prototype.easeInCore = function (gradient) {
  22289. return (gradient * gradient * gradient * gradient);
  22290. };
  22291. return QuarticEase;
  22292. })(EasingFunction);
  22293. BABYLON.QuarticEase = QuarticEase;
  22294. var QuinticEase = (function (_super) {
  22295. __extends(QuinticEase, _super);
  22296. function QuinticEase() {
  22297. _super.apply(this, arguments);
  22298. }
  22299. QuinticEase.prototype.easeInCore = function (gradient) {
  22300. return (gradient * gradient * gradient * gradient * gradient);
  22301. };
  22302. return QuinticEase;
  22303. })(EasingFunction);
  22304. BABYLON.QuinticEase = QuinticEase;
  22305. var SineEase = (function (_super) {
  22306. __extends(SineEase, _super);
  22307. function SineEase() {
  22308. _super.apply(this, arguments);
  22309. }
  22310. SineEase.prototype.easeInCore = function (gradient) {
  22311. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22312. };
  22313. return SineEase;
  22314. })(EasingFunction);
  22315. BABYLON.SineEase = SineEase;
  22316. var BezierCurveEase = (function (_super) {
  22317. __extends(BezierCurveEase, _super);
  22318. function BezierCurveEase(x1, y1, x2, y2) {
  22319. if (x1 === void 0) { x1 = 0; }
  22320. if (y1 === void 0) { y1 = 0; }
  22321. if (x2 === void 0) { x2 = 1; }
  22322. if (y2 === void 0) { y2 = 1; }
  22323. _super.call(this);
  22324. this.x1 = x1;
  22325. this.y1 = y1;
  22326. this.x2 = x2;
  22327. this.y2 = y2;
  22328. }
  22329. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22330. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22331. };
  22332. return BezierCurveEase;
  22333. })(EasingFunction);
  22334. BABYLON.BezierCurveEase = BezierCurveEase;
  22335. })(BABYLON || (BABYLON = {}));
  22336. var BABYLON;
  22337. (function (BABYLON) {
  22338. var Bone = (function (_super) {
  22339. __extends(Bone, _super);
  22340. function Bone(name, skeleton, parentBone, matrix) {
  22341. _super.call(this, name, skeleton.getScene());
  22342. this.name = name;
  22343. this.children = new Array();
  22344. this.animations = new Array();
  22345. this._worldTransform = new BABYLON.Matrix();
  22346. this._absoluteTransform = new BABYLON.Matrix();
  22347. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22348. this._skeleton = skeleton;
  22349. this._matrix = matrix;
  22350. this._baseMatrix = matrix;
  22351. skeleton.bones.push(this);
  22352. if (parentBone) {
  22353. this._parent = parentBone;
  22354. parentBone.children.push(this);
  22355. }
  22356. else {
  22357. this._parent = null;
  22358. }
  22359. this._updateDifferenceMatrix();
  22360. }
  22361. // Members
  22362. Bone.prototype.getParent = function () {
  22363. return this._parent;
  22364. };
  22365. Bone.prototype.getLocalMatrix = function () {
  22366. return this._matrix;
  22367. };
  22368. Bone.prototype.getBaseMatrix = function () {
  22369. return this._baseMatrix;
  22370. };
  22371. Bone.prototype.getWorldMatrix = function () {
  22372. return this._worldTransform;
  22373. };
  22374. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22375. return this._invertedAbsoluteTransform;
  22376. };
  22377. Bone.prototype.getAbsoluteMatrix = function () {
  22378. var matrix = this._matrix.clone();
  22379. var parent = this._parent;
  22380. while (parent) {
  22381. matrix = matrix.multiply(parent.getLocalMatrix());
  22382. parent = parent.getParent();
  22383. }
  22384. return matrix;
  22385. };
  22386. // Methods
  22387. Bone.prototype.updateMatrix = function (matrix) {
  22388. this._matrix = matrix;
  22389. this._skeleton._markAsDirty();
  22390. this._updateDifferenceMatrix();
  22391. };
  22392. Bone.prototype._updateDifferenceMatrix = function () {
  22393. if (this._parent) {
  22394. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22395. }
  22396. else {
  22397. this._absoluteTransform.copyFrom(this._matrix);
  22398. }
  22399. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22400. for (var index = 0; index < this.children.length; index++) {
  22401. this.children[index]._updateDifferenceMatrix();
  22402. }
  22403. };
  22404. Bone.prototype.markAsDirty = function () {
  22405. this._currentRenderId++;
  22406. this._skeleton._markAsDirty();
  22407. };
  22408. return Bone;
  22409. })(BABYLON.Node);
  22410. BABYLON.Bone = Bone;
  22411. })(BABYLON || (BABYLON = {}));
  22412. var BABYLON;
  22413. (function (BABYLON) {
  22414. var Skeleton = (function () {
  22415. function Skeleton(name, id, scene) {
  22416. this.name = name;
  22417. this.id = id;
  22418. this.bones = new Array();
  22419. this._isDirty = true;
  22420. this._identity = BABYLON.Matrix.Identity();
  22421. this._ranges = new Array();
  22422. this.bones = [];
  22423. this._scene = scene;
  22424. scene.skeletons.push(this);
  22425. this.prepare();
  22426. //make sure it will recalculate the matrix next time prepare is called.
  22427. this._isDirty = true;
  22428. }
  22429. // Members
  22430. Skeleton.prototype.getTransformMatrices = function () {
  22431. return this._transformMatrices;
  22432. };
  22433. Skeleton.prototype.getScene = function () {
  22434. return this._scene;
  22435. };
  22436. // Methods
  22437. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22438. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22439. };
  22440. Skeleton.prototype.deleteAnimationRange = function (name) {
  22441. for (var index = 0; index < this._ranges.length; index++) {
  22442. if (this._ranges[index].name === name) {
  22443. this._ranges.splice(index, 1);
  22444. return;
  22445. }
  22446. }
  22447. };
  22448. Skeleton.prototype.getAnimationRange = function (name) {
  22449. for (var index = 0; index < this._ranges.length; index++) {
  22450. if (this._ranges[index].name === name) {
  22451. return this._ranges[index];
  22452. }
  22453. }
  22454. return null;
  22455. };
  22456. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22457. var range = this.getAnimationRange(name);
  22458. if (!range) {
  22459. return null;
  22460. }
  22461. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22462. };
  22463. Skeleton.prototype._markAsDirty = function () {
  22464. this._isDirty = true;
  22465. };
  22466. Skeleton.prototype.prepare = function () {
  22467. if (!this._isDirty) {
  22468. return;
  22469. }
  22470. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22471. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22472. }
  22473. for (var index = 0; index < this.bones.length; index++) {
  22474. var bone = this.bones[index];
  22475. var parentBone = bone.getParent();
  22476. if (parentBone) {
  22477. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22478. }
  22479. else {
  22480. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22481. }
  22482. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22483. }
  22484. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22485. this._isDirty = false;
  22486. this._scene._activeBones += this.bones.length;
  22487. };
  22488. Skeleton.prototype.getAnimatables = function () {
  22489. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22490. this._animatables = [];
  22491. for (var index = 0; index < this.bones.length; index++) {
  22492. this._animatables.push(this.bones[index]);
  22493. }
  22494. }
  22495. return this._animatables;
  22496. };
  22497. Skeleton.prototype.clone = function (name, id) {
  22498. var result = new Skeleton(name, id || name, this._scene);
  22499. for (var index = 0; index < this.bones.length; index++) {
  22500. var source = this.bones[index];
  22501. var parentBone = null;
  22502. if (source.getParent()) {
  22503. var parentIndex = this.bones.indexOf(source.getParent());
  22504. parentBone = result.bones[parentIndex];
  22505. }
  22506. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22507. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22508. }
  22509. return result;
  22510. };
  22511. Skeleton.prototype.dispose = function () {
  22512. // Animations
  22513. this.getScene().stopAnimation(this);
  22514. // Remove from scene
  22515. this.getScene().removeSkeleton(this);
  22516. };
  22517. return Skeleton;
  22518. })();
  22519. BABYLON.Skeleton = Skeleton;
  22520. })(BABYLON || (BABYLON = {}));
  22521. var BABYLON;
  22522. (function (BABYLON) {
  22523. var PostProcess = (function () {
  22524. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22526. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22527. this.name = name;
  22528. this.width = -1;
  22529. this.height = -1;
  22530. this._reusable = false;
  22531. this._textures = new BABYLON.SmartArray(2);
  22532. this._currentRenderTextureInd = 0;
  22533. if (camera != null) {
  22534. this._camera = camera;
  22535. this._scene = camera.getScene();
  22536. camera.attachPostProcess(this);
  22537. this._engine = this._scene.getEngine();
  22538. }
  22539. else {
  22540. this._engine = engine;
  22541. }
  22542. this._renderRatio = ratio;
  22543. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22544. this._reusable = reusable || false;
  22545. this._textureType = textureType;
  22546. samplers = samplers || [];
  22547. samplers.push("textureSampler");
  22548. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22549. }
  22550. PostProcess.prototype.isReusable = function () {
  22551. return this._reusable;
  22552. };
  22553. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22554. camera = camera || this._camera;
  22555. var scene = camera.getScene();
  22556. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22557. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22558. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22559. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22560. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22561. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22562. if (this._textures.length > 0) {
  22563. for (var i = 0; i < this._textures.length; i++) {
  22564. this._engine._releaseTexture(this._textures.data[i]);
  22565. }
  22566. this._textures.reset();
  22567. }
  22568. this.width = desiredWidth;
  22569. this.height = desiredHeight;
  22570. 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 }));
  22571. if (this._reusable) {
  22572. 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 }));
  22573. }
  22574. if (this.onSizeChanged) {
  22575. this.onSizeChanged();
  22576. }
  22577. }
  22578. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22579. if (this.onActivate) {
  22580. this.onActivate(camera);
  22581. }
  22582. // Clear
  22583. if (this.clearColor) {
  22584. this._engine.clear(this.clearColor, true, true);
  22585. }
  22586. else {
  22587. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22588. }
  22589. if (this._reusable) {
  22590. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22591. }
  22592. };
  22593. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22594. get: function () {
  22595. return this._effect.isSupported;
  22596. },
  22597. enumerable: true,
  22598. configurable: true
  22599. });
  22600. PostProcess.prototype.apply = function () {
  22601. // Check
  22602. if (!this._effect.isReady())
  22603. return null;
  22604. // States
  22605. this._engine.enableEffect(this._effect);
  22606. this._engine.setState(false);
  22607. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22608. this._engine.setDepthBuffer(false);
  22609. this._engine.setDepthWrite(false);
  22610. // Texture
  22611. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22612. // Parameters
  22613. if (this.onApply) {
  22614. this.onApply(this._effect);
  22615. }
  22616. return this._effect;
  22617. };
  22618. PostProcess.prototype.dispose = function (camera) {
  22619. camera = camera || this._camera;
  22620. if (this._textures.length > 0) {
  22621. for (var i = 0; i < this._textures.length; i++) {
  22622. this._engine._releaseTexture(this._textures.data[i]);
  22623. }
  22624. this._textures.reset();
  22625. }
  22626. if (!camera) {
  22627. return;
  22628. }
  22629. camera.detachPostProcess(this);
  22630. var index = camera._postProcesses.indexOf(this);
  22631. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22632. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22633. }
  22634. };
  22635. return PostProcess;
  22636. })();
  22637. BABYLON.PostProcess = PostProcess;
  22638. })(BABYLON || (BABYLON = {}));
  22639. var BABYLON;
  22640. (function (BABYLON) {
  22641. var PostProcessManager = (function () {
  22642. function PostProcessManager(scene) {
  22643. this._vertexDeclaration = [2];
  22644. this._vertexStrideSize = 2 * 4;
  22645. this._scene = scene;
  22646. }
  22647. PostProcessManager.prototype._prepareBuffers = function () {
  22648. if (this._vertexBuffer) {
  22649. return;
  22650. }
  22651. // VBO
  22652. var vertices = [];
  22653. vertices.push(1, 1);
  22654. vertices.push(-1, 1);
  22655. vertices.push(-1, -1);
  22656. vertices.push(1, -1);
  22657. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22658. // Indices
  22659. var indices = [];
  22660. indices.push(0);
  22661. indices.push(1);
  22662. indices.push(2);
  22663. indices.push(0);
  22664. indices.push(2);
  22665. indices.push(3);
  22666. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22667. };
  22668. // Methods
  22669. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22670. var postProcesses = this._scene.activeCamera._postProcesses;
  22671. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22672. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22673. return false;
  22674. }
  22675. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22676. return true;
  22677. };
  22678. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22679. var engine = this._scene.getEngine();
  22680. for (var index = 0; index < postProcesses.length; index++) {
  22681. if (index < postProcesses.length - 1) {
  22682. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22683. }
  22684. else {
  22685. if (targetTexture) {
  22686. engine.bindFramebuffer(targetTexture);
  22687. }
  22688. else {
  22689. engine.restoreDefaultFramebuffer();
  22690. }
  22691. }
  22692. var pp = postProcesses[index];
  22693. var effect = pp.apply();
  22694. if (effect) {
  22695. if (pp.onBeforeRender) {
  22696. pp.onBeforeRender(effect);
  22697. }
  22698. // VBOs
  22699. this._prepareBuffers();
  22700. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22701. // Draw order
  22702. engine.draw(true, 0, 6);
  22703. if (pp.onAfterRender) {
  22704. pp.onAfterRender(effect);
  22705. }
  22706. }
  22707. }
  22708. // Restore depth buffer
  22709. engine.setDepthBuffer(true);
  22710. engine.setDepthWrite(true);
  22711. };
  22712. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22713. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22714. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22715. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22716. return;
  22717. }
  22718. var engine = this._scene.getEngine();
  22719. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22720. if (index < postProcessesTakenIndices.length - 1) {
  22721. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22722. }
  22723. else {
  22724. if (targetTexture) {
  22725. engine.bindFramebuffer(targetTexture, faceIndex);
  22726. }
  22727. else {
  22728. engine.restoreDefaultFramebuffer();
  22729. }
  22730. }
  22731. if (doNotPresent) {
  22732. break;
  22733. }
  22734. var pp = postProcesses[postProcessesTakenIndices[index]];
  22735. var effect = pp.apply();
  22736. if (effect) {
  22737. if (pp.onBeforeRender) {
  22738. pp.onBeforeRender(effect);
  22739. }
  22740. // VBOs
  22741. this._prepareBuffers();
  22742. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22743. // Draw order
  22744. engine.draw(true, 0, 6);
  22745. if (pp.onAfterRender) {
  22746. pp.onAfterRender(effect);
  22747. }
  22748. }
  22749. }
  22750. // Restore depth buffer
  22751. engine.setDepthBuffer(true);
  22752. engine.setDepthWrite(true);
  22753. };
  22754. PostProcessManager.prototype.dispose = function () {
  22755. if (this._vertexBuffer) {
  22756. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22757. this._vertexBuffer = null;
  22758. }
  22759. if (this._indexBuffer) {
  22760. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22761. this._indexBuffer = null;
  22762. }
  22763. };
  22764. return PostProcessManager;
  22765. })();
  22766. BABYLON.PostProcessManager = PostProcessManager;
  22767. })(BABYLON || (BABYLON = {}));
  22768. var BABYLON;
  22769. (function (BABYLON) {
  22770. var PassPostProcess = (function (_super) {
  22771. __extends(PassPostProcess, _super);
  22772. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22773. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22774. }
  22775. return PassPostProcess;
  22776. })(BABYLON.PostProcess);
  22777. BABYLON.PassPostProcess = PassPostProcess;
  22778. })(BABYLON || (BABYLON = {}));
  22779. var BABYLON;
  22780. (function (BABYLON) {
  22781. var PhysicsEngine = (function () {
  22782. function PhysicsEngine(plugin) {
  22783. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22784. }
  22785. PhysicsEngine.prototype._initialize = function (gravity) {
  22786. this._currentPlugin.initialize();
  22787. this._setGravity(gravity);
  22788. };
  22789. PhysicsEngine.prototype._runOneStep = function (delta) {
  22790. if (delta > 0.1) {
  22791. delta = 0.1;
  22792. }
  22793. else if (delta <= 0) {
  22794. delta = 1.0 / 60.0;
  22795. }
  22796. this._currentPlugin.runOneStep(delta);
  22797. };
  22798. PhysicsEngine.prototype._setGravity = function (gravity) {
  22799. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22800. this._currentPlugin.setGravity(this.gravity);
  22801. };
  22802. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22803. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22804. };
  22805. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22806. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22807. };
  22808. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22809. this._currentPlugin.unregisterMesh(mesh);
  22810. };
  22811. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22812. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22813. };
  22814. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22815. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22816. };
  22817. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22818. this._currentPlugin.updateBodyPosition(mesh);
  22819. };
  22820. PhysicsEngine.prototype.dispose = function () {
  22821. this._currentPlugin.dispose();
  22822. };
  22823. PhysicsEngine.prototype.isSupported = function () {
  22824. return this._currentPlugin.isSupported();
  22825. };
  22826. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22827. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22828. };
  22829. // Statics
  22830. PhysicsEngine.NoImpostor = 0;
  22831. PhysicsEngine.SphereImpostor = 1;
  22832. PhysicsEngine.BoxImpostor = 2;
  22833. PhysicsEngine.PlaneImpostor = 3;
  22834. PhysicsEngine.MeshImpostor = 4;
  22835. PhysicsEngine.CapsuleImpostor = 5;
  22836. PhysicsEngine.ConeImpostor = 6;
  22837. PhysicsEngine.CylinderImpostor = 7;
  22838. PhysicsEngine.ConvexHullImpostor = 8;
  22839. PhysicsEngine.HeightmapImpostor = 9;
  22840. PhysicsEngine.Epsilon = 0.001;
  22841. return PhysicsEngine;
  22842. })();
  22843. BABYLON.PhysicsEngine = PhysicsEngine;
  22844. })(BABYLON || (BABYLON = {}));
  22845. var BABYLON;
  22846. (function (BABYLON) {
  22847. var VertexData = (function () {
  22848. function VertexData() {
  22849. }
  22850. VertexData.prototype.set = function (data, kind) {
  22851. switch (kind) {
  22852. case BABYLON.VertexBuffer.PositionKind:
  22853. this.positions = data;
  22854. break;
  22855. case BABYLON.VertexBuffer.NormalKind:
  22856. this.normals = data;
  22857. break;
  22858. case BABYLON.VertexBuffer.UVKind:
  22859. this.uvs = data;
  22860. break;
  22861. case BABYLON.VertexBuffer.UV2Kind:
  22862. this.uvs2 = data;
  22863. break;
  22864. case BABYLON.VertexBuffer.UV3Kind:
  22865. this.uvs3 = data;
  22866. break;
  22867. case BABYLON.VertexBuffer.UV4Kind:
  22868. this.uvs4 = data;
  22869. break;
  22870. case BABYLON.VertexBuffer.UV5Kind:
  22871. this.uvs5 = data;
  22872. break;
  22873. case BABYLON.VertexBuffer.UV6Kind:
  22874. this.uvs6 = data;
  22875. break;
  22876. case BABYLON.VertexBuffer.ColorKind:
  22877. this.colors = data;
  22878. break;
  22879. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22880. this.matricesIndices = data;
  22881. break;
  22882. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22883. this.matricesWeights = data;
  22884. break;
  22885. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22886. this.matricesIndicesExtra = data;
  22887. break;
  22888. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22889. this.matricesWeightsExtra = data;
  22890. break;
  22891. }
  22892. };
  22893. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22894. this._applyTo(mesh, updatable);
  22895. };
  22896. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22897. this._applyTo(geometry, updatable);
  22898. };
  22899. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22900. this._update(mesh);
  22901. };
  22902. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22903. this._update(geometry);
  22904. };
  22905. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22906. if (this.positions) {
  22907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22908. }
  22909. if (this.normals) {
  22910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22911. }
  22912. if (this.uvs) {
  22913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22914. }
  22915. if (this.uvs2) {
  22916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22917. }
  22918. if (this.uvs3) {
  22919. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22920. }
  22921. if (this.uvs4) {
  22922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22923. }
  22924. if (this.uvs5) {
  22925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22926. }
  22927. if (this.uvs6) {
  22928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22929. }
  22930. if (this.colors) {
  22931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22932. }
  22933. if (this.matricesIndices) {
  22934. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22935. }
  22936. if (this.matricesWeights) {
  22937. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22938. }
  22939. if (this.matricesIndicesExtra) {
  22940. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22941. }
  22942. if (this.matricesWeightsExtra) {
  22943. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22944. }
  22945. if (this.indices) {
  22946. meshOrGeometry.setIndices(this.indices);
  22947. }
  22948. };
  22949. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22950. if (this.positions) {
  22951. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22952. }
  22953. if (this.normals) {
  22954. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22955. }
  22956. if (this.uvs) {
  22957. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22958. }
  22959. if (this.uvs2) {
  22960. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22961. }
  22962. if (this.uvs3) {
  22963. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22964. }
  22965. if (this.uvs4) {
  22966. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22967. }
  22968. if (this.uvs5) {
  22969. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22970. }
  22971. if (this.uvs6) {
  22972. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22973. }
  22974. if (this.colors) {
  22975. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22976. }
  22977. if (this.matricesIndices) {
  22978. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22979. }
  22980. if (this.matricesWeights) {
  22981. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22982. }
  22983. if (this.matricesIndicesExtra) {
  22984. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22985. }
  22986. if (this.matricesWeightsExtra) {
  22987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22988. }
  22989. if (this.indices) {
  22990. meshOrGeometry.setIndices(this.indices);
  22991. }
  22992. };
  22993. VertexData.prototype.transform = function (matrix) {
  22994. var transformed = BABYLON.Vector3.Zero();
  22995. var index;
  22996. if (this.positions) {
  22997. var position = BABYLON.Vector3.Zero();
  22998. for (index = 0; index < this.positions.length; index += 3) {
  22999. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23000. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23001. this.positions[index] = transformed.x;
  23002. this.positions[index + 1] = transformed.y;
  23003. this.positions[index + 2] = transformed.z;
  23004. }
  23005. }
  23006. if (this.normals) {
  23007. var normal = BABYLON.Vector3.Zero();
  23008. for (index = 0; index < this.normals.length; index += 3) {
  23009. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23010. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23011. this.normals[index] = transformed.x;
  23012. this.normals[index + 1] = transformed.y;
  23013. this.normals[index + 2] = transformed.z;
  23014. }
  23015. }
  23016. };
  23017. VertexData.prototype.merge = function (other) {
  23018. var index;
  23019. if (other.indices) {
  23020. if (!this.indices) {
  23021. this.indices = [];
  23022. }
  23023. var offset = this.positions ? this.positions.length / 3 : 0;
  23024. for (index = 0; index < other.indices.length; index++) {
  23025. this.indices.push(other.indices[index] + offset);
  23026. }
  23027. }
  23028. if (other.positions) {
  23029. if (!this.positions) {
  23030. this.positions = [];
  23031. }
  23032. for (index = 0; index < other.positions.length; index++) {
  23033. this.positions.push(other.positions[index]);
  23034. }
  23035. }
  23036. if (other.normals) {
  23037. if (!this.normals) {
  23038. this.normals = [];
  23039. }
  23040. for (index = 0; index < other.normals.length; index++) {
  23041. this.normals.push(other.normals[index]);
  23042. }
  23043. }
  23044. if (other.uvs) {
  23045. if (!this.uvs) {
  23046. this.uvs = [];
  23047. }
  23048. for (index = 0; index < other.uvs.length; index++) {
  23049. this.uvs.push(other.uvs[index]);
  23050. }
  23051. }
  23052. if (other.uvs2) {
  23053. if (!this.uvs2) {
  23054. this.uvs2 = [];
  23055. }
  23056. for (index = 0; index < other.uvs2.length; index++) {
  23057. this.uvs2.push(other.uvs2[index]);
  23058. }
  23059. }
  23060. if (other.uvs3) {
  23061. if (!this.uvs3) {
  23062. this.uvs3 = [];
  23063. }
  23064. for (index = 0; index < other.uvs3.length; index++) {
  23065. this.uvs3.push(other.uvs3[index]);
  23066. }
  23067. }
  23068. if (other.uvs4) {
  23069. if (!this.uvs4) {
  23070. this.uvs4 = [];
  23071. }
  23072. for (index = 0; index < other.uvs4.length; index++) {
  23073. this.uvs4.push(other.uvs4[index]);
  23074. }
  23075. }
  23076. if (other.uvs5) {
  23077. if (!this.uvs5) {
  23078. this.uvs5 = [];
  23079. }
  23080. for (index = 0; index < other.uvs5.length; index++) {
  23081. this.uvs5.push(other.uvs5[index]);
  23082. }
  23083. }
  23084. if (other.uvs6) {
  23085. if (!this.uvs6) {
  23086. this.uvs6 = [];
  23087. }
  23088. for (index = 0; index < other.uvs6.length; index++) {
  23089. this.uvs6.push(other.uvs6[index]);
  23090. }
  23091. }
  23092. if (other.matricesIndices) {
  23093. if (!this.matricesIndices) {
  23094. this.matricesIndices = [];
  23095. }
  23096. for (index = 0; index < other.matricesIndices.length; index++) {
  23097. this.matricesIndices.push(other.matricesIndices[index]);
  23098. }
  23099. }
  23100. if (other.matricesWeights) {
  23101. if (!this.matricesWeights) {
  23102. this.matricesWeights = [];
  23103. }
  23104. for (index = 0; index < other.matricesWeights.length; index++) {
  23105. this.matricesWeights.push(other.matricesWeights[index]);
  23106. }
  23107. }
  23108. if (other.matricesIndicesExtra) {
  23109. if (!this.matricesIndicesExtra) {
  23110. this.matricesIndicesExtra = [];
  23111. }
  23112. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  23113. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  23114. }
  23115. }
  23116. if (other.matricesWeightsExtra) {
  23117. if (!this.matricesWeightsExtra) {
  23118. this.matricesWeightsExtra = [];
  23119. }
  23120. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  23121. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  23122. }
  23123. }
  23124. if (other.colors) {
  23125. if (!this.colors) {
  23126. this.colors = [];
  23127. }
  23128. for (index = 0; index < other.colors.length; index++) {
  23129. this.colors.push(other.colors[index]);
  23130. }
  23131. }
  23132. };
  23133. // Statics
  23134. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23135. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23136. };
  23137. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23138. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23139. };
  23140. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23141. var result = new VertexData();
  23142. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23143. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23144. }
  23145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23146. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23147. }
  23148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23149. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23150. }
  23151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23152. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23153. }
  23154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23155. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23156. }
  23157. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23158. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23159. }
  23160. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23161. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23162. }
  23163. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23164. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23165. }
  23166. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23167. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23168. }
  23169. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23170. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23171. }
  23172. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23173. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23174. }
  23175. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23176. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23177. }
  23178. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23179. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23180. }
  23181. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23182. return result;
  23183. };
  23184. VertexData.CreateRibbon = function (options) {
  23185. var pathArray = options.pathArray;
  23186. var closeArray = options.closeArray || false;
  23187. var closePath = options.closePath || false;
  23188. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23189. var offset = options.offset || defaultOffset;
  23190. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23192. var positions = [];
  23193. var indices = [];
  23194. var normals = [];
  23195. var uvs = [];
  23196. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23197. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23198. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23199. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23200. var minlg; // minimal length among all paths from pathArray
  23201. var lg = []; // array of path lengths : nb of vertex per path
  23202. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23203. var p; // path iterator
  23204. var i; // point iterator
  23205. var j; // point iterator
  23206. // if single path in pathArray
  23207. if (pathArray.length < 2) {
  23208. var ar1 = [];
  23209. var ar2 = [];
  23210. for (i = 0; i < pathArray[0].length - offset; i++) {
  23211. ar1.push(pathArray[0][i]);
  23212. ar2.push(pathArray[0][i + offset]);
  23213. }
  23214. pathArray = [ar1, ar2];
  23215. }
  23216. // positions and horizontal distances (u)
  23217. var idc = 0;
  23218. var closePathCorr = (closePath) ? 1 : 0;
  23219. var path;
  23220. var l;
  23221. minlg = pathArray[0].length;
  23222. var vectlg;
  23223. var dist;
  23224. for (p = 0; p < pathArray.length; p++) {
  23225. uTotalDistance[p] = 0;
  23226. us[p] = [0];
  23227. path = pathArray[p];
  23228. l = path.length;
  23229. minlg = (minlg < l) ? minlg : l;
  23230. j = 0;
  23231. while (j < l) {
  23232. positions.push(path[j].x, path[j].y, path[j].z);
  23233. if (j > 0) {
  23234. vectlg = path[j].subtract(path[j - 1]).length();
  23235. dist = vectlg + uTotalDistance[p];
  23236. us[p].push(dist);
  23237. uTotalDistance[p] = dist;
  23238. }
  23239. j++;
  23240. }
  23241. if (closePath) {
  23242. j--;
  23243. positions.push(path[0].x, path[0].y, path[0].z);
  23244. vectlg = path[j].subtract(path[0]).length();
  23245. dist = vectlg + uTotalDistance[p];
  23246. us[p].push(dist);
  23247. uTotalDistance[p] = dist;
  23248. }
  23249. lg[p] = l + closePathCorr;
  23250. idx[p] = idc;
  23251. idc += (l + closePathCorr);
  23252. }
  23253. // vertical distances (v)
  23254. var path1;
  23255. var path2;
  23256. var vertex1;
  23257. var vertex2;
  23258. for (i = 0; i < minlg + closePathCorr; i++) {
  23259. vTotalDistance[i] = 0;
  23260. vs[i] = [0];
  23261. for (p = 0; p < pathArray.length - 1; p++) {
  23262. path1 = pathArray[p];
  23263. path2 = pathArray[p + 1];
  23264. if (i === minlg) {
  23265. vertex1 = path1[0];
  23266. vertex2 = path2[0];
  23267. }
  23268. else {
  23269. vertex1 = path1[i];
  23270. vertex2 = path2[i];
  23271. }
  23272. vectlg = vertex2.subtract(vertex1).length();
  23273. dist = vectlg + vTotalDistance[i];
  23274. vs[i].push(dist);
  23275. vTotalDistance[i] = dist;
  23276. }
  23277. if (closeArray) {
  23278. path1 = pathArray[p];
  23279. path2 = pathArray[0];
  23280. if (i === minlg) {
  23281. vertex2 = path2[0];
  23282. }
  23283. vectlg = vertex2.subtract(vertex1).length();
  23284. dist = vectlg + vTotalDistance[i];
  23285. vTotalDistance[i] = dist;
  23286. }
  23287. }
  23288. // uvs
  23289. var u;
  23290. var v;
  23291. for (p = 0; p < pathArray.length; p++) {
  23292. for (i = 0; i < minlg + closePathCorr; i++) {
  23293. u = us[p][i] / uTotalDistance[p];
  23294. v = vs[i][p] / vTotalDistance[i];
  23295. uvs.push(u, v);
  23296. }
  23297. }
  23298. // indices
  23299. p = 0; // path index
  23300. var pi = 0; // positions array index
  23301. var l1 = lg[p] - 1; // path1 length
  23302. var l2 = lg[p + 1] - 1; // path2 length
  23303. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23304. var shft = idx[1] - idx[0]; // shift
  23305. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23306. while (pi <= min && p < path1nb) {
  23307. // 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
  23308. indices.push(pi, pi + shft, pi + 1);
  23309. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23310. pi += 1;
  23311. if (pi === min) {
  23312. p++;
  23313. if (p === lg.length - 1) {
  23314. shft = idx[0] - idx[p];
  23315. l1 = lg[p] - 1;
  23316. l2 = lg[0] - 1;
  23317. }
  23318. else {
  23319. shft = idx[p + 1] - idx[p];
  23320. l1 = lg[p] - 1;
  23321. l2 = lg[p + 1] - 1;
  23322. }
  23323. pi = idx[p];
  23324. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23325. }
  23326. }
  23327. // normals
  23328. VertexData.ComputeNormals(positions, indices, normals);
  23329. if (closePath) {
  23330. var indexFirst = 0;
  23331. var indexLast = 0;
  23332. for (p = 0; p < pathArray.length; p++) {
  23333. indexFirst = idx[p] * 3;
  23334. if (p + 1 < pathArray.length) {
  23335. indexLast = (idx[p + 1] - 1) * 3;
  23336. }
  23337. else {
  23338. indexLast = normals.length - 3;
  23339. }
  23340. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23341. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23342. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23343. normals[indexLast] = normals[indexFirst];
  23344. normals[indexLast + 1] = normals[indexFirst + 1];
  23345. normals[indexLast + 2] = normals[indexFirst + 2];
  23346. }
  23347. }
  23348. // sides
  23349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23350. // Result
  23351. var vertexData = new VertexData();
  23352. vertexData.indices = indices;
  23353. vertexData.positions = positions;
  23354. vertexData.normals = normals;
  23355. vertexData.uvs = uvs;
  23356. if (closePath) {
  23357. vertexData._idx = idx;
  23358. }
  23359. return vertexData;
  23360. };
  23361. VertexData.CreateBox = function (options) {
  23362. var normalsSource = [
  23363. new BABYLON.Vector3(0, 0, 1),
  23364. new BABYLON.Vector3(0, 0, -1),
  23365. new BABYLON.Vector3(1, 0, 0),
  23366. new BABYLON.Vector3(-1, 0, 0),
  23367. new BABYLON.Vector3(0, 1, 0),
  23368. new BABYLON.Vector3(0, -1, 0)
  23369. ];
  23370. var indices = [];
  23371. var positions = [];
  23372. var normals = [];
  23373. var uvs = [];
  23374. var width = options.width || options.size || 1;
  23375. var height = options.height || options.size || 1;
  23376. var depth = options.depth || options.size || 1;
  23377. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23378. var faceUV = options.faceUV || new Array(6);
  23379. var faceColors = options.faceColors;
  23380. var colors = [];
  23381. // default face colors and UV if undefined
  23382. for (var f = 0; f < 6; f++) {
  23383. if (faceUV[f] === undefined) {
  23384. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23385. }
  23386. if (faceColors && faceColors[f] === undefined) {
  23387. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23388. }
  23389. }
  23390. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23391. // Create each face in turn.
  23392. for (var index = 0; index < normalsSource.length; index++) {
  23393. var normal = normalsSource[index];
  23394. // Get two vectors perpendicular to the face normal and to each other.
  23395. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23396. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23397. // Six indices (two triangles) per face.
  23398. var verticesLength = positions.length / 3;
  23399. indices.push(verticesLength);
  23400. indices.push(verticesLength + 1);
  23401. indices.push(verticesLength + 2);
  23402. indices.push(verticesLength);
  23403. indices.push(verticesLength + 2);
  23404. indices.push(verticesLength + 3);
  23405. // Four vertices per face.
  23406. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23407. positions.push(vertex.x, vertex.y, vertex.z);
  23408. normals.push(normal.x, normal.y, normal.z);
  23409. uvs.push(faceUV[index].z, faceUV[index].w);
  23410. if (faceColors) {
  23411. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23412. }
  23413. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23414. positions.push(vertex.x, vertex.y, vertex.z);
  23415. normals.push(normal.x, normal.y, normal.z);
  23416. uvs.push(faceUV[index].x, faceUV[index].w);
  23417. if (faceColors) {
  23418. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23419. }
  23420. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23421. positions.push(vertex.x, vertex.y, vertex.z);
  23422. normals.push(normal.x, normal.y, normal.z);
  23423. uvs.push(faceUV[index].x, faceUV[index].y);
  23424. if (faceColors) {
  23425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23426. }
  23427. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23428. positions.push(vertex.x, vertex.y, vertex.z);
  23429. normals.push(normal.x, normal.y, normal.z);
  23430. uvs.push(faceUV[index].z, faceUV[index].y);
  23431. if (faceColors) {
  23432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23433. }
  23434. }
  23435. // sides
  23436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23437. // Result
  23438. var vertexData = new VertexData();
  23439. vertexData.indices = indices;
  23440. vertexData.positions = positions;
  23441. vertexData.normals = normals;
  23442. vertexData.uvs = uvs;
  23443. if (faceColors) {
  23444. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23445. vertexData.colors = totalColors;
  23446. }
  23447. return vertexData;
  23448. };
  23449. VertexData.CreateSphere = function (options) {
  23450. var segments = options.segments || 32;
  23451. var diameterX = options.diameterX || options.diameter || 1;
  23452. var diameterY = options.diameterY || options.diameter || 1;
  23453. var diameterZ = options.diameterZ || options.diameter || 1;
  23454. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23455. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23456. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23457. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23458. var totalZRotationSteps = 2 + segments;
  23459. var totalYRotationSteps = 2 * totalZRotationSteps;
  23460. var indices = [];
  23461. var positions = [];
  23462. var normals = [];
  23463. var uvs = [];
  23464. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23465. var normalizedZ = zRotationStep / totalZRotationSteps;
  23466. var angleZ = normalizedZ * Math.PI * slice;
  23467. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23468. var normalizedY = yRotationStep / totalYRotationSteps;
  23469. var angleY = normalizedY * Math.PI * 2 * arc;
  23470. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23471. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23472. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23473. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23474. var vertex = complete.multiply(radius);
  23475. var normal = BABYLON.Vector3.Normalize(vertex);
  23476. positions.push(vertex.x, vertex.y, vertex.z);
  23477. normals.push(normal.x, normal.y, normal.z);
  23478. uvs.push(normalizedY, normalizedZ);
  23479. }
  23480. if (zRotationStep > 0) {
  23481. var verticesCount = positions.length / 3;
  23482. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23483. indices.push((firstIndex));
  23484. indices.push((firstIndex + 1));
  23485. indices.push(firstIndex + totalYRotationSteps + 1);
  23486. indices.push((firstIndex + totalYRotationSteps + 1));
  23487. indices.push((firstIndex + 1));
  23488. indices.push((firstIndex + totalYRotationSteps + 2));
  23489. }
  23490. }
  23491. }
  23492. // Sides
  23493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23494. // Result
  23495. var vertexData = new VertexData();
  23496. vertexData.indices = indices;
  23497. vertexData.positions = positions;
  23498. vertexData.normals = normals;
  23499. vertexData.uvs = uvs;
  23500. return vertexData;
  23501. };
  23502. // Cylinder and cone
  23503. VertexData.CreateCylinder = function (options) {
  23504. var height = options.height || 2;
  23505. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23506. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23507. var tessellation = options.tessellation || 24;
  23508. var subdivisions = options.subdivisions || 1;
  23509. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23510. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23511. var faceUV = options.faceUV || new Array(3);
  23512. var faceColors = options.faceColors;
  23513. // default face colors and UV if undefined
  23514. for (var f = 0; f < 3; f++) {
  23515. if (faceColors && faceColors[f] === undefined) {
  23516. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23517. }
  23518. if (faceUV && faceUV[f] === undefined) {
  23519. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23520. }
  23521. }
  23522. var indices = [];
  23523. var positions = [];
  23524. var normals = [];
  23525. var uvs = [];
  23526. var colors = [];
  23527. var angle_step = Math.PI * 2 * arc / tessellation;
  23528. var angle;
  23529. var h;
  23530. var radius;
  23531. var tan = (diameterBottom - diameterTop) / 2 / height;
  23532. var ringVertex = BABYLON.Vector3.Zero();
  23533. var ringNormal = BABYLON.Vector3.Zero();
  23534. // positions, normals, uvs
  23535. var i;
  23536. var j;
  23537. for (i = 0; i <= subdivisions; i++) {
  23538. h = i / subdivisions;
  23539. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23540. for (j = 0; j <= tessellation; j++) {
  23541. angle = j * angle_step;
  23542. ringVertex.x = Math.cos(-angle) * radius;
  23543. ringVertex.y = -height / 2 + h * height;
  23544. ringVertex.z = Math.sin(-angle) * radius;
  23545. if (diameterTop === 0 && i === subdivisions) {
  23546. // if no top cap, reuse former normals
  23547. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23548. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23549. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23550. }
  23551. else {
  23552. ringNormal.x = ringVertex.x;
  23553. ringNormal.z = ringVertex.z;
  23554. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23555. ringNormal.normalize();
  23556. }
  23557. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23558. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23559. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23560. if (faceColors) {
  23561. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23562. }
  23563. }
  23564. }
  23565. // indices
  23566. for (i = 0; i < subdivisions; i++) {
  23567. for (j = 0; j < tessellation; j++) {
  23568. var i0 = i * (tessellation + 1) + j;
  23569. var i1 = (i + 1) * (tessellation + 1) + j;
  23570. var i2 = i * (tessellation + 1) + (j + 1);
  23571. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23572. indices.push(i0, i1, i2);
  23573. indices.push(i3, i2, i1);
  23574. }
  23575. }
  23576. // Caps
  23577. var createCylinderCap = function (isTop) {
  23578. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23579. if (radius === 0) {
  23580. return;
  23581. }
  23582. // Cap positions, normals & uvs
  23583. var angle;
  23584. var circleVector;
  23585. var i;
  23586. var u = (isTop) ? faceUV[2] : faceUV[0];
  23587. var c;
  23588. if (faceColors) {
  23589. c = (isTop) ? faceColors[2] : faceColors[0];
  23590. }
  23591. // cap center
  23592. var vbase = positions.length / 3;
  23593. var offset = isTop ? height / 2 : -height / 2;
  23594. var center = new BABYLON.Vector3(0, offset, 0);
  23595. positions.push(center.x, center.y, center.z);
  23596. normals.push(0, isTop ? 1 : -1, 0);
  23597. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23598. if (faceColors) {
  23599. colors.push(c.r, c.g, c.b, c.a);
  23600. }
  23601. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23602. for (i = 0; i <= tessellation; i++) {
  23603. angle = Math.PI * 2 * i * arc / tessellation;
  23604. var cos = Math.cos(-angle);
  23605. var sin = Math.sin(-angle);
  23606. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23607. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23608. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23609. normals.push(0, isTop ? 1 : -1, 0);
  23610. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23611. if (faceColors) {
  23612. colors.push(c.r, c.g, c.b, c.a);
  23613. }
  23614. }
  23615. // Cap indices
  23616. for (i = 0; i < tessellation; i++) {
  23617. if (!isTop) {
  23618. indices.push(vbase);
  23619. indices.push(vbase + (i + 1));
  23620. indices.push(vbase + (i + 2));
  23621. }
  23622. else {
  23623. indices.push(vbase);
  23624. indices.push(vbase + (i + 2));
  23625. indices.push(vbase + (i + 1));
  23626. }
  23627. }
  23628. };
  23629. // add caps to geometry
  23630. createCylinderCap(false);
  23631. createCylinderCap(true);
  23632. // Sides
  23633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23634. var vertexData = new VertexData();
  23635. vertexData.indices = indices;
  23636. vertexData.positions = positions;
  23637. vertexData.normals = normals;
  23638. vertexData.uvs = uvs;
  23639. if (faceColors) {
  23640. vertexData.colors = colors;
  23641. }
  23642. return vertexData;
  23643. };
  23644. VertexData.CreateTorus = function (options) {
  23645. var indices = [];
  23646. var positions = [];
  23647. var normals = [];
  23648. var uvs = [];
  23649. var diameter = options.diameter || 1;
  23650. var thickness = options.thickness || 0.5;
  23651. var tessellation = options.tessellation || 16;
  23652. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23653. var stride = tessellation + 1;
  23654. for (var i = 0; i <= tessellation; i++) {
  23655. var u = i / tessellation;
  23656. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23657. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23658. for (var j = 0; j <= tessellation; j++) {
  23659. var v = 1 - j / tessellation;
  23660. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23661. var dx = Math.cos(innerAngle);
  23662. var dy = Math.sin(innerAngle);
  23663. // Create a vertex.
  23664. var normal = new BABYLON.Vector3(dx, dy, 0);
  23665. var position = normal.scale(thickness / 2);
  23666. var textureCoordinate = new BABYLON.Vector2(u, v);
  23667. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23668. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23669. positions.push(position.x, position.y, position.z);
  23670. normals.push(normal.x, normal.y, normal.z);
  23671. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23672. // And create indices for two triangles.
  23673. var nextI = (i + 1) % stride;
  23674. var nextJ = (j + 1) % stride;
  23675. indices.push(i * stride + j);
  23676. indices.push(i * stride + nextJ);
  23677. indices.push(nextI * stride + j);
  23678. indices.push(i * stride + nextJ);
  23679. indices.push(nextI * stride + nextJ);
  23680. indices.push(nextI * stride + j);
  23681. }
  23682. }
  23683. // Sides
  23684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23685. // Result
  23686. var vertexData = new VertexData();
  23687. vertexData.indices = indices;
  23688. vertexData.positions = positions;
  23689. vertexData.normals = normals;
  23690. vertexData.uvs = uvs;
  23691. return vertexData;
  23692. };
  23693. VertexData.CreateLines = function (options) {
  23694. var indices = [];
  23695. var positions = [];
  23696. var points = options.points;
  23697. for (var index = 0; index < points.length; index++) {
  23698. positions.push(points[index].x, points[index].y, points[index].z);
  23699. if (index > 0) {
  23700. indices.push(index - 1);
  23701. indices.push(index);
  23702. }
  23703. }
  23704. // Result
  23705. var vertexData = new VertexData();
  23706. vertexData.indices = indices;
  23707. vertexData.positions = positions;
  23708. return vertexData;
  23709. };
  23710. VertexData.CreateDashedLines = function (options) {
  23711. var dashSize = options.dashSize || 3;
  23712. var gapSize = options.gapSize || 1;
  23713. var dashNb = options.dashNb || 200;
  23714. var points = options.points;
  23715. var positions = new Array();
  23716. var indices = new Array();
  23717. var curvect = BABYLON.Vector3.Zero();
  23718. var lg = 0;
  23719. var nb = 0;
  23720. var shft = 0;
  23721. var dashshft = 0;
  23722. var curshft = 0;
  23723. var idx = 0;
  23724. var i = 0;
  23725. for (i = 0; i < points.length - 1; i++) {
  23726. points[i + 1].subtractToRef(points[i], curvect);
  23727. lg += curvect.length();
  23728. }
  23729. shft = lg / dashNb;
  23730. dashshft = dashSize * shft / (dashSize + gapSize);
  23731. for (i = 0; i < points.length - 1; i++) {
  23732. points[i + 1].subtractToRef(points[i], curvect);
  23733. nb = Math.floor(curvect.length() / shft);
  23734. curvect.normalize();
  23735. for (var j = 0; j < nb; j++) {
  23736. curshft = shft * j;
  23737. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23738. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23739. indices.push(idx, idx + 1);
  23740. idx += 2;
  23741. }
  23742. }
  23743. // Result
  23744. var vertexData = new VertexData();
  23745. vertexData.positions = positions;
  23746. vertexData.indices = indices;
  23747. return vertexData;
  23748. };
  23749. VertexData.CreateGround = function (options) {
  23750. var indices = [];
  23751. var positions = [];
  23752. var normals = [];
  23753. var uvs = [];
  23754. var row, col;
  23755. var width = options.width || 1;
  23756. var height = options.height || 1;
  23757. var subdivisions = options.subdivisions || 1;
  23758. for (row = 0; row <= subdivisions; row++) {
  23759. for (col = 0; col <= subdivisions; col++) {
  23760. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23761. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23762. positions.push(position.x, position.y, position.z);
  23763. normals.push(normal.x, normal.y, normal.z);
  23764. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23765. }
  23766. }
  23767. for (row = 0; row < subdivisions; row++) {
  23768. for (col = 0; col < subdivisions; col++) {
  23769. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23770. indices.push(col + 1 + row * (subdivisions + 1));
  23771. indices.push(col + row * (subdivisions + 1));
  23772. indices.push(col + (row + 1) * (subdivisions + 1));
  23773. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23774. indices.push(col + row * (subdivisions + 1));
  23775. }
  23776. }
  23777. // Result
  23778. var vertexData = new VertexData();
  23779. vertexData.indices = indices;
  23780. vertexData.positions = positions;
  23781. vertexData.normals = normals;
  23782. vertexData.uvs = uvs;
  23783. return vertexData;
  23784. };
  23785. VertexData.CreateTiledGround = function (options) {
  23786. var xmin = options.xmin;
  23787. var zmin = options.zmin;
  23788. var xmax = options.xmax;
  23789. var zmax = options.zmax;
  23790. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23791. var precision = options.precision || { w: 1, h: 1 };
  23792. var indices = [];
  23793. var positions = [];
  23794. var normals = [];
  23795. var uvs = [];
  23796. var row, col, tileRow, tileCol;
  23797. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23798. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23799. precision.w = (precision.w < 1) ? 1 : precision.w;
  23800. precision.h = (precision.h < 1) ? 1 : precision.h;
  23801. var tileSize = {
  23802. 'w': (xmax - xmin) / subdivisions.w,
  23803. 'h': (zmax - zmin) / subdivisions.h
  23804. };
  23805. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23806. // Indices
  23807. var base = positions.length / 3;
  23808. var rowLength = precision.w + 1;
  23809. for (row = 0; row < precision.h; row++) {
  23810. for (col = 0; col < precision.w; col++) {
  23811. var square = [
  23812. base + col + row * rowLength,
  23813. base + (col + 1) + row * rowLength,
  23814. base + (col + 1) + (row + 1) * rowLength,
  23815. base + col + (row + 1) * rowLength
  23816. ];
  23817. indices.push(square[1]);
  23818. indices.push(square[2]);
  23819. indices.push(square[3]);
  23820. indices.push(square[0]);
  23821. indices.push(square[1]);
  23822. indices.push(square[3]);
  23823. }
  23824. }
  23825. // Position, normals and uvs
  23826. var position = BABYLON.Vector3.Zero();
  23827. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23828. for (row = 0; row <= precision.h; row++) {
  23829. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23830. for (col = 0; col <= precision.w; col++) {
  23831. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23832. position.y = 0;
  23833. positions.push(position.x, position.y, position.z);
  23834. normals.push(normal.x, normal.y, normal.z);
  23835. uvs.push(col / precision.w, row / precision.h);
  23836. }
  23837. }
  23838. }
  23839. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23840. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23841. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23842. }
  23843. }
  23844. // Result
  23845. var vertexData = new VertexData();
  23846. vertexData.indices = indices;
  23847. vertexData.positions = positions;
  23848. vertexData.normals = normals;
  23849. vertexData.uvs = uvs;
  23850. return vertexData;
  23851. };
  23852. VertexData.CreateGroundFromHeightMap = function (options) {
  23853. var indices = [];
  23854. var positions = [];
  23855. var normals = [];
  23856. var uvs = [];
  23857. var row, col;
  23858. // Vertices
  23859. for (row = 0; row <= options.subdivisions; row++) {
  23860. for (col = 0; col <= options.subdivisions; col++) {
  23861. 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));
  23862. // Compute height
  23863. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23864. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23865. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23866. var r = options.buffer[pos] / 255.0;
  23867. var g = options.buffer[pos + 1] / 255.0;
  23868. var b = options.buffer[pos + 2] / 255.0;
  23869. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23870. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23871. // Add vertex
  23872. positions.push(position.x, position.y, position.z);
  23873. normals.push(0, 0, 0);
  23874. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23875. }
  23876. }
  23877. // Indices
  23878. for (row = 0; row < options.subdivisions; row++) {
  23879. for (col = 0; col < options.subdivisions; col++) {
  23880. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23881. indices.push(col + 1 + row * (options.subdivisions + 1));
  23882. indices.push(col + row * (options.subdivisions + 1));
  23883. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23884. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23885. indices.push(col + row * (options.subdivisions + 1));
  23886. }
  23887. }
  23888. // Normals
  23889. VertexData.ComputeNormals(positions, indices, normals);
  23890. // Result
  23891. var vertexData = new VertexData();
  23892. vertexData.indices = indices;
  23893. vertexData.positions = positions;
  23894. vertexData.normals = normals;
  23895. vertexData.uvs = uvs;
  23896. return vertexData;
  23897. };
  23898. VertexData.CreatePlane = function (options) {
  23899. var indices = [];
  23900. var positions = [];
  23901. var normals = [];
  23902. var uvs = [];
  23903. var width = options.width || options.size || 1;
  23904. var height = options.height || options.size || 1;
  23905. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23906. // Vertices
  23907. var halfWidth = width / 2.0;
  23908. var halfHeight = height / 2.0;
  23909. positions.push(-halfWidth, -halfHeight, 0);
  23910. normals.push(0, 0, -1.0);
  23911. uvs.push(0.0, 0.0);
  23912. positions.push(halfWidth, -halfHeight, 0);
  23913. normals.push(0, 0, -1.0);
  23914. uvs.push(1.0, 0.0);
  23915. positions.push(halfWidth, halfHeight, 0);
  23916. normals.push(0, 0, -1.0);
  23917. uvs.push(1.0, 1.0);
  23918. positions.push(-halfWidth, halfHeight, 0);
  23919. normals.push(0, 0, -1.0);
  23920. uvs.push(0.0, 1.0);
  23921. // Indices
  23922. indices.push(0);
  23923. indices.push(1);
  23924. indices.push(2);
  23925. indices.push(0);
  23926. indices.push(2);
  23927. indices.push(3);
  23928. // Sides
  23929. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23930. // Result
  23931. var vertexData = new VertexData();
  23932. vertexData.indices = indices;
  23933. vertexData.positions = positions;
  23934. vertexData.normals = normals;
  23935. vertexData.uvs = uvs;
  23936. return vertexData;
  23937. };
  23938. VertexData.CreateDisc = function (options) {
  23939. var positions = [];
  23940. var indices = [];
  23941. var normals = [];
  23942. var uvs = [];
  23943. var radius = options.radius || 0.5;
  23944. var tessellation = options.tessellation || 64;
  23945. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23946. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23947. // positions and uvs
  23948. positions.push(0, 0, 0); // disc center first
  23949. uvs.push(0.5, 0.5);
  23950. var theta = Math.PI * 2 * arc;
  23951. var step = theta / tessellation;
  23952. for (var a = 0; a < theta; a += step) {
  23953. var x = Math.cos(a);
  23954. var y = Math.sin(a);
  23955. var u = (x + 1) / 2;
  23956. var v = (1 - y) / 2;
  23957. positions.push(radius * x, radius * y, 0);
  23958. uvs.push(u, v);
  23959. }
  23960. if (arc === 1) {
  23961. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23962. uvs.push(uvs[2], uvs[3]);
  23963. }
  23964. //indices
  23965. var vertexNb = positions.length / 3;
  23966. for (var i = 1; i < vertexNb - 1; i++) {
  23967. indices.push(i + 1, 0, i);
  23968. }
  23969. // result
  23970. VertexData.ComputeNormals(positions, indices, normals);
  23971. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23972. var vertexData = new VertexData();
  23973. vertexData.indices = indices;
  23974. vertexData.positions = positions;
  23975. vertexData.normals = normals;
  23976. vertexData.uvs = uvs;
  23977. return vertexData;
  23978. };
  23979. VertexData.CreateIcoSphere = function (options) {
  23980. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23981. var radius = options.radius || 1;
  23982. var flat = (options.flat === undefined) ? true : options.flat;
  23983. var subdivisions = options.subdivisions || 4;
  23984. var radiusX = options.radiusX || radius;
  23985. var radiusY = options.radiusY || radius;
  23986. var radiusZ = options.radiusZ || radius;
  23987. var t = (1 + Math.sqrt(5)) / 2;
  23988. // 12 vertex x,y,z
  23989. var ico_vertices = [
  23990. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23991. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23992. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23993. ];
  23994. // index of 3 vertex makes a face of icopshere
  23995. var ico_indices = [
  23996. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23997. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23998. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23999. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  24000. ];
  24001. // uv as integer step (not pixels !)
  24002. var ico_vertexuv = [
  24003. 4, 1, 2, 1, 6, 3, 5, 4,
  24004. 4, 3, 3, 2, 7, 4, 3, 0,
  24005. 1, 0, 0, 1, 5, 0, 5, 2 // v8-11
  24006. ];
  24007. // Vertices [0, 1, ...9, A, B] : position on UV plane (7,8,9,10=A have duplicate position)
  24008. // v=5h 9+ 8+ 7+
  24009. // v=4h 9+ 3 6 A+
  24010. // v=3h 9+ 4 2 A+
  24011. // v=2h 9+ 5 B A+
  24012. // v=1h 9 1 0 A+
  24013. // v=0h 8 7 A
  24014. // u=0 1 2 3 4 5 6 7 8 9 *a
  24015. //
  24016. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24017. var ustep = 97 / 1024;
  24018. var vstep = 168 / 1024;
  24019. var uoffset = 50 / 1024;
  24020. var voffset = 51 / 1024;
  24021. var indices = [];
  24022. var positions = [];
  24023. var normals = [];
  24024. var uvs = [];
  24025. var current_indice = 0;
  24026. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24027. var face_vertex_pos = new Array(3);
  24028. var face_vertex_uv = new Array(3);
  24029. for (var v012 = 0; v012 < 3; v012++) {
  24030. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24031. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24032. }
  24033. // create all with normals
  24034. for (var face = 0; face < 20; face++) {
  24035. // 3 vertex per face
  24036. for (var v012 = 0; v012 < 3; v012++) {
  24037. // look up vertex 0,1,2 to its index in 0 to 11
  24038. var v_id = ico_indices[3 * face + v012];
  24039. // vertex have 3D position (x,y,z)
  24040. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * v_id], ico_vertices[3 * v_id + 1], ico_vertices[3 * v_id + 2]);
  24041. // Normalize to get normal, then scale to radius
  24042. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24043. // uv from vertex ID (may need fix due to unwrap on texture plan, unalias needed)
  24044. // vertex may get to different UV according to belonging face (see fix below)
  24045. var fix = 0;
  24046. // Vertice 9 UV to be fixed
  24047. if (face === 5 && v012 === 2) {
  24048. fix = 1;
  24049. }
  24050. if (face === 15 && v012 === 1) {
  24051. fix = 2;
  24052. }
  24053. if (face === 10 && v012 === 1) {
  24054. fix = 3;
  24055. }
  24056. if (face === 14 && v012 === 2) {
  24057. fix = 4;
  24058. }
  24059. // vertice 10 UV to be fixed
  24060. if (face === 4 && v012 === 1) {
  24061. fix = 1;
  24062. }
  24063. if (face === 7 && v012 === 1) {
  24064. fix = 2;
  24065. }
  24066. if (face === 17 && v012 === 2) {
  24067. fix = 3;
  24068. }
  24069. if (face === 8 && v012 === 0) {
  24070. fix = 4;
  24071. }
  24072. // vertice 7 UV to be fixed
  24073. if (face === 8 && v012 === 1) {
  24074. fix = 5;
  24075. }
  24076. if (face === 18 && v012 === 0) {
  24077. fix = 5;
  24078. }
  24079. // vertice 8 UV to be fixed
  24080. if (face === 13 && v012 === 2) {
  24081. fix = 5;
  24082. }
  24083. if (face === 14 && v012 === 1) {
  24084. fix = 5;
  24085. }
  24086. if (face === 18 && v012 === 2) {
  24087. fix = 5;
  24088. }
  24089. //
  24090. face_vertex_uv[v012].copyFromFloats((ico_vertexuv[2 * v_id] + fix) * ustep + uoffset, (ico_vertexuv[2 * v_id + 1] + fix) * vstep + voffset);
  24091. }
  24092. // Subdivide the face (interpolate pos, norm, uv)
  24093. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24094. // - norm is linear interpolation of vertex corner normal
  24095. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24096. // - uv is linear interpolation
  24097. //
  24098. // Topology is as below for sub-divide by 2
  24099. // vertex shown as v0,v1,v2
  24100. // interp index is i1 to progress in range [v0,v1[
  24101. // interp index is i2 to progress in range [v0,v2[
  24102. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24103. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24104. //
  24105. //
  24106. // i2 v2
  24107. // ^ ^
  24108. // / / \
  24109. // / / \
  24110. // / / \
  24111. // / / (0,1) \
  24112. // / #---------\
  24113. // / / \ (0,0)'/ \
  24114. // / / \ / \
  24115. // / / \ / \
  24116. // / / (0,0) \ / (1,0) \
  24117. // / #---------#---------\
  24118. // v0 v1
  24119. //
  24120. // --------------------> i1
  24121. //
  24122. // interp of (i1,i2):
  24123. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24124. // along i1 : lerp(x0,x1, i1/(S-i2))
  24125. //
  24126. // centroid of triangle is needed to get help normal computation
  24127. // (c1,c2) are used for centroid location
  24128. var interp_vertex = function (i1, i2, c1, c2) {
  24129. // vertex is interpolated from
  24130. // - face_vertex_pos[0..2]
  24131. // - face_vertex_uv[0..2]
  24132. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24133. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24134. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24135. pos_interp.normalize();
  24136. pos_interp.x *= radiusX;
  24137. pos_interp.y *= radiusY;
  24138. pos_interp.z *= radiusZ;
  24139. var vertex_normal;
  24140. if (flat) {
  24141. // in flat mode, recalculate normal as face centroid normal
  24142. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24143. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24144. var centroid_interp = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24145. vertex_normal = BABYLON.Vector3.Normalize(centroid_interp);
  24146. }
  24147. else {
  24148. // in smooth mode, recalculate normal from each single vertex position
  24149. vertex_normal = BABYLON.Vector3.Normalize(pos_interp);
  24150. }
  24151. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24152. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24153. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24154. positions.push(pos_interp.x, pos_interp.y, pos_interp.z);
  24155. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24156. uvs.push(uv_interp.x, uv_interp.y);
  24157. // push each vertex has member of a face
  24158. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24159. indices.push(current_indice);
  24160. current_indice++;
  24161. };
  24162. for (var i2 = 0; i2 < subdivisions; i2++) {
  24163. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24164. // face : (i1,i2) for /\ :
  24165. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24166. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24167. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24168. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24169. if (i1 + i2 + 1 < subdivisions) {
  24170. // face : (i1,i2)' for \/ :
  24171. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24172. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24173. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24174. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24175. }
  24176. }
  24177. }
  24178. }
  24179. // Sides
  24180. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24181. // Result
  24182. var vertexData = new VertexData();
  24183. vertexData.indices = indices;
  24184. vertexData.positions = positions;
  24185. vertexData.normals = normals;
  24186. vertexData.uvs = uvs;
  24187. return vertexData;
  24188. };
  24189. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24190. VertexData.CreatePolyhedron = function (options) {
  24191. // provided polyhedron types :
  24192. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24193. // 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)
  24194. var polyhedra = [];
  24195. 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]] };
  24196. 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]] };
  24197. polyhedra[2] = {
  24198. 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]],
  24199. 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]]
  24200. };
  24201. polyhedra[3] = {
  24202. 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]],
  24203. 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]]
  24204. };
  24205. polyhedra[4] = {
  24206. 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]],
  24207. 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]]
  24208. };
  24209. 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]] };
  24210. 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]] };
  24211. 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]] };
  24212. 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]] };
  24213. 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]] };
  24214. 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]] };
  24215. 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]] };
  24216. 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]] };
  24217. 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]] };
  24218. polyhedra[14] = {
  24219. 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]],
  24220. 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]]
  24221. };
  24222. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24223. var size = options.size;
  24224. var sizeX = options.sizeX || size || 1;
  24225. var sizeY = options.sizeY || size || 1;
  24226. var sizeZ = options.sizeZ || size || 1;
  24227. var data = options.custom || polyhedra[type];
  24228. var nbfaces = data.face.length;
  24229. var faceUV = options.faceUV || new Array(nbfaces);
  24230. var faceColors = options.faceColors;
  24231. var flat = (options.flat === undefined) ? true : options.flat;
  24232. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24233. var positions = [];
  24234. var indices = [];
  24235. var normals = [];
  24236. var uvs = [];
  24237. var colors = [];
  24238. var index = 0;
  24239. var faceIdx = 0; // face cursor in the array "indexes"
  24240. var indexes = [];
  24241. var i = 0;
  24242. var f = 0;
  24243. var u, v, ang, x, y, tmp;
  24244. // default face colors and UV if undefined
  24245. if (flat) {
  24246. for (f = 0; f < nbfaces; f++) {
  24247. if (faceColors && faceColors[f] === undefined) {
  24248. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24249. }
  24250. if (faceUV && faceUV[f] === undefined) {
  24251. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24252. }
  24253. }
  24254. }
  24255. if (!flat) {
  24256. for (i = 0; i < data.vertex.length; i++) {
  24257. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24258. uvs.push(0, 0);
  24259. }
  24260. for (f = 0; f < nbfaces; f++) {
  24261. for (i = 0; i < data.face[f].length - 2; i++) {
  24262. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24263. }
  24264. }
  24265. }
  24266. else {
  24267. for (f = 0; f < nbfaces; f++) {
  24268. var fl = data.face[f].length; // number of vertices of the current face
  24269. ang = 2 * Math.PI / fl;
  24270. x = 0.5 * Math.tan(ang / 2);
  24271. y = 0.5;
  24272. // positions, uvs, colors
  24273. for (i = 0; i < fl; i++) {
  24274. // positions
  24275. 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);
  24276. indexes.push(index);
  24277. index++;
  24278. // uvs
  24279. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24280. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24281. uvs.push(u, v);
  24282. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24283. y = x * Math.sin(ang) + y * Math.cos(ang);
  24284. x = tmp;
  24285. // colors
  24286. if (faceColors) {
  24287. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24288. }
  24289. }
  24290. // indices from indexes
  24291. for (i = 0; i < fl - 2; i++) {
  24292. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24293. }
  24294. faceIdx += fl;
  24295. }
  24296. }
  24297. VertexData.ComputeNormals(positions, indices, normals);
  24298. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24299. var vertexData = new VertexData();
  24300. vertexData.positions = positions;
  24301. vertexData.indices = indices;
  24302. vertexData.normals = normals;
  24303. vertexData.uvs = uvs;
  24304. if (faceColors && flat) {
  24305. vertexData.colors = colors;
  24306. }
  24307. return vertexData;
  24308. };
  24309. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24310. VertexData.CreateTorusKnot = function (options) {
  24311. var indices = [];
  24312. var positions = [];
  24313. var normals = [];
  24314. var uvs = [];
  24315. var radius = options.radius || 2;
  24316. var tube = options.tube || 0.5;
  24317. var radialSegments = options.radialSegments || 32;
  24318. var tubularSegments = options.tubularSegments || 32;
  24319. var p = options.p || 2;
  24320. var q = options.q || 3;
  24321. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24322. // Helper
  24323. var getPos = function (angle) {
  24324. var cu = Math.cos(angle);
  24325. var su = Math.sin(angle);
  24326. var quOverP = q / p * angle;
  24327. var cs = Math.cos(quOverP);
  24328. var tx = radius * (2 + cs) * 0.5 * cu;
  24329. var ty = radius * (2 + cs) * su * 0.5;
  24330. var tz = radius * Math.sin(quOverP) * 0.5;
  24331. return new BABYLON.Vector3(tx, ty, tz);
  24332. };
  24333. // Vertices
  24334. var i;
  24335. var j;
  24336. for (i = 0; i <= radialSegments; i++) {
  24337. var modI = i % radialSegments;
  24338. var u = modI / radialSegments * 2 * p * Math.PI;
  24339. var p1 = getPos(u);
  24340. var p2 = getPos(u + 0.01);
  24341. var tang = p2.subtract(p1);
  24342. var n = p2.add(p1);
  24343. var bitan = BABYLON.Vector3.Cross(tang, n);
  24344. n = BABYLON.Vector3.Cross(bitan, tang);
  24345. bitan.normalize();
  24346. n.normalize();
  24347. for (j = 0; j < tubularSegments; j++) {
  24348. var modJ = j % tubularSegments;
  24349. var v = modJ / tubularSegments * 2 * Math.PI;
  24350. var cx = -tube * Math.cos(v);
  24351. var cy = tube * Math.sin(v);
  24352. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24353. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24354. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24355. uvs.push(i / radialSegments);
  24356. uvs.push(j / tubularSegments);
  24357. }
  24358. }
  24359. for (i = 0; i < radialSegments; i++) {
  24360. for (j = 0; j < tubularSegments; j++) {
  24361. var jNext = (j + 1) % tubularSegments;
  24362. var a = i * tubularSegments + j;
  24363. var b = (i + 1) * tubularSegments + j;
  24364. var c = (i + 1) * tubularSegments + jNext;
  24365. var d = i * tubularSegments + jNext;
  24366. indices.push(d);
  24367. indices.push(b);
  24368. indices.push(a);
  24369. indices.push(d);
  24370. indices.push(c);
  24371. indices.push(b);
  24372. }
  24373. }
  24374. // Normals
  24375. VertexData.ComputeNormals(positions, indices, normals);
  24376. // Sides
  24377. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24378. // Result
  24379. var vertexData = new VertexData();
  24380. vertexData.indices = indices;
  24381. vertexData.positions = positions;
  24382. vertexData.normals = normals;
  24383. vertexData.uvs = uvs;
  24384. return vertexData;
  24385. };
  24386. // Tools
  24387. /**
  24388. * @param {any} - positions (number[] or Float32Array)
  24389. * @param {any} - indices (number[] or Uint16Array)
  24390. * @param {any} - normals (number[] or Float32Array)
  24391. */
  24392. VertexData.ComputeNormals = function (positions, indices, normals) {
  24393. var index = 0;
  24394. // temp Vector3
  24395. var p1p2 = BABYLON.Vector3.Zero();
  24396. var p3p2 = BABYLON.Vector3.Zero();
  24397. var faceNormal = BABYLON.Vector3.Zero();
  24398. var vertexNormali1 = BABYLON.Vector3.Zero();
  24399. for (index = 0; index < positions.length; index++) {
  24400. normals[index] = 0.0;
  24401. }
  24402. // indice triplet = 1 face
  24403. var nbFaces = indices.length / 3;
  24404. for (index = 0; index < nbFaces; index++) {
  24405. var i1 = indices[index * 3];
  24406. var i2 = indices[index * 3 + 1];
  24407. var i3 = indices[index * 3 + 2];
  24408. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  24409. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24410. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24411. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  24412. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24413. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24414. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24415. faceNormal.normalize();
  24416. normals[i1 * 3] += faceNormal.x;
  24417. normals[i1 * 3 + 1] += faceNormal.y;
  24418. normals[i1 * 3 + 2] += faceNormal.z;
  24419. normals[i2 * 3] += faceNormal.x;
  24420. normals[i2 * 3 + 1] += faceNormal.y;
  24421. normals[i2 * 3 + 2] += faceNormal.z;
  24422. normals[i3 * 3] += faceNormal.x;
  24423. normals[i3 * 3 + 1] += faceNormal.y;
  24424. normals[i3 * 3 + 2] += faceNormal.z;
  24425. }
  24426. // last normalization
  24427. for (index = 0; index < normals.length / 3; index++) {
  24428. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24429. vertexNormali1.normalize();
  24430. normals[index * 3] = vertexNormali1.x;
  24431. normals[index * 3 + 1] = vertexNormali1.y;
  24432. normals[index * 3 + 2] = vertexNormali1.z;
  24433. }
  24434. };
  24435. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24436. var li = indices.length;
  24437. var ln = normals.length;
  24438. var i;
  24439. var n;
  24440. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24441. switch (sideOrientation) {
  24442. case BABYLON.Mesh.FRONTSIDE:
  24443. // nothing changed
  24444. break;
  24445. case BABYLON.Mesh.BACKSIDE:
  24446. var tmp;
  24447. // indices
  24448. for (i = 0; i < li; i += 3) {
  24449. tmp = indices[i];
  24450. indices[i] = indices[i + 2];
  24451. indices[i + 2] = tmp;
  24452. }
  24453. // normals
  24454. for (n = 0; n < ln; n++) {
  24455. normals[n] = -normals[n];
  24456. }
  24457. break;
  24458. case BABYLON.Mesh.DOUBLESIDE:
  24459. // positions
  24460. var lp = positions.length;
  24461. var l = lp / 3;
  24462. for (var p = 0; p < lp; p++) {
  24463. positions[lp + p] = positions[p];
  24464. }
  24465. // indices
  24466. for (i = 0; i < li; i += 3) {
  24467. indices[i + li] = indices[i + 2] + l;
  24468. indices[i + 1 + li] = indices[i + 1] + l;
  24469. indices[i + 2 + li] = indices[i] + l;
  24470. }
  24471. // normals
  24472. for (n = 0; n < ln; n++) {
  24473. normals[ln + n] = -normals[n];
  24474. }
  24475. // uvs
  24476. var lu = uvs.length;
  24477. for (var u = 0; u < lu; u++) {
  24478. uvs[u + lu] = uvs[u];
  24479. }
  24480. break;
  24481. }
  24482. };
  24483. return VertexData;
  24484. })();
  24485. BABYLON.VertexData = VertexData;
  24486. })(BABYLON || (BABYLON = {}));
  24487. var BABYLON;
  24488. (function (BABYLON) {
  24489. var Tags = (function () {
  24490. function Tags() {
  24491. }
  24492. Tags.EnableFor = function (obj) {
  24493. obj._tags = obj._tags || {};
  24494. obj.hasTags = function () {
  24495. return Tags.HasTags(obj);
  24496. };
  24497. obj.addTags = function (tagsString) {
  24498. return Tags.AddTagsTo(obj, tagsString);
  24499. };
  24500. obj.removeTags = function (tagsString) {
  24501. return Tags.RemoveTagsFrom(obj, tagsString);
  24502. };
  24503. obj.matchesTagsQuery = function (tagsQuery) {
  24504. return Tags.MatchesQuery(obj, tagsQuery);
  24505. };
  24506. };
  24507. Tags.DisableFor = function (obj) {
  24508. delete obj._tags;
  24509. delete obj.hasTags;
  24510. delete obj.addTags;
  24511. delete obj.removeTags;
  24512. delete obj.matchesTagsQuery;
  24513. };
  24514. Tags.HasTags = function (obj) {
  24515. if (!obj._tags) {
  24516. return false;
  24517. }
  24518. return !BABYLON.Tools.IsEmpty(obj._tags);
  24519. };
  24520. Tags.GetTags = function (obj) {
  24521. if (!obj._tags) {
  24522. return null;
  24523. }
  24524. return obj._tags;
  24525. };
  24526. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24527. // a tag cannot start with '||', '&&', and '!'
  24528. // it cannot contain whitespaces
  24529. Tags.AddTagsTo = function (obj, tagsString) {
  24530. if (!tagsString) {
  24531. return;
  24532. }
  24533. if (typeof tagsString !== "string") {
  24534. return;
  24535. }
  24536. var tags = tagsString.split(" ");
  24537. for (var t in tags) {
  24538. Tags._AddTagTo(obj, tags[t]);
  24539. }
  24540. };
  24541. Tags._AddTagTo = function (obj, tag) {
  24542. tag = tag.trim();
  24543. if (tag === "" || tag === "true" || tag === "false") {
  24544. return;
  24545. }
  24546. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24547. return;
  24548. }
  24549. Tags.EnableFor(obj);
  24550. obj._tags[tag] = true;
  24551. };
  24552. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24553. if (!Tags.HasTags(obj)) {
  24554. return;
  24555. }
  24556. var tags = tagsString.split(" ");
  24557. for (var t in tags) {
  24558. Tags._RemoveTagFrom(obj, tags[t]);
  24559. }
  24560. };
  24561. Tags._RemoveTagFrom = function (obj, tag) {
  24562. delete obj._tags[tag];
  24563. };
  24564. Tags.MatchesQuery = function (obj, tagsQuery) {
  24565. if (tagsQuery === undefined) {
  24566. return true;
  24567. }
  24568. if (tagsQuery === "") {
  24569. return Tags.HasTags(obj);
  24570. }
  24571. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24572. };
  24573. return Tags;
  24574. })();
  24575. BABYLON.Tags = Tags;
  24576. })(BABYLON || (BABYLON = {}));
  24577. var BABYLON;
  24578. (function (BABYLON) {
  24579. var Internals;
  24580. (function (Internals) {
  24581. var AndOrNotEvaluator = (function () {
  24582. function AndOrNotEvaluator() {
  24583. }
  24584. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24585. if (!query.match(/\([^\(\)]*\)/g)) {
  24586. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24587. }
  24588. else {
  24589. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24590. // remove parenthesis
  24591. r = r.slice(1, r.length - 1);
  24592. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24593. });
  24594. }
  24595. if (query === "true") {
  24596. return true;
  24597. }
  24598. if (query === "false") {
  24599. return false;
  24600. }
  24601. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24602. };
  24603. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24604. evaluateCallback = evaluateCallback || (function (r) {
  24605. return r === "true" ? true : false;
  24606. });
  24607. var result;
  24608. var or = parenthesisContent.split("||");
  24609. for (var i in or) {
  24610. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24611. var and = ori.split("&&");
  24612. if (and.length > 1) {
  24613. for (var j = 0; j < and.length; ++j) {
  24614. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24615. if (andj !== "true" && andj !== "false") {
  24616. if (andj[0] === "!") {
  24617. result = !evaluateCallback(andj.substring(1));
  24618. }
  24619. else {
  24620. result = evaluateCallback(andj);
  24621. }
  24622. }
  24623. else {
  24624. result = andj === "true" ? true : false;
  24625. }
  24626. if (!result) {
  24627. ori = "false";
  24628. break;
  24629. }
  24630. }
  24631. }
  24632. if (result || ori === "true") {
  24633. result = true;
  24634. break;
  24635. }
  24636. // result equals false (or undefined)
  24637. if (ori !== "true" && ori !== "false") {
  24638. if (ori[0] === "!") {
  24639. result = !evaluateCallback(ori.substring(1));
  24640. }
  24641. else {
  24642. result = evaluateCallback(ori);
  24643. }
  24644. }
  24645. else {
  24646. result = ori === "true" ? true : false;
  24647. }
  24648. }
  24649. // the whole parenthesis scope is replaced by 'true' or 'false'
  24650. return result ? "true" : "false";
  24651. };
  24652. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24653. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24654. // remove whitespaces
  24655. r = r.replace(/[\s]/g, function () { return ""; });
  24656. return r.length % 2 ? "!" : "";
  24657. });
  24658. booleanString = booleanString.trim();
  24659. if (booleanString === "!true") {
  24660. booleanString = "false";
  24661. }
  24662. else if (booleanString === "!false") {
  24663. booleanString = "true";
  24664. }
  24665. return booleanString;
  24666. };
  24667. return AndOrNotEvaluator;
  24668. })();
  24669. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24670. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24671. })(BABYLON || (BABYLON = {}));
  24672. var BABYLON;
  24673. (function (BABYLON) {
  24674. var PostProcessRenderPass = (function () {
  24675. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24676. this._enabled = true;
  24677. this._refCount = 0;
  24678. this._name = name;
  24679. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24680. this.setRenderList(renderList);
  24681. this._renderTexture.onBeforeRender = beforeRender;
  24682. this._renderTexture.onAfterRender = afterRender;
  24683. this._scene = scene;
  24684. this._renderList = renderList;
  24685. }
  24686. // private
  24687. PostProcessRenderPass.prototype._incRefCount = function () {
  24688. if (this._refCount === 0) {
  24689. this._scene.customRenderTargets.push(this._renderTexture);
  24690. }
  24691. return ++this._refCount;
  24692. };
  24693. PostProcessRenderPass.prototype._decRefCount = function () {
  24694. this._refCount--;
  24695. if (this._refCount <= 0) {
  24696. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24697. }
  24698. return this._refCount;
  24699. };
  24700. PostProcessRenderPass.prototype._update = function () {
  24701. this.setRenderList(this._renderList);
  24702. };
  24703. // public
  24704. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24705. this._renderTexture.renderList = renderList;
  24706. };
  24707. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24708. return this._renderTexture;
  24709. };
  24710. return PostProcessRenderPass;
  24711. })();
  24712. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24713. })(BABYLON || (BABYLON = {}));
  24714. var BABYLON;
  24715. (function (BABYLON) {
  24716. var PostProcessRenderEffect = (function () {
  24717. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24718. this._engine = engine;
  24719. this._name = name;
  24720. this._singleInstance = singleInstance || true;
  24721. this._getPostProcess = getPostProcess;
  24722. this._cameras = [];
  24723. this._indicesForCamera = [];
  24724. this._postProcesses = {};
  24725. this._renderPasses = {};
  24726. this._renderEffectAsPasses = {};
  24727. }
  24728. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24729. get: function () {
  24730. for (var index in this._postProcesses) {
  24731. if (!this._postProcesses[index].isSupported) {
  24732. return false;
  24733. }
  24734. }
  24735. return true;
  24736. },
  24737. enumerable: true,
  24738. configurable: true
  24739. });
  24740. PostProcessRenderEffect.prototype._update = function () {
  24741. for (var renderPassName in this._renderPasses) {
  24742. this._renderPasses[renderPassName]._update();
  24743. }
  24744. };
  24745. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24746. this._renderPasses[renderPass._name] = renderPass;
  24747. this._linkParameters();
  24748. };
  24749. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24750. delete this._renderPasses[renderPass._name];
  24751. this._linkParameters();
  24752. };
  24753. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24754. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24755. this._linkParameters();
  24756. };
  24757. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24758. for (var renderPassName in this._renderPasses) {
  24759. if (renderPassName === passName) {
  24760. return this._renderPasses[passName];
  24761. }
  24762. }
  24763. };
  24764. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24765. this._renderPasses = {};
  24766. this._linkParameters();
  24767. };
  24768. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24769. var cameraKey;
  24770. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24771. for (var i = 0; i < _cam.length; i++) {
  24772. var camera = _cam[i];
  24773. var cameraName = camera.name;
  24774. if (this._singleInstance) {
  24775. cameraKey = 0;
  24776. }
  24777. else {
  24778. cameraKey = cameraName;
  24779. }
  24780. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24781. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24782. if (!this._indicesForCamera[cameraName]) {
  24783. this._indicesForCamera[cameraName] = [];
  24784. }
  24785. this._indicesForCamera[cameraName].push(index);
  24786. if (this._cameras.indexOf(camera) === -1) {
  24787. this._cameras[cameraName] = camera;
  24788. }
  24789. for (var passName in this._renderPasses) {
  24790. this._renderPasses[passName]._incRefCount();
  24791. }
  24792. }
  24793. this._linkParameters();
  24794. };
  24795. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24796. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24797. for (var i = 0; i < _cam.length; i++) {
  24798. var camera = _cam[i];
  24799. var cameraName = camera.name;
  24800. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24801. var index = this._cameras.indexOf(cameraName);
  24802. this._indicesForCamera.splice(index, 1);
  24803. this._cameras.splice(index, 1);
  24804. for (var passName in this._renderPasses) {
  24805. this._renderPasses[passName]._decRefCount();
  24806. }
  24807. }
  24808. };
  24809. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24810. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24811. for (var i = 0; i < _cam.length; i++) {
  24812. var camera = _cam[i];
  24813. var cameraName = camera.name;
  24814. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24815. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24816. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24817. }
  24818. }
  24819. for (var passName in this._renderPasses) {
  24820. this._renderPasses[passName]._incRefCount();
  24821. }
  24822. }
  24823. };
  24824. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24825. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24826. for (var i = 0; i < _cam.length; i++) {
  24827. var camera = _cam[i];
  24828. var cameraName = camera.Name;
  24829. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24830. for (var passName in this._renderPasses) {
  24831. this._renderPasses[passName]._decRefCount();
  24832. }
  24833. }
  24834. };
  24835. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24836. if (this._singleInstance) {
  24837. return this._postProcesses[0];
  24838. }
  24839. else {
  24840. return this._postProcesses[camera.name];
  24841. }
  24842. };
  24843. PostProcessRenderEffect.prototype._linkParameters = function () {
  24844. var _this = this;
  24845. for (var index in this._postProcesses) {
  24846. if (this.applyParameters) {
  24847. this.applyParameters(this._postProcesses[index]);
  24848. }
  24849. this._postProcesses[index].onBeforeRender = function (effect) {
  24850. _this._linkTextures(effect);
  24851. };
  24852. }
  24853. };
  24854. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24855. for (var renderPassName in this._renderPasses) {
  24856. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24857. }
  24858. for (var renderEffectName in this._renderEffectAsPasses) {
  24859. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24860. }
  24861. };
  24862. return PostProcessRenderEffect;
  24863. })();
  24864. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24865. })(BABYLON || (BABYLON = {}));
  24866. var BABYLON;
  24867. (function (BABYLON) {
  24868. var PostProcessRenderPipeline = (function () {
  24869. function PostProcessRenderPipeline(engine, name) {
  24870. this._engine = engine;
  24871. this._name = name;
  24872. this._renderEffects = {};
  24873. this._renderEffectsForIsolatedPass = {};
  24874. this._cameras = [];
  24875. }
  24876. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24877. get: function () {
  24878. for (var renderEffectName in this._renderEffects) {
  24879. if (!this._renderEffects[renderEffectName].isSupported) {
  24880. return false;
  24881. }
  24882. }
  24883. return true;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24889. this._renderEffects[renderEffect._name] = renderEffect;
  24890. };
  24891. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24892. var renderEffects = this._renderEffects[renderEffectName];
  24893. if (!renderEffects) {
  24894. return;
  24895. }
  24896. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24897. };
  24898. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24899. var renderEffects = this._renderEffects[renderEffectName];
  24900. if (!renderEffects) {
  24901. return;
  24902. }
  24903. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24904. };
  24905. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24906. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24907. var indicesToDelete = [];
  24908. var i;
  24909. for (i = 0; i < _cam.length; i++) {
  24910. var camera = _cam[i];
  24911. var cameraName = camera.name;
  24912. if (this._cameras.indexOf(camera) === -1) {
  24913. this._cameras[cameraName] = camera;
  24914. }
  24915. else if (unique) {
  24916. indicesToDelete.push(i);
  24917. }
  24918. }
  24919. for (i = 0; i < indicesToDelete.length; i++) {
  24920. cameras.splice(indicesToDelete[i], 1);
  24921. }
  24922. for (var renderEffectName in this._renderEffects) {
  24923. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24924. }
  24925. };
  24926. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24927. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24928. for (var renderEffectName in this._renderEffects) {
  24929. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24930. }
  24931. for (var i = 0; i < _cam.length; i++) {
  24932. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24933. }
  24934. };
  24935. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24936. var _this = this;
  24937. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24938. var pass = null;
  24939. var renderEffectName;
  24940. for (renderEffectName in this._renderEffects) {
  24941. pass = this._renderEffects[renderEffectName].getPass(passName);
  24942. if (pass != null) {
  24943. break;
  24944. }
  24945. }
  24946. if (pass === null) {
  24947. return;
  24948. }
  24949. for (renderEffectName in this._renderEffects) {
  24950. this._renderEffects[renderEffectName]._disable(_cam);
  24951. }
  24952. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24953. for (var i = 0; i < _cam.length; i++) {
  24954. var camera = _cam[i];
  24955. var cameraName = camera.name;
  24956. 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); });
  24957. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24958. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24959. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24960. }
  24961. };
  24962. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24963. var _this = this;
  24964. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24965. for (var i = 0; i < _cam.length; i++) {
  24966. var camera = _cam[i];
  24967. var cameraName = camera.name;
  24968. 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); });
  24969. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24970. }
  24971. for (var renderEffectName in this._renderEffects) {
  24972. this._renderEffects[renderEffectName]._enable(_cam);
  24973. }
  24974. };
  24975. PostProcessRenderPipeline.prototype._update = function () {
  24976. for (var renderEffectName in this._renderEffects) {
  24977. this._renderEffects[renderEffectName]._update();
  24978. }
  24979. for (var i = 0; i < this._cameras.length; i++) {
  24980. var cameraName = this._cameras[i].name;
  24981. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24982. this._renderEffectsForIsolatedPass[cameraName]._update();
  24983. }
  24984. }
  24985. };
  24986. PostProcessRenderPipeline.prototype.dispose = function () {
  24987. // Must be implemented by children
  24988. };
  24989. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24990. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24991. return PostProcessRenderPipeline;
  24992. })();
  24993. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24994. })(BABYLON || (BABYLON = {}));
  24995. var BABYLON;
  24996. (function (BABYLON) {
  24997. var PostProcessRenderPipelineManager = (function () {
  24998. function PostProcessRenderPipelineManager() {
  24999. this._renderPipelines = {};
  25000. }
  25001. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25002. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25003. };
  25004. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25005. var renderPipeline = this._renderPipelines[renderPipelineName];
  25006. if (!renderPipeline) {
  25007. return;
  25008. }
  25009. renderPipeline._attachCameras(cameras, unique);
  25010. };
  25011. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25012. var renderPipeline = this._renderPipelines[renderPipelineName];
  25013. if (!renderPipeline) {
  25014. return;
  25015. }
  25016. renderPipeline._detachCameras(cameras);
  25017. };
  25018. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25019. var renderPipeline = this._renderPipelines[renderPipelineName];
  25020. if (!renderPipeline) {
  25021. return;
  25022. }
  25023. renderPipeline._enableEffect(renderEffectName, cameras);
  25024. };
  25025. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25026. var renderPipeline = this._renderPipelines[renderPipelineName];
  25027. if (!renderPipeline) {
  25028. return;
  25029. }
  25030. renderPipeline._disableEffect(renderEffectName, cameras);
  25031. };
  25032. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25033. var renderPipeline = this._renderPipelines[renderPipelineName];
  25034. if (!renderPipeline) {
  25035. return;
  25036. }
  25037. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25038. };
  25039. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25040. var renderPipeline = this._renderPipelines[renderPipelineName];
  25041. if (!renderPipeline) {
  25042. return;
  25043. }
  25044. renderPipeline._disableDisplayOnlyPass(cameras);
  25045. };
  25046. PostProcessRenderPipelineManager.prototype.update = function () {
  25047. for (var renderPipelineName in this._renderPipelines) {
  25048. var pipeline = this._renderPipelines[renderPipelineName];
  25049. if (!pipeline.isSupported) {
  25050. pipeline.dispose();
  25051. delete this._renderPipelines[renderPipelineName];
  25052. }
  25053. else {
  25054. pipeline._update();
  25055. }
  25056. }
  25057. };
  25058. return PostProcessRenderPipelineManager;
  25059. })();
  25060. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25061. })(BABYLON || (BABYLON = {}));
  25062. var BABYLON;
  25063. (function (BABYLON) {
  25064. var BoundingBoxRenderer = (function () {
  25065. function BoundingBoxRenderer(scene) {
  25066. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25067. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25068. this.showBackLines = true;
  25069. this.renderList = new BABYLON.SmartArray(32);
  25070. this._scene = scene;
  25071. }
  25072. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25073. if (this._colorShader) {
  25074. return;
  25075. }
  25076. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25077. attributes: ["position"],
  25078. uniforms: ["worldViewProjection", "color"]
  25079. });
  25080. var engine = this._scene.getEngine();
  25081. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25082. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25083. 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]);
  25084. };
  25085. BoundingBoxRenderer.prototype.reset = function () {
  25086. this.renderList.reset();
  25087. };
  25088. BoundingBoxRenderer.prototype.render = function () {
  25089. if (this.renderList.length === 0) {
  25090. return;
  25091. }
  25092. this._prepareRessources();
  25093. if (!this._colorShader.isReady()) {
  25094. return;
  25095. }
  25096. var engine = this._scene.getEngine();
  25097. engine.setDepthWrite(false);
  25098. this._colorShader._preBind();
  25099. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25100. var boundingBox = this.renderList.data[boundingBoxIndex];
  25101. var min = boundingBox.minimum;
  25102. var max = boundingBox.maximum;
  25103. var diff = max.subtract(min);
  25104. var median = min.add(diff.scale(0.5));
  25105. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25106. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25107. .multiply(boundingBox.getWorldMatrix());
  25108. // VBOs
  25109. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25110. if (this.showBackLines) {
  25111. // Back
  25112. engine.setDepthFunctionToGreaterOrEqual();
  25113. this._scene.resetCachedMaterial();
  25114. this._colorShader.setColor4("color", this.backColor.toColor4());
  25115. this._colorShader.bind(worldMatrix);
  25116. // Draw order
  25117. engine.draw(false, 0, 24);
  25118. }
  25119. // Front
  25120. engine.setDepthFunctionToLess();
  25121. this._scene.resetCachedMaterial();
  25122. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25123. this._colorShader.bind(worldMatrix);
  25124. // Draw order
  25125. engine.draw(false, 0, 24);
  25126. }
  25127. this._colorShader.unbind();
  25128. engine.setDepthFunctionToLessOrEqual();
  25129. engine.setDepthWrite(true);
  25130. };
  25131. BoundingBoxRenderer.prototype.dispose = function () {
  25132. if (!this._colorShader) {
  25133. return;
  25134. }
  25135. this._colorShader.dispose();
  25136. this._vb.dispose();
  25137. this._scene.getEngine()._releaseBuffer(this._ib);
  25138. };
  25139. return BoundingBoxRenderer;
  25140. })();
  25141. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25142. })(BABYLON || (BABYLON = {}));
  25143. var BABYLON;
  25144. (function (BABYLON) {
  25145. var Condition = (function () {
  25146. function Condition(actionManager) {
  25147. this._actionManager = actionManager;
  25148. }
  25149. Condition.prototype.isValid = function () {
  25150. return true;
  25151. };
  25152. Condition.prototype._getProperty = function (propertyPath) {
  25153. return this._actionManager._getProperty(propertyPath);
  25154. };
  25155. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25156. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25157. };
  25158. return Condition;
  25159. })();
  25160. BABYLON.Condition = Condition;
  25161. var ValueCondition = (function (_super) {
  25162. __extends(ValueCondition, _super);
  25163. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25164. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25165. _super.call(this, actionManager);
  25166. this.propertyPath = propertyPath;
  25167. this.value = value;
  25168. this.operator = operator;
  25169. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25170. this._property = this._getProperty(this.propertyPath);
  25171. }
  25172. Object.defineProperty(ValueCondition, "IsEqual", {
  25173. get: function () {
  25174. return ValueCondition._IsEqual;
  25175. },
  25176. enumerable: true,
  25177. configurable: true
  25178. });
  25179. Object.defineProperty(ValueCondition, "IsDifferent", {
  25180. get: function () {
  25181. return ValueCondition._IsDifferent;
  25182. },
  25183. enumerable: true,
  25184. configurable: true
  25185. });
  25186. Object.defineProperty(ValueCondition, "IsGreater", {
  25187. get: function () {
  25188. return ValueCondition._IsGreater;
  25189. },
  25190. enumerable: true,
  25191. configurable: true
  25192. });
  25193. Object.defineProperty(ValueCondition, "IsLesser", {
  25194. get: function () {
  25195. return ValueCondition._IsLesser;
  25196. },
  25197. enumerable: true,
  25198. configurable: true
  25199. });
  25200. // Methods
  25201. ValueCondition.prototype.isValid = function () {
  25202. switch (this.operator) {
  25203. case ValueCondition.IsGreater:
  25204. return this._target[this._property] > this.value;
  25205. case ValueCondition.IsLesser:
  25206. return this._target[this._property] < this.value;
  25207. case ValueCondition.IsEqual:
  25208. case ValueCondition.IsDifferent:
  25209. var check;
  25210. if (this.value.equals) {
  25211. check = this.value.equals(this._target[this._property]);
  25212. }
  25213. else {
  25214. check = this.value === this._target[this._property];
  25215. }
  25216. return this.operator === ValueCondition.IsEqual ? check : !check;
  25217. }
  25218. return false;
  25219. };
  25220. // Statics
  25221. ValueCondition._IsEqual = 0;
  25222. ValueCondition._IsDifferent = 1;
  25223. ValueCondition._IsGreater = 2;
  25224. ValueCondition._IsLesser = 3;
  25225. return ValueCondition;
  25226. })(Condition);
  25227. BABYLON.ValueCondition = ValueCondition;
  25228. var PredicateCondition = (function (_super) {
  25229. __extends(PredicateCondition, _super);
  25230. function PredicateCondition(actionManager, predicate) {
  25231. _super.call(this, actionManager);
  25232. this.predicate = predicate;
  25233. }
  25234. PredicateCondition.prototype.isValid = function () {
  25235. return this.predicate();
  25236. };
  25237. return PredicateCondition;
  25238. })(Condition);
  25239. BABYLON.PredicateCondition = PredicateCondition;
  25240. var StateCondition = (function (_super) {
  25241. __extends(StateCondition, _super);
  25242. function StateCondition(actionManager, target, value) {
  25243. _super.call(this, actionManager);
  25244. this.value = value;
  25245. this._target = target;
  25246. }
  25247. // Methods
  25248. StateCondition.prototype.isValid = function () {
  25249. return this._target.state === this.value;
  25250. };
  25251. return StateCondition;
  25252. })(Condition);
  25253. BABYLON.StateCondition = StateCondition;
  25254. })(BABYLON || (BABYLON = {}));
  25255. var BABYLON;
  25256. (function (BABYLON) {
  25257. var Action = (function () {
  25258. function Action(triggerOptions, condition) {
  25259. this.triggerOptions = triggerOptions;
  25260. if (triggerOptions.parameter) {
  25261. this.trigger = triggerOptions.trigger;
  25262. this._triggerParameter = triggerOptions.parameter;
  25263. }
  25264. else {
  25265. this.trigger = triggerOptions;
  25266. }
  25267. this._nextActiveAction = this;
  25268. this._condition = condition;
  25269. }
  25270. // Methods
  25271. Action.prototype._prepare = function () {
  25272. };
  25273. Action.prototype.getTriggerParameter = function () {
  25274. return this._triggerParameter;
  25275. };
  25276. Action.prototype._executeCurrent = function (evt) {
  25277. if (this._nextActiveAction._condition) {
  25278. var condition = this._nextActiveAction._condition;
  25279. var currentRenderId = this._actionManager.getScene().getRenderId();
  25280. // We cache the current evaluation for the current frame
  25281. if (condition._evaluationId === currentRenderId) {
  25282. if (!condition._currentResult) {
  25283. return;
  25284. }
  25285. }
  25286. else {
  25287. condition._evaluationId = currentRenderId;
  25288. if (!condition.isValid()) {
  25289. condition._currentResult = false;
  25290. return;
  25291. }
  25292. condition._currentResult = true;
  25293. }
  25294. }
  25295. this._nextActiveAction.execute(evt);
  25296. if (this._nextActiveAction._child) {
  25297. if (!this._nextActiveAction._child._actionManager) {
  25298. this._nextActiveAction._child._actionManager = this._actionManager;
  25299. }
  25300. this._nextActiveAction = this._nextActiveAction._child;
  25301. }
  25302. else {
  25303. this._nextActiveAction = this;
  25304. }
  25305. };
  25306. Action.prototype.execute = function (evt) {
  25307. };
  25308. Action.prototype.then = function (action) {
  25309. this._child = action;
  25310. action._actionManager = this._actionManager;
  25311. action._prepare();
  25312. return action;
  25313. };
  25314. Action.prototype._getProperty = function (propertyPath) {
  25315. return this._actionManager._getProperty(propertyPath);
  25316. };
  25317. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25318. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25319. };
  25320. return Action;
  25321. })();
  25322. BABYLON.Action = Action;
  25323. })(BABYLON || (BABYLON = {}));
  25324. var BABYLON;
  25325. (function (BABYLON) {
  25326. /**
  25327. * ActionEvent is the event beint sent when an action is triggered.
  25328. */
  25329. var ActionEvent = (function () {
  25330. /**
  25331. * @constructor
  25332. * @param source The mesh or sprite that triggered the action.
  25333. * @param pointerX The X mouse cursor position at the time of the event
  25334. * @param pointerY The Y mouse cursor position at the time of the event
  25335. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25336. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25337. */
  25338. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25339. this.source = source;
  25340. this.pointerX = pointerX;
  25341. this.pointerY = pointerY;
  25342. this.meshUnderPointer = meshUnderPointer;
  25343. this.sourceEvent = sourceEvent;
  25344. this.additionalData = additionalData;
  25345. }
  25346. /**
  25347. * Helper function to auto-create an ActionEvent from a source mesh.
  25348. * @param source The source mesh that triggered the event
  25349. * @param evt {Event} The original (browser) event
  25350. */
  25351. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25352. var scene = source.getScene();
  25353. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25354. };
  25355. /**
  25356. * Helper function to auto-create an ActionEvent from a source mesh.
  25357. * @param source The source sprite that triggered the event
  25358. * @param scene Scene associated with the sprite
  25359. * @param evt {Event} The original (browser) event
  25360. */
  25361. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25362. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25363. };
  25364. /**
  25365. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25366. * @param scene the scene where the event occurred
  25367. * @param evt {Event} The original (browser) event
  25368. */
  25369. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25370. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25371. };
  25372. return ActionEvent;
  25373. })();
  25374. BABYLON.ActionEvent = ActionEvent;
  25375. /**
  25376. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25377. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25378. */
  25379. var ActionManager = (function () {
  25380. function ActionManager(scene) {
  25381. // Members
  25382. this.actions = new Array();
  25383. this._scene = scene;
  25384. scene._actionManagers.push(this);
  25385. }
  25386. Object.defineProperty(ActionManager, "NothingTrigger", {
  25387. get: function () {
  25388. return ActionManager._NothingTrigger;
  25389. },
  25390. enumerable: true,
  25391. configurable: true
  25392. });
  25393. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25394. get: function () {
  25395. return ActionManager._OnPickTrigger;
  25396. },
  25397. enumerable: true,
  25398. configurable: true
  25399. });
  25400. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25401. get: function () {
  25402. return ActionManager._OnLeftPickTrigger;
  25403. },
  25404. enumerable: true,
  25405. configurable: true
  25406. });
  25407. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25408. get: function () {
  25409. return ActionManager._OnRightPickTrigger;
  25410. },
  25411. enumerable: true,
  25412. configurable: true
  25413. });
  25414. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25415. get: function () {
  25416. return ActionManager._OnCenterPickTrigger;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25422. get: function () {
  25423. return ActionManager._OnPointerOverTrigger;
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25429. get: function () {
  25430. return ActionManager._OnPointerOutTrigger;
  25431. },
  25432. enumerable: true,
  25433. configurable: true
  25434. });
  25435. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25436. get: function () {
  25437. return ActionManager._OnEveryFrameTrigger;
  25438. },
  25439. enumerable: true,
  25440. configurable: true
  25441. });
  25442. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25443. get: function () {
  25444. return ActionManager._OnIntersectionEnterTrigger;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25450. get: function () {
  25451. return ActionManager._OnIntersectionExitTrigger;
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25457. get: function () {
  25458. return ActionManager._OnKeyDownTrigger;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25464. get: function () {
  25465. return ActionManager._OnKeyUpTrigger;
  25466. },
  25467. enumerable: true,
  25468. configurable: true
  25469. });
  25470. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25471. get: function () {
  25472. return ActionManager._OnPickUpTrigger;
  25473. },
  25474. enumerable: true,
  25475. configurable: true
  25476. });
  25477. // Methods
  25478. ActionManager.prototype.dispose = function () {
  25479. var index = this._scene._actionManagers.indexOf(this);
  25480. if (index > -1) {
  25481. this._scene._actionManagers.splice(index, 1);
  25482. }
  25483. };
  25484. ActionManager.prototype.getScene = function () {
  25485. return this._scene;
  25486. };
  25487. /**
  25488. * Does this action manager handles actions of any of the given triggers
  25489. * @param {number[]} triggers - the triggers to be tested
  25490. * @return {boolean} whether one (or more) of the triggers is handeled
  25491. */
  25492. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25493. for (var index = 0; index < this.actions.length; index++) {
  25494. var action = this.actions[index];
  25495. if (triggers.indexOf(action.trigger) > -1) {
  25496. return true;
  25497. }
  25498. }
  25499. return false;
  25500. };
  25501. /**
  25502. * Does this action manager handles actions of a given trigger
  25503. * @param {number} trigger - the trigger to be tested
  25504. * @return {boolean} whether the trigger is handeled
  25505. */
  25506. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25507. for (var index = 0; index < this.actions.length; index++) {
  25508. var action = this.actions[index];
  25509. if (action.trigger === trigger) {
  25510. return true;
  25511. }
  25512. }
  25513. return false;
  25514. };
  25515. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25516. /**
  25517. * Does this action manager has pointer triggers
  25518. * @return {boolean} whether or not it has pointer triggers
  25519. */
  25520. get: function () {
  25521. for (var index = 0; index < this.actions.length; index++) {
  25522. var action = this.actions[index];
  25523. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25524. return true;
  25525. }
  25526. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25527. return true;
  25528. }
  25529. }
  25530. return false;
  25531. },
  25532. enumerable: true,
  25533. configurable: true
  25534. });
  25535. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25536. /**
  25537. * Does this action manager has pick triggers
  25538. * @return {boolean} whether or not it has pick triggers
  25539. */
  25540. get: function () {
  25541. for (var index = 0; index < this.actions.length; index++) {
  25542. var action = this.actions[index];
  25543. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25544. return true;
  25545. }
  25546. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25547. return true;
  25548. }
  25549. }
  25550. return false;
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. /**
  25556. * Registers an action to this action manager
  25557. * @param {BABYLON.Action} action - the action to be registered
  25558. * @return {BABYLON.Action} the action amended (prepared) after registration
  25559. */
  25560. ActionManager.prototype.registerAction = function (action) {
  25561. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25562. if (this.getScene().actionManager !== this) {
  25563. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25564. return null;
  25565. }
  25566. }
  25567. this.actions.push(action);
  25568. action._actionManager = this;
  25569. action._prepare();
  25570. return action;
  25571. };
  25572. /**
  25573. * Process a specific trigger
  25574. * @param {number} trigger - the trigger to process
  25575. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25576. */
  25577. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25578. for (var index = 0; index < this.actions.length; index++) {
  25579. var action = this.actions[index];
  25580. if (action.trigger === trigger) {
  25581. if (trigger === ActionManager.OnKeyUpTrigger
  25582. || trigger === ActionManager.OnKeyDownTrigger) {
  25583. var parameter = action.getTriggerParameter();
  25584. if (parameter) {
  25585. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25586. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25587. if (actualkey !== parameter.toLowerCase()) {
  25588. continue;
  25589. }
  25590. }
  25591. }
  25592. action._executeCurrent(evt);
  25593. }
  25594. }
  25595. };
  25596. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25597. var properties = propertyPath.split(".");
  25598. for (var index = 0; index < properties.length - 1; index++) {
  25599. target = target[properties[index]];
  25600. }
  25601. return target;
  25602. };
  25603. ActionManager.prototype._getProperty = function (propertyPath) {
  25604. var properties = propertyPath.split(".");
  25605. return properties[properties.length - 1];
  25606. };
  25607. // Statics
  25608. ActionManager._NothingTrigger = 0;
  25609. ActionManager._OnPickTrigger = 1;
  25610. ActionManager._OnLeftPickTrigger = 2;
  25611. ActionManager._OnRightPickTrigger = 3;
  25612. ActionManager._OnCenterPickTrigger = 4;
  25613. ActionManager._OnPointerOverTrigger = 5;
  25614. ActionManager._OnPointerOutTrigger = 6;
  25615. ActionManager._OnEveryFrameTrigger = 7;
  25616. ActionManager._OnIntersectionEnterTrigger = 8;
  25617. ActionManager._OnIntersectionExitTrigger = 9;
  25618. ActionManager._OnKeyDownTrigger = 10;
  25619. ActionManager._OnKeyUpTrigger = 11;
  25620. ActionManager._OnPickUpTrigger = 12;
  25621. return ActionManager;
  25622. })();
  25623. BABYLON.ActionManager = ActionManager;
  25624. })(BABYLON || (BABYLON = {}));
  25625. var BABYLON;
  25626. (function (BABYLON) {
  25627. var InterpolateValueAction = (function (_super) {
  25628. __extends(InterpolateValueAction, _super);
  25629. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25630. if (duration === void 0) { duration = 1000; }
  25631. _super.call(this, triggerOptions, condition);
  25632. this.propertyPath = propertyPath;
  25633. this.value = value;
  25634. this.duration = duration;
  25635. this.stopOtherAnimations = stopOtherAnimations;
  25636. this.onInterpolationDone = onInterpolationDone;
  25637. this._target = target;
  25638. }
  25639. InterpolateValueAction.prototype._prepare = function () {
  25640. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25641. this._property = this._getProperty(this.propertyPath);
  25642. };
  25643. InterpolateValueAction.prototype.execute = function () {
  25644. var scene = this._actionManager.getScene();
  25645. var keys = [
  25646. {
  25647. frame: 0,
  25648. value: this._target[this._property]
  25649. }, {
  25650. frame: 100,
  25651. value: this.value
  25652. }
  25653. ];
  25654. var dataType;
  25655. if (typeof this.value === "number") {
  25656. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25657. }
  25658. else if (this.value instanceof BABYLON.Color3) {
  25659. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25660. }
  25661. else if (this.value instanceof BABYLON.Vector3) {
  25662. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25663. }
  25664. else if (this.value instanceof BABYLON.Matrix) {
  25665. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25666. }
  25667. else if (this.value instanceof BABYLON.Quaternion) {
  25668. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25669. }
  25670. else {
  25671. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25672. return;
  25673. }
  25674. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25675. animation.setKeys(keys);
  25676. if (this.stopOtherAnimations) {
  25677. scene.stopAnimation(this._target);
  25678. }
  25679. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25680. };
  25681. return InterpolateValueAction;
  25682. })(BABYLON.Action);
  25683. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25684. })(BABYLON || (BABYLON = {}));
  25685. var BABYLON;
  25686. (function (BABYLON) {
  25687. var SwitchBooleanAction = (function (_super) {
  25688. __extends(SwitchBooleanAction, _super);
  25689. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25690. _super.call(this, triggerOptions, condition);
  25691. this.propertyPath = propertyPath;
  25692. this._target = target;
  25693. }
  25694. SwitchBooleanAction.prototype._prepare = function () {
  25695. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25696. this._property = this._getProperty(this.propertyPath);
  25697. };
  25698. SwitchBooleanAction.prototype.execute = function () {
  25699. this._target[this._property] = !this._target[this._property];
  25700. };
  25701. return SwitchBooleanAction;
  25702. })(BABYLON.Action);
  25703. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25704. var SetStateAction = (function (_super) {
  25705. __extends(SetStateAction, _super);
  25706. function SetStateAction(triggerOptions, target, value, condition) {
  25707. _super.call(this, triggerOptions, condition);
  25708. this.value = value;
  25709. this._target = target;
  25710. }
  25711. SetStateAction.prototype.execute = function () {
  25712. this._target.state = this.value;
  25713. };
  25714. return SetStateAction;
  25715. })(BABYLON.Action);
  25716. BABYLON.SetStateAction = SetStateAction;
  25717. var SetValueAction = (function (_super) {
  25718. __extends(SetValueAction, _super);
  25719. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25720. _super.call(this, triggerOptions, condition);
  25721. this.propertyPath = propertyPath;
  25722. this.value = value;
  25723. this._target = target;
  25724. }
  25725. SetValueAction.prototype._prepare = function () {
  25726. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25727. this._property = this._getProperty(this.propertyPath);
  25728. };
  25729. SetValueAction.prototype.execute = function () {
  25730. this._target[this._property] = this.value;
  25731. };
  25732. return SetValueAction;
  25733. })(BABYLON.Action);
  25734. BABYLON.SetValueAction = SetValueAction;
  25735. var IncrementValueAction = (function (_super) {
  25736. __extends(IncrementValueAction, _super);
  25737. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25738. _super.call(this, triggerOptions, condition);
  25739. this.propertyPath = propertyPath;
  25740. this.value = value;
  25741. this._target = target;
  25742. }
  25743. IncrementValueAction.prototype._prepare = function () {
  25744. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25745. this._property = this._getProperty(this.propertyPath);
  25746. if (typeof this._target[this._property] !== "number") {
  25747. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25748. }
  25749. };
  25750. IncrementValueAction.prototype.execute = function () {
  25751. this._target[this._property] += this.value;
  25752. };
  25753. return IncrementValueAction;
  25754. })(BABYLON.Action);
  25755. BABYLON.IncrementValueAction = IncrementValueAction;
  25756. var PlayAnimationAction = (function (_super) {
  25757. __extends(PlayAnimationAction, _super);
  25758. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25759. _super.call(this, triggerOptions, condition);
  25760. this.from = from;
  25761. this.to = to;
  25762. this.loop = loop;
  25763. this._target = target;
  25764. }
  25765. PlayAnimationAction.prototype._prepare = function () {
  25766. };
  25767. PlayAnimationAction.prototype.execute = function () {
  25768. var scene = this._actionManager.getScene();
  25769. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25770. };
  25771. return PlayAnimationAction;
  25772. })(BABYLON.Action);
  25773. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25774. var StopAnimationAction = (function (_super) {
  25775. __extends(StopAnimationAction, _super);
  25776. function StopAnimationAction(triggerOptions, target, condition) {
  25777. _super.call(this, triggerOptions, condition);
  25778. this._target = target;
  25779. }
  25780. StopAnimationAction.prototype._prepare = function () {
  25781. };
  25782. StopAnimationAction.prototype.execute = function () {
  25783. var scene = this._actionManager.getScene();
  25784. scene.stopAnimation(this._target);
  25785. };
  25786. return StopAnimationAction;
  25787. })(BABYLON.Action);
  25788. BABYLON.StopAnimationAction = StopAnimationAction;
  25789. var DoNothingAction = (function (_super) {
  25790. __extends(DoNothingAction, _super);
  25791. function DoNothingAction(triggerOptions, condition) {
  25792. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25793. _super.call(this, triggerOptions, condition);
  25794. }
  25795. DoNothingAction.prototype.execute = function () {
  25796. };
  25797. return DoNothingAction;
  25798. })(BABYLON.Action);
  25799. BABYLON.DoNothingAction = DoNothingAction;
  25800. var CombineAction = (function (_super) {
  25801. __extends(CombineAction, _super);
  25802. function CombineAction(triggerOptions, children, condition) {
  25803. _super.call(this, triggerOptions, condition);
  25804. this.children = children;
  25805. }
  25806. CombineAction.prototype._prepare = function () {
  25807. for (var index = 0; index < this.children.length; index++) {
  25808. this.children[index]._actionManager = this._actionManager;
  25809. this.children[index]._prepare();
  25810. }
  25811. };
  25812. CombineAction.prototype.execute = function (evt) {
  25813. for (var index = 0; index < this.children.length; index++) {
  25814. this.children[index].execute(evt);
  25815. }
  25816. };
  25817. return CombineAction;
  25818. })(BABYLON.Action);
  25819. BABYLON.CombineAction = CombineAction;
  25820. var ExecuteCodeAction = (function (_super) {
  25821. __extends(ExecuteCodeAction, _super);
  25822. function ExecuteCodeAction(triggerOptions, func, condition) {
  25823. _super.call(this, triggerOptions, condition);
  25824. this.func = func;
  25825. }
  25826. ExecuteCodeAction.prototype.execute = function (evt) {
  25827. this.func(evt);
  25828. };
  25829. return ExecuteCodeAction;
  25830. })(BABYLON.Action);
  25831. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25832. var SetParentAction = (function (_super) {
  25833. __extends(SetParentAction, _super);
  25834. function SetParentAction(triggerOptions, target, parent, condition) {
  25835. _super.call(this, triggerOptions, condition);
  25836. this._target = target;
  25837. this._parent = parent;
  25838. }
  25839. SetParentAction.prototype._prepare = function () {
  25840. };
  25841. SetParentAction.prototype.execute = function () {
  25842. if (this._target.parent === this._parent) {
  25843. return;
  25844. }
  25845. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25846. invertParentWorldMatrix.invert();
  25847. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25848. this._target.parent = this._parent;
  25849. };
  25850. return SetParentAction;
  25851. })(BABYLON.Action);
  25852. BABYLON.SetParentAction = SetParentAction;
  25853. var PlaySoundAction = (function (_super) {
  25854. __extends(PlaySoundAction, _super);
  25855. function PlaySoundAction(triggerOptions, sound, condition) {
  25856. _super.call(this, triggerOptions, condition);
  25857. this._sound = sound;
  25858. }
  25859. PlaySoundAction.prototype._prepare = function () {
  25860. };
  25861. PlaySoundAction.prototype.execute = function () {
  25862. if (this._sound !== undefined)
  25863. this._sound.play();
  25864. };
  25865. return PlaySoundAction;
  25866. })(BABYLON.Action);
  25867. BABYLON.PlaySoundAction = PlaySoundAction;
  25868. var StopSoundAction = (function (_super) {
  25869. __extends(StopSoundAction, _super);
  25870. function StopSoundAction(triggerOptions, sound, condition) {
  25871. _super.call(this, triggerOptions, condition);
  25872. this._sound = sound;
  25873. }
  25874. StopSoundAction.prototype._prepare = function () {
  25875. };
  25876. StopSoundAction.prototype.execute = function () {
  25877. if (this._sound !== undefined)
  25878. this._sound.stop();
  25879. };
  25880. return StopSoundAction;
  25881. })(BABYLON.Action);
  25882. BABYLON.StopSoundAction = StopSoundAction;
  25883. })(BABYLON || (BABYLON = {}));
  25884. var BABYLON;
  25885. (function (BABYLON) {
  25886. var Geometry = (function () {
  25887. function Geometry(id, scene, vertexData, updatable, mesh) {
  25888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25889. this._totalVertices = 0;
  25890. this._isDisposed = false;
  25891. this.id = id;
  25892. this._engine = scene.getEngine();
  25893. this._meshes = [];
  25894. this._scene = scene;
  25895. //Init vertex buffer cache
  25896. this._vertexBuffers = {};
  25897. this._indices = [];
  25898. // vertexData
  25899. if (vertexData) {
  25900. this.setAllVerticesData(vertexData, updatable);
  25901. }
  25902. else {
  25903. this._totalVertices = 0;
  25904. this._indices = [];
  25905. }
  25906. // applyToMesh
  25907. if (mesh) {
  25908. this.applyToMesh(mesh);
  25909. mesh.computeWorldMatrix(true);
  25910. }
  25911. }
  25912. Object.defineProperty(Geometry.prototype, "extend", {
  25913. get: function () {
  25914. return this._extend;
  25915. },
  25916. enumerable: true,
  25917. configurable: true
  25918. });
  25919. Geometry.prototype.getScene = function () {
  25920. return this._scene;
  25921. };
  25922. Geometry.prototype.getEngine = function () {
  25923. return this._engine;
  25924. };
  25925. Geometry.prototype.isReady = function () {
  25926. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25927. };
  25928. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25929. vertexData.applyToGeometry(this, updatable);
  25930. this.notifyUpdate();
  25931. };
  25932. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25933. if (this._vertexBuffers[kind]) {
  25934. this._vertexBuffers[kind].dispose();
  25935. }
  25936. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25937. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25938. stride = this._vertexBuffers[kind].getStrideSize();
  25939. this._totalVertices = data.length / stride;
  25940. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25941. var meshes = this._meshes;
  25942. var numOfMeshes = meshes.length;
  25943. for (var index = 0; index < numOfMeshes; index++) {
  25944. var mesh = meshes[index];
  25945. mesh._resetPointsArrayCache();
  25946. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25947. mesh._createGlobalSubMesh();
  25948. mesh.computeWorldMatrix(true);
  25949. }
  25950. }
  25951. this.notifyUpdate(kind);
  25952. };
  25953. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25954. var vertexBuffer = this.getVertexBuffer(kind);
  25955. if (!vertexBuffer) {
  25956. return;
  25957. }
  25958. vertexBuffer.updateDirectly(data, offset);
  25959. this.notifyUpdate(kind);
  25960. };
  25961. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25962. var vertexBuffer = this.getVertexBuffer(kind);
  25963. if (!vertexBuffer) {
  25964. return;
  25965. }
  25966. vertexBuffer.update(data);
  25967. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25968. var stride = vertexBuffer.getStrideSize();
  25969. this._totalVertices = data.length / stride;
  25970. if (updateExtends) {
  25971. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25972. }
  25973. var meshes = this._meshes;
  25974. var numOfMeshes = meshes.length;
  25975. for (var index = 0; index < numOfMeshes; index++) {
  25976. var mesh = meshes[index];
  25977. mesh._resetPointsArrayCache();
  25978. if (updateExtends) {
  25979. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25980. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25981. var subMesh = mesh.subMeshes[subIndex];
  25982. subMesh.refreshBoundingInfo();
  25983. }
  25984. }
  25985. }
  25986. }
  25987. this.notifyUpdate(kind);
  25988. };
  25989. Geometry.prototype.getTotalVertices = function () {
  25990. if (!this.isReady()) {
  25991. return 0;
  25992. }
  25993. return this._totalVertices;
  25994. };
  25995. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25996. var vertexBuffer = this.getVertexBuffer(kind);
  25997. if (!vertexBuffer) {
  25998. return null;
  25999. }
  26000. var orig = vertexBuffer.getData();
  26001. if (!copyWhenShared || this._meshes.length === 1) {
  26002. return orig;
  26003. }
  26004. else {
  26005. var len = orig.length;
  26006. var copy = [];
  26007. for (var i = 0; i < len; i++) {
  26008. copy.push(orig[i]);
  26009. }
  26010. return copy;
  26011. }
  26012. };
  26013. Geometry.prototype.getVertexBuffer = function (kind) {
  26014. if (!this.isReady()) {
  26015. return null;
  26016. }
  26017. return this._vertexBuffers[kind];
  26018. };
  26019. Geometry.prototype.getVertexBuffers = function () {
  26020. if (!this.isReady()) {
  26021. return null;
  26022. }
  26023. return this._vertexBuffers;
  26024. };
  26025. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26026. if (!this._vertexBuffers) {
  26027. if (this._delayInfo) {
  26028. return this._delayInfo.indexOf(kind) !== -1;
  26029. }
  26030. return false;
  26031. }
  26032. return this._vertexBuffers[kind] !== undefined;
  26033. };
  26034. Geometry.prototype.getVerticesDataKinds = function () {
  26035. var result = [];
  26036. var kind;
  26037. if (!this._vertexBuffers && this._delayInfo) {
  26038. for (kind in this._delayInfo) {
  26039. result.push(kind);
  26040. }
  26041. }
  26042. else {
  26043. for (kind in this._vertexBuffers) {
  26044. result.push(kind);
  26045. }
  26046. }
  26047. return result;
  26048. };
  26049. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26050. if (this._indexBuffer) {
  26051. this._engine._releaseBuffer(this._indexBuffer);
  26052. }
  26053. this._indices = indices;
  26054. if (this._meshes.length !== 0 && this._indices) {
  26055. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26056. }
  26057. if (totalVertices !== undefined) {
  26058. this._totalVertices = totalVertices;
  26059. }
  26060. var meshes = this._meshes;
  26061. var numOfMeshes = meshes.length;
  26062. for (var index = 0; index < numOfMeshes; index++) {
  26063. meshes[index]._createGlobalSubMesh();
  26064. }
  26065. this.notifyUpdate();
  26066. };
  26067. Geometry.prototype.getTotalIndices = function () {
  26068. if (!this.isReady()) {
  26069. return 0;
  26070. }
  26071. return this._indices.length;
  26072. };
  26073. Geometry.prototype.getIndices = function (copyWhenShared) {
  26074. if (!this.isReady()) {
  26075. return null;
  26076. }
  26077. var orig = this._indices;
  26078. if (!copyWhenShared || this._meshes.length === 1) {
  26079. return orig;
  26080. }
  26081. else {
  26082. var len = orig.length;
  26083. var copy = [];
  26084. for (var i = 0; i < len; i++) {
  26085. copy.push(orig[i]);
  26086. }
  26087. return copy;
  26088. }
  26089. };
  26090. Geometry.prototype.getIndexBuffer = function () {
  26091. if (!this.isReady()) {
  26092. return null;
  26093. }
  26094. return this._indexBuffer;
  26095. };
  26096. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26097. var meshes = this._meshes;
  26098. var index = meshes.indexOf(mesh);
  26099. if (index === -1) {
  26100. return;
  26101. }
  26102. for (var kind in this._vertexBuffers) {
  26103. this._vertexBuffers[kind].dispose();
  26104. }
  26105. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26106. this._indexBuffer = null;
  26107. }
  26108. meshes.splice(index, 1);
  26109. mesh._geometry = null;
  26110. if (meshes.length === 0 && shouldDispose) {
  26111. this.dispose();
  26112. }
  26113. };
  26114. Geometry.prototype.applyToMesh = function (mesh) {
  26115. if (mesh._geometry === this) {
  26116. return;
  26117. }
  26118. var previousGeometry = mesh._geometry;
  26119. if (previousGeometry) {
  26120. previousGeometry.releaseForMesh(mesh);
  26121. }
  26122. var meshes = this._meshes;
  26123. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26124. mesh._geometry = this;
  26125. this._scene.pushGeometry(this);
  26126. meshes.push(mesh);
  26127. if (this.isReady()) {
  26128. this._applyToMesh(mesh);
  26129. }
  26130. else {
  26131. mesh._boundingInfo = this._boundingInfo;
  26132. }
  26133. };
  26134. Geometry.prototype._applyToMesh = function (mesh) {
  26135. var numOfMeshes = this._meshes.length;
  26136. // vertexBuffers
  26137. for (var kind in this._vertexBuffers) {
  26138. if (numOfMeshes === 1) {
  26139. this._vertexBuffers[kind].create();
  26140. }
  26141. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26142. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26143. mesh._resetPointsArrayCache();
  26144. if (!this._extend) {
  26145. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26146. }
  26147. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26148. mesh._createGlobalSubMesh();
  26149. //bounding info was just created again, world matrix should be applied again.
  26150. mesh._updateBoundingInfo();
  26151. }
  26152. }
  26153. // indexBuffer
  26154. if (numOfMeshes === 1 && this._indices) {
  26155. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26156. }
  26157. if (this._indexBuffer) {
  26158. this._indexBuffer.references = numOfMeshes;
  26159. }
  26160. };
  26161. Geometry.prototype.notifyUpdate = function (kind) {
  26162. if (this.onGeometryUpdated) {
  26163. this.onGeometryUpdated(this, kind);
  26164. }
  26165. };
  26166. Geometry.prototype.load = function (scene, onLoaded) {
  26167. var _this = this;
  26168. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26169. return;
  26170. }
  26171. if (this.isReady()) {
  26172. if (onLoaded) {
  26173. onLoaded();
  26174. }
  26175. return;
  26176. }
  26177. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26178. scene._addPendingData(this);
  26179. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26180. _this._delayLoadingFunction(JSON.parse(data), _this);
  26181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26182. _this._delayInfo = [];
  26183. scene._removePendingData(_this);
  26184. var meshes = _this._meshes;
  26185. var numOfMeshes = meshes.length;
  26186. for (var index = 0; index < numOfMeshes; index++) {
  26187. _this._applyToMesh(meshes[index]);
  26188. }
  26189. if (onLoaded) {
  26190. onLoaded();
  26191. }
  26192. }, function () { }, scene.database);
  26193. };
  26194. Geometry.prototype.isDisposed = function () {
  26195. return this._isDisposed;
  26196. };
  26197. Geometry.prototype.dispose = function () {
  26198. var meshes = this._meshes;
  26199. var numOfMeshes = meshes.length;
  26200. var index;
  26201. for (index = 0; index < numOfMeshes; index++) {
  26202. this.releaseForMesh(meshes[index]);
  26203. }
  26204. this._meshes = [];
  26205. for (var kind in this._vertexBuffers) {
  26206. this._vertexBuffers[kind].dispose();
  26207. }
  26208. this._vertexBuffers = [];
  26209. this._totalVertices = 0;
  26210. if (this._indexBuffer) {
  26211. this._engine._releaseBuffer(this._indexBuffer);
  26212. }
  26213. this._indexBuffer = null;
  26214. this._indices = [];
  26215. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26216. this.delayLoadingFile = null;
  26217. this._delayLoadingFunction = null;
  26218. this._delayInfo = [];
  26219. this._boundingInfo = null;
  26220. this._scene.removeGeometry(this);
  26221. this._isDisposed = true;
  26222. };
  26223. Geometry.prototype.copy = function (id) {
  26224. var vertexData = new BABYLON.VertexData();
  26225. vertexData.indices = [];
  26226. var indices = this.getIndices();
  26227. for (var index = 0; index < indices.length; index++) {
  26228. vertexData.indices.push(indices[index]);
  26229. }
  26230. var updatable = false;
  26231. var stopChecking = false;
  26232. var kind;
  26233. for (kind in this._vertexBuffers) {
  26234. // using slice() to make a copy of the array and not just reference it
  26235. var data = this.getVerticesData(kind);
  26236. if (data instanceof Float32Array) {
  26237. vertexData.set(new Float32Array(data), kind);
  26238. }
  26239. else {
  26240. vertexData.set(data.slice(0), kind);
  26241. }
  26242. if (!stopChecking) {
  26243. updatable = this.getVertexBuffer(kind).isUpdatable();
  26244. stopChecking = !updatable;
  26245. }
  26246. }
  26247. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26248. geometry.delayLoadState = this.delayLoadState;
  26249. geometry.delayLoadingFile = this.delayLoadingFile;
  26250. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26251. for (kind in this._delayInfo) {
  26252. geometry._delayInfo = geometry._delayInfo || [];
  26253. geometry._delayInfo.push(kind);
  26254. }
  26255. // Bounding info
  26256. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26257. return geometry;
  26258. };
  26259. // Statics
  26260. Geometry.ExtractFromMesh = function (mesh, id) {
  26261. var geometry = mesh._geometry;
  26262. if (!geometry) {
  26263. return null;
  26264. }
  26265. return geometry.copy(id);
  26266. };
  26267. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26268. // be aware Math.random() could cause collisions
  26269. Geometry.RandomId = function () {
  26270. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26271. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26272. return v.toString(16);
  26273. });
  26274. };
  26275. return Geometry;
  26276. })();
  26277. BABYLON.Geometry = Geometry;
  26278. /////// Primitives //////////////////////////////////////////////
  26279. var Geometry;
  26280. (function (Geometry) {
  26281. var Primitives;
  26282. (function (Primitives) {
  26283. /// Abstract class
  26284. var _Primitive = (function (_super) {
  26285. __extends(_Primitive, _super);
  26286. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26287. this._beingRegenerated = true;
  26288. this._canBeRegenerated = canBeRegenerated;
  26289. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26290. this._beingRegenerated = false;
  26291. }
  26292. _Primitive.prototype.canBeRegenerated = function () {
  26293. return this._canBeRegenerated;
  26294. };
  26295. _Primitive.prototype.regenerate = function () {
  26296. if (!this._canBeRegenerated) {
  26297. return;
  26298. }
  26299. this._beingRegenerated = true;
  26300. this.setAllVerticesData(this._regenerateVertexData(), false);
  26301. this._beingRegenerated = false;
  26302. };
  26303. _Primitive.prototype.asNewGeometry = function (id) {
  26304. return _super.prototype.copy.call(this, id);
  26305. };
  26306. // overrides
  26307. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26308. if (!this._beingRegenerated) {
  26309. return;
  26310. }
  26311. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26312. };
  26313. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26314. if (!this._beingRegenerated) {
  26315. return;
  26316. }
  26317. _super.prototype.setVerticesData.call(this, kind, data, false);
  26318. };
  26319. // to override
  26320. // protected
  26321. _Primitive.prototype._regenerateVertexData = function () {
  26322. throw new Error("Abstract method");
  26323. };
  26324. _Primitive.prototype.copy = function (id) {
  26325. throw new Error("Must be overriden in sub-classes.");
  26326. };
  26327. return _Primitive;
  26328. })(Geometry);
  26329. Primitives._Primitive = _Primitive;
  26330. var Ribbon = (function (_super) {
  26331. __extends(Ribbon, _super);
  26332. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26333. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26334. this.pathArray = pathArray;
  26335. this.closeArray = closeArray;
  26336. this.closePath = closePath;
  26337. this.offset = offset;
  26338. this.side = side;
  26339. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26340. }
  26341. Ribbon.prototype._regenerateVertexData = function () {
  26342. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26343. };
  26344. Ribbon.prototype.copy = function (id) {
  26345. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26346. };
  26347. return Ribbon;
  26348. })(_Primitive);
  26349. Primitives.Ribbon = Ribbon;
  26350. var Box = (function (_super) {
  26351. __extends(Box, _super);
  26352. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26353. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26354. this.size = size;
  26355. this.side = side;
  26356. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26357. }
  26358. Box.prototype._regenerateVertexData = function () {
  26359. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26360. };
  26361. Box.prototype.copy = function (id) {
  26362. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26363. };
  26364. return Box;
  26365. })(_Primitive);
  26366. Primitives.Box = Box;
  26367. var Sphere = (function (_super) {
  26368. __extends(Sphere, _super);
  26369. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26370. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26371. this.segments = segments;
  26372. this.diameter = diameter;
  26373. this.side = side;
  26374. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26375. }
  26376. Sphere.prototype._regenerateVertexData = function () {
  26377. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26378. };
  26379. Sphere.prototype.copy = function (id) {
  26380. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26381. };
  26382. return Sphere;
  26383. })(_Primitive);
  26384. Primitives.Sphere = Sphere;
  26385. var Disc = (function (_super) {
  26386. __extends(Disc, _super);
  26387. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26389. this.radius = radius;
  26390. this.tessellation = tessellation;
  26391. this.side = side;
  26392. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26393. }
  26394. Disc.prototype._regenerateVertexData = function () {
  26395. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26396. };
  26397. Disc.prototype.copy = function (id) {
  26398. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26399. };
  26400. return Disc;
  26401. })(_Primitive);
  26402. Primitives.Disc = Disc;
  26403. var Cylinder = (function (_super) {
  26404. __extends(Cylinder, _super);
  26405. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26406. if (subdivisions === void 0) { subdivisions = 1; }
  26407. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26408. this.height = height;
  26409. this.diameterTop = diameterTop;
  26410. this.diameterBottom = diameterBottom;
  26411. this.tessellation = tessellation;
  26412. this.subdivisions = subdivisions;
  26413. this.side = side;
  26414. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26415. }
  26416. Cylinder.prototype._regenerateVertexData = function () {
  26417. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26418. };
  26419. Cylinder.prototype.copy = function (id) {
  26420. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26421. };
  26422. return Cylinder;
  26423. })(_Primitive);
  26424. Primitives.Cylinder = Cylinder;
  26425. var Torus = (function (_super) {
  26426. __extends(Torus, _super);
  26427. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26428. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26429. this.diameter = diameter;
  26430. this.thickness = thickness;
  26431. this.tessellation = tessellation;
  26432. this.side = side;
  26433. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26434. }
  26435. Torus.prototype._regenerateVertexData = function () {
  26436. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26437. };
  26438. Torus.prototype.copy = function (id) {
  26439. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26440. };
  26441. return Torus;
  26442. })(_Primitive);
  26443. Primitives.Torus = Torus;
  26444. var Ground = (function (_super) {
  26445. __extends(Ground, _super);
  26446. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26447. this.width = width;
  26448. this.height = height;
  26449. this.subdivisions = subdivisions;
  26450. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26451. }
  26452. Ground.prototype._regenerateVertexData = function () {
  26453. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26454. };
  26455. Ground.prototype.copy = function (id) {
  26456. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26457. };
  26458. return Ground;
  26459. })(_Primitive);
  26460. Primitives.Ground = Ground;
  26461. var TiledGround = (function (_super) {
  26462. __extends(TiledGround, _super);
  26463. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26464. this.xmin = xmin;
  26465. this.zmin = zmin;
  26466. this.xmax = xmax;
  26467. this.zmax = zmax;
  26468. this.subdivisions = subdivisions;
  26469. this.precision = precision;
  26470. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26471. }
  26472. TiledGround.prototype._regenerateVertexData = function () {
  26473. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26474. };
  26475. TiledGround.prototype.copy = function (id) {
  26476. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26477. };
  26478. return TiledGround;
  26479. })(_Primitive);
  26480. Primitives.TiledGround = TiledGround;
  26481. var Plane = (function (_super) {
  26482. __extends(Plane, _super);
  26483. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26484. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26485. this.size = size;
  26486. this.side = side;
  26487. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26488. }
  26489. Plane.prototype._regenerateVertexData = function () {
  26490. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26491. };
  26492. Plane.prototype.copy = function (id) {
  26493. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26494. };
  26495. return Plane;
  26496. })(_Primitive);
  26497. Primitives.Plane = Plane;
  26498. var TorusKnot = (function (_super) {
  26499. __extends(TorusKnot, _super);
  26500. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26501. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26502. this.radius = radius;
  26503. this.tube = tube;
  26504. this.radialSegments = radialSegments;
  26505. this.tubularSegments = tubularSegments;
  26506. this.p = p;
  26507. this.q = q;
  26508. this.side = side;
  26509. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26510. }
  26511. TorusKnot.prototype._regenerateVertexData = function () {
  26512. 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 });
  26513. };
  26514. TorusKnot.prototype.copy = function (id) {
  26515. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26516. };
  26517. return TorusKnot;
  26518. })(_Primitive);
  26519. Primitives.TorusKnot = TorusKnot;
  26520. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26521. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26522. })(BABYLON || (BABYLON = {}));
  26523. var BABYLON;
  26524. (function (BABYLON) {
  26525. var GroundMesh = (function (_super) {
  26526. __extends(GroundMesh, _super);
  26527. function GroundMesh(name, scene) {
  26528. _super.call(this, name, scene);
  26529. this.generateOctree = false;
  26530. this._worldInverse = new BABYLON.Matrix();
  26531. }
  26532. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26533. get: function () {
  26534. return this._subdivisions;
  26535. },
  26536. enumerable: true,
  26537. configurable: true
  26538. });
  26539. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26540. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26541. this._subdivisions = chunksCount;
  26542. this.subdivide(this._subdivisions);
  26543. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26544. };
  26545. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26546. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26547. this.getWorldMatrix().invertToRef(this._worldInverse);
  26548. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26549. var pickInfo = this.intersects(ray);
  26550. if (pickInfo.hit) {
  26551. return pickInfo.pickedPoint.y;
  26552. }
  26553. return 0;
  26554. };
  26555. return GroundMesh;
  26556. })(BABYLON.Mesh);
  26557. BABYLON.GroundMesh = GroundMesh;
  26558. })(BABYLON || (BABYLON = {}));
  26559. var BABYLON;
  26560. (function (BABYLON) {
  26561. var LinesMesh = (function (_super) {
  26562. __extends(LinesMesh, _super);
  26563. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26564. if (parent === void 0) { parent = null; }
  26565. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26566. this.color = new BABYLON.Color3(1, 1, 1);
  26567. this.alpha = 1;
  26568. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26569. attributes: ["position"],
  26570. uniforms: ["worldViewProjection", "color"],
  26571. needAlphaBlending: true
  26572. });
  26573. }
  26574. Object.defineProperty(LinesMesh.prototype, "material", {
  26575. get: function () {
  26576. return this._colorShader;
  26577. },
  26578. enumerable: true,
  26579. configurable: true
  26580. });
  26581. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26582. get: function () {
  26583. return false;
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26589. get: function () {
  26590. return false;
  26591. },
  26592. enumerable: true,
  26593. configurable: true
  26594. });
  26595. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26596. var engine = this.getScene().getEngine();
  26597. var indexToBind = this._geometry.getIndexBuffer();
  26598. // VBOs
  26599. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26600. // Color
  26601. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26602. };
  26603. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26604. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26605. return;
  26606. }
  26607. var engine = this.getScene().getEngine();
  26608. // Draw order
  26609. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26610. };
  26611. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26612. return null;
  26613. };
  26614. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26615. this._colorShader.dispose();
  26616. _super.prototype.dispose.call(this, doNotRecurse);
  26617. };
  26618. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26619. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26620. };
  26621. return LinesMesh;
  26622. })(BABYLON.Mesh);
  26623. BABYLON.LinesMesh = LinesMesh;
  26624. })(BABYLON || (BABYLON = {}));
  26625. var BABYLON;
  26626. (function (BABYLON) {
  26627. var DebugLayer = (function () {
  26628. function DebugLayer(scene) {
  26629. var _this = this;
  26630. this._transformationMatrix = BABYLON.Matrix.Identity();
  26631. this._enabled = false;
  26632. this._labelsEnabled = false;
  26633. this._displayStatistics = true;
  26634. this._displayTree = false;
  26635. this._displayLogs = false;
  26636. this._identityMatrix = BABYLON.Matrix.Identity();
  26637. this.axisRatio = 0.02;
  26638. this.accentColor = "orange";
  26639. this._scene = scene;
  26640. this._syncPositions = function () {
  26641. var engine = _this._scene.getEngine();
  26642. var canvasRect = engine.getRenderingCanvasClientRect();
  26643. if (_this._showUI) {
  26644. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26645. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26646. _this._statsDiv.style.width = "400px";
  26647. _this._statsDiv.style.height = "auto";
  26648. _this._statsSubsetDiv.style.maxHeight = "240px";
  26649. _this._optionsDiv.style.left = "0px";
  26650. _this._optionsDiv.style.top = "10px";
  26651. _this._optionsDiv.style.width = "200px";
  26652. _this._optionsDiv.style.height = "auto";
  26653. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26654. _this._logDiv.style.left = "0px";
  26655. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26656. _this._logDiv.style.width = "600px";
  26657. _this._logDiv.style.height = "160px";
  26658. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26659. _this._treeDiv.style.top = "10px";
  26660. _this._treeDiv.style.width = "300px";
  26661. _this._treeDiv.style.height = "auto";
  26662. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26663. }
  26664. _this._globalDiv.style.left = canvasRect.left + "px";
  26665. _this._globalDiv.style.top = canvasRect.top + "px";
  26666. _this._drawingCanvas.style.left = "0px";
  26667. _this._drawingCanvas.style.top = "0px";
  26668. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26669. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26670. var devicePixelRatio = window.devicePixelRatio || 1;
  26671. var context = _this._drawingContext;
  26672. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26673. context.mozBackingStorePixelRatio ||
  26674. context.msBackingStorePixelRatio ||
  26675. context.oBackingStorePixelRatio ||
  26676. context.backingStorePixelRatio || 1;
  26677. _this._ratio = devicePixelRatio / backingStoreRatio;
  26678. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26679. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26680. };
  26681. this._onCanvasClick = function (evt) {
  26682. _this._clickPosition = {
  26683. x: evt.clientX * _this._ratio,
  26684. y: evt.clientY * _this._ratio
  26685. };
  26686. };
  26687. this._syncUI = function () {
  26688. if (_this._showUI) {
  26689. if (_this._displayStatistics) {
  26690. _this._displayStats();
  26691. _this._statsDiv.style.display = "";
  26692. }
  26693. else {
  26694. _this._statsDiv.style.display = "none";
  26695. }
  26696. if (_this._displayLogs) {
  26697. _this._logDiv.style.display = "";
  26698. }
  26699. else {
  26700. _this._logDiv.style.display = "none";
  26701. }
  26702. if (_this._displayTree) {
  26703. _this._treeDiv.style.display = "";
  26704. if (_this._needToRefreshMeshesTree) {
  26705. _this._needToRefreshMeshesTree = false;
  26706. _this._refreshMeshesTreeContent();
  26707. }
  26708. }
  26709. else {
  26710. _this._treeDiv.style.display = "none";
  26711. }
  26712. }
  26713. };
  26714. this._syncData = function () {
  26715. if (_this._labelsEnabled || !_this._showUI) {
  26716. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26717. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26718. var engine = _this._scene.getEngine();
  26719. var viewport = _this._camera.viewport;
  26720. var globalViewport = viewport.toGlobal(engine);
  26721. // Meshes
  26722. var meshes = _this._camera.getActiveMeshes();
  26723. for (var index = 0; index < meshes.length; index++) {
  26724. var mesh = meshes.data[index];
  26725. var position = mesh.getBoundingInfo().boundingSphere.center;
  26726. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26727. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26728. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26729. }
  26730. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26731. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26732. }
  26733. }
  26734. // Cameras
  26735. var cameras = _this._scene.cameras;
  26736. for (index = 0; index < cameras.length; index++) {
  26737. var camera = cameras[index];
  26738. if (camera === _this._camera) {
  26739. continue;
  26740. }
  26741. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26742. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26743. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26744. _this._camera.detachControl(engine.getRenderingCanvas());
  26745. _this._camera = camera;
  26746. _this._camera.attachControl(engine.getRenderingCanvas());
  26747. }, function () { return "purple"; });
  26748. }
  26749. }
  26750. // Lights
  26751. var lights = _this._scene.lights;
  26752. for (index = 0; index < lights.length; index++) {
  26753. var light = lights[index];
  26754. if (light.position) {
  26755. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26756. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26757. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26758. light.setEnabled(!light.isEnabled());
  26759. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26760. }
  26761. }
  26762. }
  26763. }
  26764. _this._clickPosition = undefined;
  26765. };
  26766. }
  26767. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26768. while (this._treeSubsetDiv.hasChildNodes()) {
  26769. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26770. }
  26771. // Add meshes
  26772. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26773. sortedArray.sort(function (a, b) {
  26774. if (a.name === b.name) {
  26775. return 0;
  26776. }
  26777. return (a.name > b.name) ? 1 : -1;
  26778. });
  26779. for (var index = 0; index < sortedArray.length; index++) {
  26780. var mesh = sortedArray[index];
  26781. if (!mesh.isEnabled()) {
  26782. continue;
  26783. }
  26784. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26785. m.isVisible = element.checked;
  26786. }, mesh);
  26787. }
  26788. };
  26789. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26790. this._drawingContext.beginPath();
  26791. this._drawingContext.moveTo(zero.x, zero.y);
  26792. this._drawingContext.lineTo(unit.x, unit.y);
  26793. this._drawingContext.strokeStyle = color;
  26794. this._drawingContext.lineWidth = 4;
  26795. this._drawingContext.stroke();
  26796. this._drawingContext.font = "normal 14px Segoe UI";
  26797. this._drawingContext.fillStyle = color;
  26798. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26799. };
  26800. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26801. var position = mesh.getBoundingInfo().boundingSphere.center;
  26802. var worldMatrix = mesh.getWorldMatrix();
  26803. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26804. var unit = (unprojectedVector.subtract(position)).length();
  26805. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26806. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26807. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26808. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26809. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26810. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26811. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26812. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26813. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26814. };
  26815. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26816. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26817. this._drawingContext.font = "normal 12px Segoe UI";
  26818. var textMetrics = this._drawingContext.measureText(text);
  26819. var centerX = projectedPosition.x - textMetrics.width / 2;
  26820. var centerY = projectedPosition.y;
  26821. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26822. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26823. onClick();
  26824. }
  26825. this._drawingContext.beginPath();
  26826. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26827. this._drawingContext.fillStyle = getFillStyle();
  26828. this._drawingContext.globalAlpha = 0.5;
  26829. this._drawingContext.fill();
  26830. this._drawingContext.globalAlpha = 1.0;
  26831. this._drawingContext.strokeStyle = '#FFFFFF';
  26832. this._drawingContext.lineWidth = 1;
  26833. this._drawingContext.stroke();
  26834. this._drawingContext.fillStyle = "#FFFFFF";
  26835. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26836. this._drawingContext.beginPath();
  26837. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26838. this._drawingContext.fill();
  26839. }
  26840. };
  26841. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26842. if (!this._clickPosition) {
  26843. return false;
  26844. }
  26845. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26846. return false;
  26847. }
  26848. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26849. return false;
  26850. }
  26851. return true;
  26852. };
  26853. DebugLayer.prototype.isVisible = function () {
  26854. return this._enabled;
  26855. };
  26856. DebugLayer.prototype.hide = function () {
  26857. if (!this._enabled) {
  26858. return;
  26859. }
  26860. this._enabled = false;
  26861. var engine = this._scene.getEngine();
  26862. this._scene.unregisterBeforeRender(this._syncData);
  26863. this._scene.unregisterAfterRender(this._syncUI);
  26864. this._rootElement.removeChild(this._globalDiv);
  26865. this._scene.forceShowBoundingBoxes = false;
  26866. this._scene.forceWireframe = false;
  26867. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26868. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26869. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26870. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26871. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26872. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26873. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26874. BABYLON.StandardMaterial.LightmapEnabled = true;
  26875. this._scene.shadowsEnabled = true;
  26876. this._scene.particlesEnabled = true;
  26877. this._scene.postProcessesEnabled = true;
  26878. this._scene.collisionsEnabled = true;
  26879. this._scene.lightsEnabled = true;
  26880. this._scene.texturesEnabled = true;
  26881. this._scene.lensFlaresEnabled = true;
  26882. this._scene.proceduralTexturesEnabled = true;
  26883. this._scene.renderTargetsEnabled = true;
  26884. this._scene.probesEnabled = true;
  26885. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26886. };
  26887. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26888. if (showUI === void 0) { showUI = true; }
  26889. if (camera === void 0) { camera = null; }
  26890. if (rootElement === void 0) { rootElement = null; }
  26891. if (this._enabled) {
  26892. return;
  26893. }
  26894. this._enabled = true;
  26895. if (camera) {
  26896. this._camera = camera;
  26897. }
  26898. else {
  26899. this._camera = this._scene.activeCamera;
  26900. }
  26901. this._showUI = showUI;
  26902. var engine = this._scene.getEngine();
  26903. this._globalDiv = document.createElement("div");
  26904. this._rootElement = rootElement || document.body;
  26905. this._rootElement.appendChild(this._globalDiv);
  26906. this._generateDOMelements();
  26907. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26908. this._syncPositions();
  26909. this._scene.registerBeforeRender(this._syncData);
  26910. this._scene.registerAfterRender(this._syncUI);
  26911. };
  26912. DebugLayer.prototype._clearLabels = function () {
  26913. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26914. for (var index = 0; index < this._scene.meshes.length; index++) {
  26915. var mesh = this._scene.meshes[index];
  26916. mesh.renderOverlay = false;
  26917. }
  26918. };
  26919. DebugLayer.prototype._generateheader = function (root, text) {
  26920. var header = document.createElement("div");
  26921. header.innerHTML = text + "&nbsp;";
  26922. header.style.textAlign = "right";
  26923. header.style.width = "100%";
  26924. header.style.color = "white";
  26925. header.style.backgroundColor = "Black";
  26926. header.style.padding = "5px 5px 4px 0px";
  26927. header.style.marginLeft = "-5px";
  26928. header.style.fontWeight = "bold";
  26929. root.appendChild(header);
  26930. };
  26931. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26932. var label = document.createElement("label");
  26933. label.innerHTML = title;
  26934. label.style.color = color;
  26935. root.appendChild(label);
  26936. root.appendChild(document.createElement("br"));
  26937. };
  26938. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26939. if (tag === void 0) { tag = null; }
  26940. var label = document.createElement("label");
  26941. var boundingBoxesCheckbox = document.createElement("input");
  26942. boundingBoxesCheckbox.type = "checkbox";
  26943. boundingBoxesCheckbox.checked = initialState;
  26944. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26945. task(evt.target, tag);
  26946. });
  26947. label.appendChild(boundingBoxesCheckbox);
  26948. var container = document.createElement("span");
  26949. var leftPart = document.createElement("span");
  26950. var rightPart = document.createElement("span");
  26951. rightPart.style.cssFloat = "right";
  26952. leftPart.innerHTML = leftTitle;
  26953. rightPart.innerHTML = rightTitle;
  26954. rightPart.style.fontSize = "12px";
  26955. rightPart.style.maxWidth = "200px";
  26956. container.appendChild(leftPart);
  26957. container.appendChild(rightPart);
  26958. label.appendChild(container);
  26959. root.appendChild(label);
  26960. root.appendChild(document.createElement("br"));
  26961. };
  26962. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26963. if (tag === void 0) { tag = null; }
  26964. var label = document.createElement("label");
  26965. var checkBox = document.createElement("input");
  26966. checkBox.type = "checkbox";
  26967. checkBox.checked = initialState;
  26968. checkBox.addEventListener("change", function (evt) {
  26969. task(evt.target, tag);
  26970. });
  26971. label.appendChild(checkBox);
  26972. label.appendChild(document.createTextNode(title));
  26973. root.appendChild(label);
  26974. root.appendChild(document.createElement("br"));
  26975. };
  26976. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26977. if (tag === void 0) { tag = null; }
  26978. var button = document.createElement("button");
  26979. button.innerHTML = title;
  26980. button.style.height = "24px";
  26981. button.style.width = "150px";
  26982. button.style.marginBottom = "5px";
  26983. button.style.color = "#444444";
  26984. button.style.border = "1px solid white";
  26985. button.className = "debugLayerButton";
  26986. button.addEventListener("click", function (evt) {
  26987. task(evt.target, tag);
  26988. });
  26989. root.appendChild(button);
  26990. root.appendChild(document.createElement("br"));
  26991. };
  26992. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26993. if (tag === void 0) { tag = null; }
  26994. var label = document.createElement("label");
  26995. var boundingBoxesRadio = document.createElement("input");
  26996. boundingBoxesRadio.type = "radio";
  26997. boundingBoxesRadio.name = name;
  26998. boundingBoxesRadio.checked = initialState;
  26999. boundingBoxesRadio.addEventListener("change", function (evt) {
  27000. task(evt.target, tag);
  27001. });
  27002. label.appendChild(boundingBoxesRadio);
  27003. label.appendChild(document.createTextNode(title));
  27004. root.appendChild(label);
  27005. root.appendChild(document.createElement("br"));
  27006. };
  27007. DebugLayer.prototype._generateDOMelements = function () {
  27008. var _this = this;
  27009. this._globalDiv.id = "DebugLayer";
  27010. this._globalDiv.style.position = "absolute";
  27011. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27012. this._globalDiv.style.fontSize = "14px";
  27013. this._globalDiv.style.color = "white";
  27014. // Drawing canvas
  27015. this._drawingCanvas = document.createElement("canvas");
  27016. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27017. this._drawingCanvas.style.position = "absolute";
  27018. this._drawingCanvas.style.pointerEvents = "none";
  27019. this._drawingCanvas.style.backgroundColor = "transparent";
  27020. this._drawingContext = this._drawingCanvas.getContext("2d");
  27021. this._globalDiv.appendChild(this._drawingCanvas);
  27022. if (this._showUI) {
  27023. var background = "rgba(128, 128, 128, 0.4)";
  27024. var border = "rgb(180, 180, 180) solid 1px";
  27025. // Stats
  27026. this._statsDiv = document.createElement("div");
  27027. this._statsDiv.id = "DebugLayerStats";
  27028. this._statsDiv.style.border = border;
  27029. this._statsDiv.style.position = "absolute";
  27030. this._statsDiv.style.background = background;
  27031. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27032. this._generateheader(this._statsDiv, "STATISTICS");
  27033. this._statsSubsetDiv = document.createElement("div");
  27034. this._statsSubsetDiv.style.paddingTop = "5px";
  27035. this._statsSubsetDiv.style.paddingBottom = "5px";
  27036. this._statsSubsetDiv.style.overflowY = "auto";
  27037. this._statsDiv.appendChild(this._statsSubsetDiv);
  27038. // Tree
  27039. this._treeDiv = document.createElement("div");
  27040. this._treeDiv.id = "DebugLayerTree";
  27041. this._treeDiv.style.border = border;
  27042. this._treeDiv.style.position = "absolute";
  27043. this._treeDiv.style.background = background;
  27044. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27045. this._treeDiv.style.display = "none";
  27046. this._generateheader(this._treeDiv, "MESHES TREE");
  27047. this._treeSubsetDiv = document.createElement("div");
  27048. this._treeSubsetDiv.style.paddingTop = "5px";
  27049. this._treeSubsetDiv.style.paddingRight = "5px";
  27050. this._treeSubsetDiv.style.overflowY = "auto";
  27051. this._treeSubsetDiv.style.maxHeight = "300px";
  27052. this._treeDiv.appendChild(this._treeSubsetDiv);
  27053. this._needToRefreshMeshesTree = true;
  27054. // Logs
  27055. this._logDiv = document.createElement("div");
  27056. this._logDiv.style.border = border;
  27057. this._logDiv.id = "DebugLayerLogs";
  27058. this._logDiv.style.position = "absolute";
  27059. this._logDiv.style.background = background;
  27060. this._logDiv.style.padding = "0px 0px 0px 5px";
  27061. this._logDiv.style.display = "none";
  27062. this._generateheader(this._logDiv, "LOGS");
  27063. this._logSubsetDiv = document.createElement("div");
  27064. this._logSubsetDiv.style.height = "127px";
  27065. this._logSubsetDiv.style.paddingTop = "5px";
  27066. this._logSubsetDiv.style.overflowY = "auto";
  27067. this._logSubsetDiv.style.fontSize = "12px";
  27068. this._logSubsetDiv.style.fontFamily = "consolas";
  27069. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27070. this._logDiv.appendChild(this._logSubsetDiv);
  27071. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27072. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27073. };
  27074. // Options
  27075. this._optionsDiv = document.createElement("div");
  27076. this._optionsDiv.id = "DebugLayerOptions";
  27077. this._optionsDiv.style.border = border;
  27078. this._optionsDiv.style.position = "absolute";
  27079. this._optionsDiv.style.background = background;
  27080. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27081. this._optionsDiv.style.overflowY = "auto";
  27082. this._generateheader(this._optionsDiv, "OPTIONS");
  27083. this._optionsSubsetDiv = document.createElement("div");
  27084. this._optionsSubsetDiv.style.paddingTop = "5px";
  27085. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27086. this._optionsSubsetDiv.style.overflowY = "auto";
  27087. this._optionsSubsetDiv.style.maxHeight = "200px";
  27088. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27089. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27090. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27091. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27092. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27093. _this._displayTree = element.checked;
  27094. _this._needToRefreshMeshesTree = true;
  27095. });
  27096. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27097. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27098. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27099. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27100. _this._labelsEnabled = element.checked;
  27101. if (!_this._labelsEnabled) {
  27102. _this._clearLabels();
  27103. }
  27104. });
  27105. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27106. if (element.checked) {
  27107. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27108. }
  27109. else {
  27110. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27111. }
  27112. });
  27113. ;
  27114. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27115. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27116. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27117. if (element.checked) {
  27118. _this._scene.forceWireframe = false;
  27119. _this._scene.forcePointsCloud = false;
  27120. }
  27121. });
  27122. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27123. if (element.checked) {
  27124. _this._scene.forceWireframe = true;
  27125. _this._scene.forcePointsCloud = false;
  27126. }
  27127. });
  27128. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27129. if (element.checked) {
  27130. _this._scene.forceWireframe = false;
  27131. _this._scene.forcePointsCloud = true;
  27132. }
  27133. });
  27134. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27135. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27136. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27137. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27138. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27139. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27140. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27141. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27142. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27143. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27144. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27145. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27146. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27147. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27148. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27149. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27150. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27151. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27152. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27153. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27154. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27155. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27156. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27157. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27158. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27159. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27160. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27161. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27162. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27163. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27164. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27165. if (element.checked) {
  27166. _this._scene.headphone = true;
  27167. }
  27168. });
  27169. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27170. if (element.checked) {
  27171. _this._scene.headphone = false;
  27172. }
  27173. });
  27174. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27175. _this._scene.audioEnabled = !element.checked;
  27176. });
  27177. }
  27178. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27179. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27180. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27181. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27182. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27183. this._globalDiv.appendChild(this._statsDiv);
  27184. this._globalDiv.appendChild(this._logDiv);
  27185. this._globalDiv.appendChild(this._optionsDiv);
  27186. this._globalDiv.appendChild(this._treeDiv);
  27187. }
  27188. };
  27189. DebugLayer.prototype._displayStats = function () {
  27190. var scene = this._scene;
  27191. var engine = scene.getEngine();
  27192. var glInfo = engine.getGlInfo();
  27193. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27194. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27195. + "<b>Count</b><br>"
  27196. + "Total meshes: " + scene.meshes.length + "<br>"
  27197. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27198. + "Total materials: " + scene.materials.length + "<br>"
  27199. + "Total textures: " + scene.textures.length + "<br>"
  27200. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27201. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27202. + "Active bones: " + scene.getActiveBones() + "<br>"
  27203. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27204. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27205. + "<b>Duration</b><br>"
  27206. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27207. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27208. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27209. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27210. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27211. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27212. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27213. + "</div>"
  27214. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27215. + "<b>Extensions</b><br>"
  27216. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27217. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27218. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27219. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27220. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27221. + "<b>Caps.</b><br>"
  27222. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27223. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27224. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27225. + "</div><br>"
  27226. + "<b>Info</b><br>"
  27227. + glInfo.version + "<br>"
  27228. + glInfo.renderer + "<br>";
  27229. if (this.customStatsFunction) {
  27230. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27231. }
  27232. };
  27233. return DebugLayer;
  27234. })();
  27235. BABYLON.DebugLayer = DebugLayer;
  27236. })(BABYLON || (BABYLON = {}));
  27237. var BABYLON;
  27238. (function (BABYLON) {
  27239. var DefaultLoadingScreen = (function () {
  27240. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27241. var _this = this;
  27242. if (_loadingText === void 0) { _loadingText = ""; }
  27243. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27244. this._renderingCanvas = _renderingCanvas;
  27245. this._loadingText = _loadingText;
  27246. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27247. // Resize
  27248. this._resizeLoadingUI = function () {
  27249. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27250. _this._loadingDiv.style.position = "absolute";
  27251. _this._loadingDiv.style.left = canvasRect.left + "px";
  27252. _this._loadingDiv.style.top = canvasRect.top + "px";
  27253. _this._loadingDiv.style.width = canvasRect.width + "px";
  27254. _this._loadingDiv.style.height = canvasRect.height + "px";
  27255. };
  27256. }
  27257. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27258. var _this = this;
  27259. this._loadingDiv = document.createElement("div");
  27260. this._loadingDiv.style.opacity = "0";
  27261. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27262. // Loading text
  27263. this._loadingTextDiv = document.createElement("div");
  27264. this._loadingTextDiv.style.position = "absolute";
  27265. this._loadingTextDiv.style.left = "0";
  27266. this._loadingTextDiv.style.top = "50%";
  27267. this._loadingTextDiv.style.marginTop = "80px";
  27268. this._loadingTextDiv.style.width = "100%";
  27269. this._loadingTextDiv.style.height = "20px";
  27270. this._loadingTextDiv.style.fontFamily = "Arial";
  27271. this._loadingTextDiv.style.fontSize = "14px";
  27272. this._loadingTextDiv.style.color = "white";
  27273. this._loadingTextDiv.style.textAlign = "center";
  27274. this._loadingTextDiv.innerHTML = "Loading";
  27275. this._loadingDiv.appendChild(this._loadingTextDiv);
  27276. //set the predefined text
  27277. this._loadingTextDiv.innerHTML = this._loadingText;
  27278. // Loading img
  27279. var imgBack = new Image();
  27280. 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==";
  27281. imgBack.style.position = "absolute";
  27282. imgBack.style.left = "50%";
  27283. imgBack.style.top = "50%";
  27284. imgBack.style.marginLeft = "-50px";
  27285. imgBack.style.marginTop = "-50px";
  27286. imgBack.style.transition = "transform 1.0s ease";
  27287. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27288. var deg = 360;
  27289. var onTransitionEnd = function () {
  27290. deg += 360;
  27291. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27292. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27293. };
  27294. imgBack.addEventListener("transitionend", onTransitionEnd);
  27295. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27296. this._loadingDiv.appendChild(imgBack);
  27297. // front image
  27298. var imgFront = new Image();
  27299. 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=";
  27300. imgFront.style.position = "absolute";
  27301. imgFront.style.left = "50%";
  27302. imgFront.style.top = "50%";
  27303. imgFront.style.marginLeft = "-50px";
  27304. imgFront.style.marginTop = "-50px";
  27305. this._loadingDiv.appendChild(imgFront);
  27306. this._resizeLoadingUI();
  27307. window.addEventListener("resize", this._resizeLoadingUI);
  27308. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27309. document.body.appendChild(this._loadingDiv);
  27310. setTimeout(function () {
  27311. _this._loadingDiv.style.opacity = "1";
  27312. imgBack.style.transform = "rotateZ(360deg)";
  27313. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27314. }, 0);
  27315. };
  27316. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27317. var _this = this;
  27318. if (!this._loadingDiv) {
  27319. return;
  27320. }
  27321. var onTransitionEnd = function () {
  27322. if (!_this._loadingDiv) {
  27323. return;
  27324. }
  27325. document.body.removeChild(_this._loadingDiv);
  27326. window.removeEventListener("resize", _this._resizeLoadingUI);
  27327. _this._loadingDiv = null;
  27328. };
  27329. this._loadingDiv.style.opacity = "0";
  27330. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27331. };
  27332. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27333. set: function (text) {
  27334. this._loadingText = text;
  27335. if (this._loadingTextDiv) {
  27336. this._loadingTextDiv.innerHTML = this._loadingText;
  27337. }
  27338. },
  27339. enumerable: true,
  27340. configurable: true
  27341. });
  27342. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27343. get: function () {
  27344. return this._loadingDivBackgroundColor;
  27345. },
  27346. set: function (color) {
  27347. this._loadingDivBackgroundColor = color;
  27348. if (!this._loadingDiv) {
  27349. return;
  27350. }
  27351. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27352. },
  27353. enumerable: true,
  27354. configurable: true
  27355. });
  27356. return DefaultLoadingScreen;
  27357. })();
  27358. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27359. })(BABYLON || (BABYLON = {}));
  27360. var BABYLON;
  27361. (function (BABYLON) {
  27362. var SIMDVector3 = (function () {
  27363. function SIMDVector3() {
  27364. }
  27365. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27366. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27367. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27368. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27369. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27370. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27371. 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));
  27372. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27373. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27374. };
  27375. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27376. var v0 = SIMD.float32x4.splat(x);
  27377. var v1 = SIMD.float32x4.splat(y);
  27378. var v2 = SIMD.float32x4.splat(z);
  27379. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27380. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27381. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27382. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27383. 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));
  27384. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27385. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27386. };
  27387. return SIMDVector3;
  27388. })();
  27389. BABYLON.SIMDVector3 = SIMDVector3;
  27390. var SIMDMatrix = (function () {
  27391. function SIMDMatrix() {
  27392. }
  27393. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27394. if (offset === void 0) { offset = 0; }
  27395. var tm = this.m;
  27396. var om = other.m;
  27397. var om0 = SIMD.float32x4.load(om, 0);
  27398. var om1 = SIMD.float32x4.load(om, 4);
  27399. var om2 = SIMD.float32x4.load(om, 8);
  27400. var om3 = SIMD.float32x4.load(om, 12);
  27401. var tm0 = SIMD.float32x4.load(tm, 0);
  27402. 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)))));
  27403. var tm1 = SIMD.float32x4.load(tm, 4);
  27404. 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)))));
  27405. var tm2 = SIMD.float32x4.load(tm, 8);
  27406. 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)))));
  27407. var tm3 = SIMD.float32x4.load(tm, 12);
  27408. 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)))));
  27409. };
  27410. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27411. var src = this.m;
  27412. var dest = other.m;
  27413. var row0, row1, row2, row3;
  27414. var tmp1;
  27415. var minor0, minor1, minor2, minor3;
  27416. var det;
  27417. // Load the 4 rows
  27418. var src0 = SIMD.float32x4.load(src, 0);
  27419. var src1 = SIMD.float32x4.load(src, 4);
  27420. var src2 = SIMD.float32x4.load(src, 8);
  27421. var src3 = SIMD.float32x4.load(src, 12);
  27422. // Transpose the source matrix. Sort of. Not a true transpose operation
  27423. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27424. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27425. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27426. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27427. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27428. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27429. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27430. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27431. // This is a true transposition, but it will lead to an incorrect result
  27432. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27433. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27434. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27435. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27436. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27437. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27438. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27439. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27440. // ----
  27441. tmp1 = SIMD.float32x4.mul(row2, row3);
  27442. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27443. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27444. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27445. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27446. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27447. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27448. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27449. // ----
  27450. tmp1 = SIMD.float32x4.mul(row1, row2);
  27451. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27452. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27453. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27454. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27455. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27456. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27457. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27458. // ----
  27459. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27460. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27461. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27462. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27463. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27464. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27465. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27466. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27467. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27468. // ----
  27469. tmp1 = SIMD.float32x4.mul(row0, row1);
  27470. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27471. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27472. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27473. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27474. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27475. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27476. // ----
  27477. tmp1 = SIMD.float32x4.mul(row0, row3);
  27478. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27479. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27480. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27481. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27482. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27483. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27484. // ----
  27485. tmp1 = SIMD.float32x4.mul(row0, row2);
  27486. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27487. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27488. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27489. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27490. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27491. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27492. // Compute determinant
  27493. det = SIMD.float32x4.mul(row0, minor0);
  27494. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27495. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27496. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27497. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27498. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27499. // These shuffles aren't necessary if the faulty transposition is done
  27500. // up at the top of this function.
  27501. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27502. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27503. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27504. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27505. // Compute final values by multiplying with 1/det
  27506. minor0 = SIMD.float32x4.mul(det, minor0);
  27507. minor1 = SIMD.float32x4.mul(det, minor1);
  27508. minor2 = SIMD.float32x4.mul(det, minor2);
  27509. minor3 = SIMD.float32x4.mul(det, minor3);
  27510. SIMD.float32x4.store(dest, 0, minor0);
  27511. SIMD.float32x4.store(dest, 4, minor1);
  27512. SIMD.float32x4.store(dest, 8, minor2);
  27513. SIMD.float32x4.store(dest, 12, minor3);
  27514. return this;
  27515. };
  27516. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27517. var out = result.m;
  27518. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27519. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27520. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27521. // cc.kmVec3Subtract(f, pCenter, pEye);
  27522. var f = SIMD.float32x4.sub(center, eye);
  27523. // cc.kmVec3Normalize(f, f);
  27524. var tmp = SIMD.float32x4.mul(f, f);
  27525. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27526. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27527. // cc.kmVec3Assign(up, pUp);
  27528. // cc.kmVec3Normalize(up, up);
  27529. tmp = SIMD.float32x4.mul(up, up);
  27530. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27531. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27532. // cc.kmVec3Cross(s, f, up);
  27533. 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)));
  27534. // cc.kmVec3Normalize(s, s);
  27535. tmp = SIMD.float32x4.mul(s, s);
  27536. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27537. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27538. // cc.kmVec3Cross(u, s, f);
  27539. 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)));
  27540. // cc.kmVec3Normalize(s, s);
  27541. tmp = SIMD.float32x4.mul(s, s);
  27542. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27543. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27544. var zero = SIMD.float32x4.splat(0.0);
  27545. s = SIMD.float32x4.neg(s);
  27546. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27547. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27548. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27549. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27550. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27551. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27552. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27553. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27554. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27555. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27556. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27557. var b3 = SIMD.float32x4.neg(eye);
  27558. b3 = SIMD.float32x4.withW(b3, 1.0);
  27559. 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)))));
  27560. 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)))));
  27561. 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)))));
  27562. 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)))));
  27563. };
  27564. return SIMDMatrix;
  27565. })();
  27566. BABYLON.SIMDMatrix = SIMDMatrix;
  27567. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27568. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27569. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27570. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27571. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27572. var SIMDHelper = (function () {
  27573. function SIMDHelper() {
  27574. }
  27575. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27576. get: function () {
  27577. return SIMDHelper._isEnabled;
  27578. },
  27579. enumerable: true,
  27580. configurable: true
  27581. });
  27582. SIMDHelper.DisableSIMD = function () {
  27583. // Replace functions
  27584. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27585. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27586. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27587. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27588. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27589. SIMDHelper._isEnabled = false;
  27590. };
  27591. SIMDHelper.EnableSIMD = function () {
  27592. if (window.SIMD === undefined) {
  27593. return;
  27594. }
  27595. // Replace functions
  27596. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27597. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27598. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27599. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27600. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27601. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27602. get: function () { return this._data[0]; },
  27603. set: function (value) {
  27604. if (!this._data) {
  27605. this._data = new Float32Array(3);
  27606. }
  27607. this._data[0] = value;
  27608. }
  27609. });
  27610. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27611. get: function () { return this._data[1]; },
  27612. set: function (value) {
  27613. this._data[1] = value;
  27614. }
  27615. });
  27616. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27617. get: function () { return this._data[2]; },
  27618. set: function (value) {
  27619. this._data[2] = value;
  27620. }
  27621. });
  27622. SIMDHelper._isEnabled = true;
  27623. };
  27624. SIMDHelper._isEnabled = false;
  27625. return SIMDHelper;
  27626. })();
  27627. BABYLON.SIMDHelper = SIMDHelper;
  27628. })(BABYLON || (BABYLON = {}));
  27629. var BABYLON;
  27630. (function (BABYLON) {
  27631. var ShaderMaterial = (function (_super) {
  27632. __extends(ShaderMaterial, _super);
  27633. function ShaderMaterial(name, scene, shaderPath, options) {
  27634. _super.call(this, name, scene);
  27635. this._textures = new Array();
  27636. this._floats = new Array();
  27637. this._floatsArrays = {};
  27638. this._colors3 = new Array();
  27639. this._colors4 = new Array();
  27640. this._vectors2 = new Array();
  27641. this._vectors3 = new Array();
  27642. this._vectors4 = new Array();
  27643. this._matrices = new Array();
  27644. this._matrices3x3 = new Array();
  27645. this._matrices2x2 = new Array();
  27646. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27647. this._shaderPath = shaderPath;
  27648. options.needAlphaBlending = options.needAlphaBlending || false;
  27649. options.needAlphaTesting = options.needAlphaTesting || false;
  27650. options.attributes = options.attributes || ["position", "normal", "uv"];
  27651. options.uniforms = options.uniforms || ["worldViewProjection"];
  27652. options.samplers = options.samplers || [];
  27653. options.defines = options.defines || [];
  27654. this._options = options;
  27655. }
  27656. ShaderMaterial.prototype.needAlphaBlending = function () {
  27657. return this._options.needAlphaBlending;
  27658. };
  27659. ShaderMaterial.prototype.needAlphaTesting = function () {
  27660. return this._options.needAlphaTesting;
  27661. };
  27662. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27663. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27664. this._options.uniforms.push(uniformName);
  27665. }
  27666. };
  27667. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27668. if (this._options.samplers.indexOf(name) === -1) {
  27669. this._options.samplers.push(name);
  27670. }
  27671. this._textures[name] = texture;
  27672. return this;
  27673. };
  27674. ShaderMaterial.prototype.setFloat = function (name, value) {
  27675. this._checkUniform(name);
  27676. this._floats[name] = value;
  27677. return this;
  27678. };
  27679. ShaderMaterial.prototype.setFloats = function (name, value) {
  27680. this._checkUniform(name);
  27681. this._floatsArrays[name] = value;
  27682. return this;
  27683. };
  27684. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27685. this._checkUniform(name);
  27686. this._colors3[name] = value;
  27687. return this;
  27688. };
  27689. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27690. this._checkUniform(name);
  27691. this._colors4[name] = value;
  27692. return this;
  27693. };
  27694. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27695. this._checkUniform(name);
  27696. this._vectors2[name] = value;
  27697. return this;
  27698. };
  27699. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27700. this._checkUniform(name);
  27701. this._vectors3[name] = value;
  27702. return this;
  27703. };
  27704. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27705. this._checkUniform(name);
  27706. this._vectors4[name] = value;
  27707. return this;
  27708. };
  27709. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27710. this._checkUniform(name);
  27711. this._matrices[name] = value;
  27712. return this;
  27713. };
  27714. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27715. this._checkUniform(name);
  27716. this._matrices3x3[name] = value;
  27717. return this;
  27718. };
  27719. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27720. this._checkUniform(name);
  27721. this._matrices2x2[name] = value;
  27722. return this;
  27723. };
  27724. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27725. var scene = this.getScene();
  27726. var engine = scene.getEngine();
  27727. if (!this.checkReadyOnEveryCall) {
  27728. if (this._renderId === scene.getRenderId()) {
  27729. return true;
  27730. }
  27731. }
  27732. // Instances
  27733. var defines = [];
  27734. var fallbacks = new BABYLON.EffectFallbacks();
  27735. if (useInstances) {
  27736. defines.push("#define INSTANCES");
  27737. }
  27738. for (var index = 0; index < this._options.defines.length; index++) {
  27739. defines.push(this._options.defines[index]);
  27740. }
  27741. // Bones
  27742. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27743. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  27744. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27745. fallbacks.addCPUSkinningFallback(0, mesh);
  27746. }
  27747. // Alpha test
  27748. if (engine.getAlphaTesting()) {
  27749. defines.push("#define ALPHATEST");
  27750. }
  27751. var previousEffect = this._effect;
  27752. var join = defines.join("\n");
  27753. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27754. if (!this._effect.isReady()) {
  27755. return false;
  27756. }
  27757. if (previousEffect !== this._effect) {
  27758. scene.resetCachedMaterial();
  27759. }
  27760. this._renderId = scene.getRenderId();
  27761. return true;
  27762. };
  27763. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27764. var scene = this.getScene();
  27765. if (this._options.uniforms.indexOf("world") !== -1) {
  27766. this._effect.setMatrix("world", world);
  27767. }
  27768. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27769. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27770. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27771. }
  27772. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27773. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27774. }
  27775. };
  27776. ShaderMaterial.prototype.bind = function (world, mesh) {
  27777. // Std values
  27778. this.bindOnlyWorldMatrix(world);
  27779. if (this.getScene().getCachedMaterial() !== this) {
  27780. if (this._options.uniforms.indexOf("view") !== -1) {
  27781. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27782. }
  27783. if (this._options.uniforms.indexOf("projection") !== -1) {
  27784. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27785. }
  27786. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27787. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27788. }
  27789. // Bones
  27790. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27791. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27792. }
  27793. // Texture
  27794. for (var name in this._textures) {
  27795. this._effect.setTexture(name, this._textures[name]);
  27796. }
  27797. // Float
  27798. for (name in this._floats) {
  27799. this._effect.setFloat(name, this._floats[name]);
  27800. }
  27801. // Float s
  27802. for (name in this._floatsArrays) {
  27803. this._effect.setArray(name, this._floatsArrays[name]);
  27804. }
  27805. // Color3
  27806. for (name in this._colors3) {
  27807. this._effect.setColor3(name, this._colors3[name]);
  27808. }
  27809. // Color4
  27810. for (name in this._colors4) {
  27811. var color = this._colors4[name];
  27812. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27813. }
  27814. // Vector2
  27815. for (name in this._vectors2) {
  27816. this._effect.setVector2(name, this._vectors2[name]);
  27817. }
  27818. // Vector3
  27819. for (name in this._vectors3) {
  27820. this._effect.setVector3(name, this._vectors3[name]);
  27821. }
  27822. // Vector4
  27823. for (name in this._vectors4) {
  27824. this._effect.setVector4(name, this._vectors4[name]);
  27825. }
  27826. // Matrix
  27827. for (name in this._matrices) {
  27828. this._effect.setMatrix(name, this._matrices[name]);
  27829. }
  27830. // Matrix 3x3
  27831. for (name in this._matrices3x3) {
  27832. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27833. }
  27834. // Matrix 2x2
  27835. for (name in this._matrices2x2) {
  27836. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27837. }
  27838. }
  27839. _super.prototype.bind.call(this, world, mesh);
  27840. };
  27841. ShaderMaterial.prototype.clone = function (name) {
  27842. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27843. return newShaderMaterial;
  27844. };
  27845. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27846. for (var name in this._textures) {
  27847. this._textures[name].dispose();
  27848. }
  27849. this._textures = [];
  27850. _super.prototype.dispose.call(this, forceDisposeEffect);
  27851. };
  27852. return ShaderMaterial;
  27853. })(BABYLON.Material);
  27854. BABYLON.ShaderMaterial = ShaderMaterial;
  27855. })(BABYLON || (BABYLON = {}));
  27856. var BABYLON;
  27857. (function (BABYLON) {
  27858. var Internals;
  27859. (function (Internals) {
  27860. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27861. // All values and structures referenced from:
  27862. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27863. var DDS_MAGIC = 0x20534444;
  27864. 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;
  27865. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27866. 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;
  27867. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27868. function FourCCToInt32(value) {
  27869. return value.charCodeAt(0) +
  27870. (value.charCodeAt(1) << 8) +
  27871. (value.charCodeAt(2) << 16) +
  27872. (value.charCodeAt(3) << 24);
  27873. }
  27874. function Int32ToFourCC(value) {
  27875. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27876. }
  27877. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27878. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27879. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27880. var headerLengthInt = 31; // The header length in 32 bit ints
  27881. // Offsets into the header array
  27882. var off_magic = 0;
  27883. var off_size = 1;
  27884. var off_flags = 2;
  27885. var off_height = 3;
  27886. var off_width = 4;
  27887. var off_mipmapCount = 7;
  27888. var off_pfFlags = 20;
  27889. var off_pfFourCC = 21;
  27890. var off_RGBbpp = 22;
  27891. var off_RMask = 23;
  27892. var off_GMask = 24;
  27893. var off_BMask = 25;
  27894. var off_AMask = 26;
  27895. var off_caps1 = 27;
  27896. var off_caps2 = 28;
  27897. ;
  27898. var DDSTools = (function () {
  27899. function DDSTools() {
  27900. }
  27901. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27902. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27903. var mipmapCount = 1;
  27904. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27905. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27906. }
  27907. return {
  27908. width: header[off_width],
  27909. height: header[off_height],
  27910. mipmapCount: mipmapCount,
  27911. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27912. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27913. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27914. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27915. };
  27916. };
  27917. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27918. var byteArray = new Uint8Array(dataLength);
  27919. var srcData = new Uint8Array(arrayBuffer);
  27920. var index = 0;
  27921. for (var y = height - 1; y >= 0; y--) {
  27922. for (var x = 0; x < width; x++) {
  27923. var srcPos = dataOffset + (x + y * width) * 4;
  27924. byteArray[index + 2] = srcData[srcPos];
  27925. byteArray[index + 1] = srcData[srcPos + 1];
  27926. byteArray[index] = srcData[srcPos + 2];
  27927. byteArray[index + 3] = srcData[srcPos + 3];
  27928. index += 4;
  27929. }
  27930. }
  27931. return byteArray;
  27932. };
  27933. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27934. var byteArray = new Uint8Array(dataLength);
  27935. var srcData = new Uint8Array(arrayBuffer);
  27936. var index = 0;
  27937. for (var y = height - 1; y >= 0; y--) {
  27938. for (var x = 0; x < width; x++) {
  27939. var srcPos = dataOffset + (x + y * width) * 3;
  27940. byteArray[index + 2] = srcData[srcPos];
  27941. byteArray[index + 1] = srcData[srcPos + 1];
  27942. byteArray[index] = srcData[srcPos + 2];
  27943. index += 3;
  27944. }
  27945. }
  27946. return byteArray;
  27947. };
  27948. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27949. var byteArray = new Uint8Array(dataLength);
  27950. var srcData = new Uint8Array(arrayBuffer);
  27951. var index = 0;
  27952. for (var y = height - 1; y >= 0; y--) {
  27953. for (var x = 0; x < width; x++) {
  27954. var srcPos = dataOffset + (x + y * width);
  27955. byteArray[index] = srcData[srcPos];
  27956. index++;
  27957. }
  27958. }
  27959. return byteArray;
  27960. };
  27961. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27962. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27963. if (header[off_magic] != DDS_MAGIC) {
  27964. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27965. return;
  27966. }
  27967. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27968. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27969. return;
  27970. }
  27971. if (info.isFourCC) {
  27972. fourCC = header[off_pfFourCC];
  27973. switch (fourCC) {
  27974. case FOURCC_DXT1:
  27975. blockBytes = 8;
  27976. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27977. break;
  27978. case FOURCC_DXT3:
  27979. blockBytes = 16;
  27980. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27981. break;
  27982. case FOURCC_DXT5:
  27983. blockBytes = 16;
  27984. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27985. break;
  27986. default:
  27987. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27988. return;
  27989. }
  27990. }
  27991. mipmapCount = 1;
  27992. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27993. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27994. }
  27995. var bpp = header[off_RGBbpp];
  27996. for (var face = 0; face < faces; face++) {
  27997. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27998. width = header[off_width];
  27999. height = header[off_height];
  28000. dataOffset = header[off_size] + 4;
  28001. for (i = 0; i < mipmapCount; ++i) {
  28002. if (info.isRGB) {
  28003. if (bpp === 24) {
  28004. dataLength = width * height * 3;
  28005. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28006. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28007. }
  28008. else {
  28009. dataLength = width * height * 4;
  28010. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28011. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28012. }
  28013. }
  28014. else if (info.isLuminance) {
  28015. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28016. var unpaddedRowSize = width;
  28017. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28018. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28019. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28020. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28021. }
  28022. else {
  28023. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28024. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28025. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28026. }
  28027. dataOffset += dataLength;
  28028. width *= 0.5;
  28029. height *= 0.5;
  28030. width = Math.max(1.0, width);
  28031. height = Math.max(1.0, height);
  28032. }
  28033. }
  28034. };
  28035. return DDSTools;
  28036. })();
  28037. Internals.DDSTools = DDSTools;
  28038. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28039. })(BABYLON || (BABYLON = {}));
  28040. var BABYLON;
  28041. (function (BABYLON) {
  28042. var CannonJSPlugin = (function () {
  28043. function CannonJSPlugin() {
  28044. this._registeredMeshes = [];
  28045. this._physicsMaterials = [];
  28046. this.updateBodyPosition = function (mesh) {
  28047. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28048. var registeredMesh = this._registeredMeshes[index];
  28049. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28050. var body = registeredMesh.body;
  28051. var center = mesh.getBoundingInfo().boundingBox.center;
  28052. body.position.set(center.x, center.y, center.z);
  28053. body.quaternion.copy(mesh.rotationQuaternion);
  28054. if (registeredMesh.deltaRotation) {
  28055. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28056. body.quaternion = body.quaternion.mult(tmpQ);
  28057. }
  28058. if (registeredMesh.heightmap) {
  28059. //calculate the correct body position:
  28060. var rotationQuaternion = mesh.rotationQuaternion;
  28061. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28062. mesh.computeWorldMatrix(true);
  28063. //get original center with no rotation
  28064. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28065. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28066. //rotation is back
  28067. mesh.rotationQuaternion = rotationQuaternion;
  28068. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28069. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28070. mesh.setPivotMatrix(p);
  28071. mesh.computeWorldMatrix(true);
  28072. //calculate the translation
  28073. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28074. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28075. //add it inverted to the delta
  28076. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28077. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28078. mesh.setPivotMatrix(oldPivot);
  28079. mesh.computeWorldMatrix(true);
  28080. }
  28081. return;
  28082. }
  28083. }
  28084. };
  28085. }
  28086. CannonJSPlugin.prototype.initialize = function (iterations) {
  28087. if (iterations === void 0) { iterations = 10; }
  28088. this._world = new CANNON.World();
  28089. this._world.broadphase = new CANNON.NaiveBroadphase();
  28090. this._world.solver.iterations = iterations;
  28091. };
  28092. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28093. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28094. };
  28095. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28096. var _this = this;
  28097. this._world.step(delta);
  28098. this._registeredMeshes.forEach(function (registeredMesh) {
  28099. // Body position
  28100. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28101. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28102. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28103. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28104. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28105. if (registeredMesh.deltaRotation) {
  28106. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28107. }
  28108. //is the physics collision callback is set?
  28109. if (registeredMesh.mesh.onPhysicsCollide) {
  28110. if (!registeredMesh.collisionFunction) {
  28111. registeredMesh.collisionFunction = function (e) {
  28112. //find the mesh that collided with the registered mesh
  28113. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28114. if (_this._registeredMeshes[idx].body == e.body) {
  28115. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28116. }
  28117. }
  28118. };
  28119. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28120. }
  28121. }
  28122. else {
  28123. //unregister, in case the function was removed for some reason
  28124. if (registeredMesh.collisionFunction) {
  28125. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28126. }
  28127. }
  28128. });
  28129. };
  28130. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28131. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28132. };
  28133. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28134. this.unregisterMesh(mesh);
  28135. if (!mesh.rotationQuaternion) {
  28136. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28137. }
  28138. mesh.computeWorldMatrix(true);
  28139. var shape = this._createShape(mesh, impostor);
  28140. return this._createRigidBodyFromShape(shape, mesh, options);
  28141. };
  28142. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28143. //get the correct bounding box
  28144. var oldQuaternion = mesh.rotationQuaternion;
  28145. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28146. mesh.computeWorldMatrix(true);
  28147. var returnValue;
  28148. switch (impostor) {
  28149. case BABYLON.PhysicsEngine.SphereImpostor:
  28150. var bbox = mesh.getBoundingInfo().boundingBox;
  28151. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28152. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28153. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28154. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28155. break;
  28156. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28157. case BABYLON.PhysicsEngine.CylinderImpostor:
  28158. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28159. case BABYLON.PhysicsEngine.BoxImpostor:
  28160. bbox = mesh.getBoundingInfo().boundingBox;
  28161. var min = bbox.minimumWorld;
  28162. var max = bbox.maximumWorld;
  28163. var box = max.subtract(min).scale(0.5);
  28164. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28165. break;
  28166. case BABYLON.PhysicsEngine.PlaneImpostor:
  28167. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28168. returnValue = new CANNON.Plane();
  28169. break;
  28170. case BABYLON.PhysicsEngine.MeshImpostor:
  28171. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28172. var rawFaces = mesh.getIndices();
  28173. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28174. break;
  28175. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28176. returnValue = this._createHeightmap(mesh);
  28177. break;
  28178. }
  28179. mesh.rotationQuaternion = oldQuaternion;
  28180. return returnValue;
  28181. };
  28182. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28183. var verts = [], faces = [];
  28184. mesh.computeWorldMatrix(true);
  28185. //reuse this variable
  28186. var transformed = BABYLON.Vector3.Zero();
  28187. // Get vertices
  28188. for (var i = 0; i < rawVerts.length; i += 3) {
  28189. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28190. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28191. }
  28192. // Get faces
  28193. for (var j = 0; j < rawFaces.length; j += 3) {
  28194. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28195. }
  28196. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28197. return shape;
  28198. };
  28199. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28200. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28201. var matrix = [];
  28202. //For now pointDepth will not be used and will be automatically calculated.
  28203. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28204. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28205. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28206. var elementSize = dim * 2 / arraySize;
  28207. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28208. for (var i = 0; i < pos.length; i = i + 3) {
  28209. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28210. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28211. var y = pos[i + 1] + minY;
  28212. if (!matrix[x]) {
  28213. matrix[x] = [];
  28214. }
  28215. if (!matrix[x][z]) {
  28216. matrix[x][z] = y;
  28217. }
  28218. matrix[x][z] = Math.max(y, matrix[x][z]);
  28219. }
  28220. for (var x = 0; x <= arraySize; ++x) {
  28221. if (!matrix[x]) {
  28222. var loc = 1;
  28223. while (!matrix[(x + loc) % arraySize]) {
  28224. loc++;
  28225. }
  28226. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28227. }
  28228. for (var z = 0; z <= arraySize; ++z) {
  28229. if (!matrix[x][z]) {
  28230. var loc = 1;
  28231. var newValue;
  28232. while (newValue === undefined) {
  28233. newValue = matrix[x][(z + loc++) % arraySize];
  28234. }
  28235. matrix[x][z] = newValue;
  28236. }
  28237. }
  28238. }
  28239. var shape = new CANNON.Heightfield(matrix, {
  28240. elementSize: elementSize
  28241. });
  28242. //For future reference, needed for body transformation
  28243. shape.minY = minY;
  28244. return shape;
  28245. };
  28246. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28247. var index;
  28248. var mat;
  28249. for (index = 0; index < this._physicsMaterials.length; index++) {
  28250. mat = this._physicsMaterials[index];
  28251. if (mat.friction === friction && mat.restitution === restitution) {
  28252. return mat;
  28253. }
  28254. }
  28255. var currentMat = new CANNON.Material("mat");
  28256. this._physicsMaterials.push(currentMat);
  28257. for (index = 0; index < this._physicsMaterials.length; index++) {
  28258. mat = this._physicsMaterials[index];
  28259. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28260. this._world.addContactMaterial(contactMaterial);
  28261. }
  28262. return currentMat;
  28263. };
  28264. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28265. if (!mesh.rotationQuaternion) {
  28266. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28267. }
  28268. // The delta between the mesh position and the mesh bounding box center
  28269. var bbox = mesh.getBoundingInfo().boundingBox;
  28270. var deltaPosition = mesh.position.subtract(bbox.center);
  28271. var deltaRotation;
  28272. var material = this._addMaterial(options.friction, options.restitution);
  28273. var body = new CANNON.Body({
  28274. mass: options.mass,
  28275. material: material,
  28276. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28277. });
  28278. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28279. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28280. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28281. //-90 DEG in X, precalculated
  28282. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28283. body.quaternion = body.quaternion.mult(tmpQ);
  28284. //Invert! (Precalculated, 90 deg in X)
  28285. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28286. }
  28287. //If it is a heightfield, if should be centered.
  28288. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28289. //calculate the correct body position:
  28290. var rotationQuaternion = mesh.rotationQuaternion;
  28291. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28292. mesh.computeWorldMatrix(true);
  28293. //get original center with no rotation
  28294. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28295. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28296. //rotation is back
  28297. mesh.rotationQuaternion = rotationQuaternion;
  28298. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28299. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28300. mesh.setPivotMatrix(p);
  28301. mesh.computeWorldMatrix(true);
  28302. //calculate the translation
  28303. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28304. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28305. //add it inverted to the delta
  28306. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28307. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28308. mesh.setPivotMatrix(oldPivot);
  28309. mesh.computeWorldMatrix(true);
  28310. }
  28311. //add the shape
  28312. body.addShape(shape);
  28313. this._world.add(body);
  28314. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28315. return body;
  28316. };
  28317. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28318. var initialMesh = parts[0].mesh;
  28319. this.unregisterMesh(initialMesh);
  28320. initialMesh.computeWorldMatrix(true);
  28321. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28322. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28323. for (var index = 1; index < parts.length; index++) {
  28324. var mesh = parts[index].mesh;
  28325. mesh.computeWorldMatrix(true);
  28326. var shape = this._createShape(mesh, parts[index].impostor);
  28327. var localPosition = mesh.position;
  28328. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28329. }
  28330. return body;
  28331. };
  28332. CannonJSPlugin.prototype._unbindBody = function (body) {
  28333. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28334. var registeredMesh = this._registeredMeshes[index];
  28335. if (registeredMesh.body === body) {
  28336. this._world.remove(registeredMesh.body);
  28337. registeredMesh.body = null;
  28338. registeredMesh.delta = null;
  28339. registeredMesh.deltaRotation = null;
  28340. }
  28341. }
  28342. };
  28343. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28344. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28345. var registeredMesh = this._registeredMeshes[index];
  28346. if (registeredMesh.mesh === mesh) {
  28347. // Remove body
  28348. if (registeredMesh.body) {
  28349. this._unbindBody(registeredMesh.body);
  28350. }
  28351. this._registeredMeshes.splice(index, 1);
  28352. return;
  28353. }
  28354. }
  28355. };
  28356. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28357. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28358. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28359. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28360. var registeredMesh = this._registeredMeshes[index];
  28361. if (registeredMesh.mesh === mesh) {
  28362. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28363. return;
  28364. }
  28365. }
  28366. };
  28367. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28368. var body1 = null, body2 = null;
  28369. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28370. var registeredMesh = this._registeredMeshes[index];
  28371. if (registeredMesh.mesh === mesh1) {
  28372. body1 = registeredMesh.body;
  28373. }
  28374. else if (registeredMesh.mesh === mesh2) {
  28375. body2 = registeredMesh.body;
  28376. }
  28377. }
  28378. if (!body1 || !body2) {
  28379. return false;
  28380. }
  28381. 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));
  28382. this._world.addConstraint(constraint);
  28383. return true;
  28384. };
  28385. CannonJSPlugin.prototype.dispose = function () {
  28386. while (this._registeredMeshes.length) {
  28387. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28388. }
  28389. };
  28390. CannonJSPlugin.prototype.isSupported = function () {
  28391. return window.CANNON !== undefined;
  28392. };
  28393. CannonJSPlugin.prototype.getWorldObject = function () {
  28394. return this._world;
  28395. };
  28396. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28397. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28398. var registeredMesh = this._registeredMeshes[index];
  28399. if (registeredMesh.mesh === mesh) {
  28400. return registeredMesh.body;
  28401. }
  28402. }
  28403. return null;
  28404. };
  28405. return CannonJSPlugin;
  28406. })();
  28407. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28408. })(BABYLON || (BABYLON = {}));
  28409. var BABYLON;
  28410. (function (BABYLON) {
  28411. var OimoJSPlugin = (function () {
  28412. function OimoJSPlugin() {
  28413. this._registeredMeshes = [];
  28414. /**
  28415. * Update the body position according to the mesh position
  28416. * @param mesh
  28417. */
  28418. this.updateBodyPosition = function (mesh) {
  28419. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28420. var registeredMesh = this._registeredMeshes[index];
  28421. var body = registeredMesh.body.body;
  28422. var updated = false;
  28423. var newPosition;
  28424. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28425. mesh.computeWorldMatrix(true);
  28426. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28427. updated = true;
  28428. }
  28429. else if (registeredMesh.mesh.parent === mesh) {
  28430. mesh.computeWorldMatrix(true);
  28431. registeredMesh.mesh.computeWorldMatrix(true);
  28432. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28433. updated = true;
  28434. }
  28435. if (updated) {
  28436. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28437. body.setQuaternion(mesh.rotationQuaternion);
  28438. body.sleeping = false;
  28439. //force Oimo to update the body's position
  28440. body.updatePosition(1);
  28441. }
  28442. }
  28443. };
  28444. }
  28445. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28446. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28447. };
  28448. OimoJSPlugin.prototype.initialize = function (iterations) {
  28449. this._world = new OIMO.World(null, null, iterations);
  28450. this._world.clear();
  28451. };
  28452. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28453. this._world.gravity = gravity;
  28454. };
  28455. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28456. this.unregisterMesh(mesh);
  28457. if (!mesh.rotationQuaternion) {
  28458. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28459. }
  28460. mesh.computeWorldMatrix(true);
  28461. var bbox = mesh.getBoundingInfo().boundingBox;
  28462. // The delta between the mesh position and the mesh bounding box center
  28463. var deltaPosition = mesh.position.subtract(bbox.center);
  28464. //calculate rotation to fit Oimo's needs (Euler...)
  28465. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28466. //get the correct bounding box
  28467. var oldQuaternion = mesh.rotationQuaternion;
  28468. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28469. mesh.computeWorldMatrix(true);
  28470. var bodyConfig = {
  28471. name: mesh.uniqueId,
  28472. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28473. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28474. move: options.mass != 0,
  28475. config: [options.mass, options.friction, options.restitution],
  28476. world: this._world
  28477. };
  28478. // register mesh
  28479. switch (impostor) {
  28480. case BABYLON.PhysicsEngine.SphereImpostor:
  28481. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28482. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28483. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28484. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28485. bodyConfig.type = 'sphere';
  28486. bodyConfig.size = [size];
  28487. break;
  28488. case BABYLON.PhysicsEngine.PlaneImpostor:
  28489. //Oimo "fakes" a cylinder as a box, so why don't we!
  28490. case BABYLON.PhysicsEngine.CylinderImpostor:
  28491. case BABYLON.PhysicsEngine.BoxImpostor:
  28492. var min = bbox.minimumWorld;
  28493. var max = bbox.maximumWorld;
  28494. var box = max.subtract(min);
  28495. var sizeX = this._checkWithEpsilon(box.x);
  28496. var sizeY = this._checkWithEpsilon(box.y);
  28497. var sizeZ = this._checkWithEpsilon(box.z);
  28498. bodyConfig.type = 'box';
  28499. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28500. break;
  28501. }
  28502. var body = new OIMO.Body(bodyConfig);
  28503. //We have to access the rigid body's properties to set the quaternion.
  28504. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28505. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28506. //TEST
  28507. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28508. //update the internal rotation matrix
  28509. //body.body.syncShapes();
  28510. this._registeredMeshes.push({
  28511. mesh: mesh,
  28512. body: body,
  28513. delta: deltaPosition
  28514. });
  28515. //for the sake of consistency.
  28516. mesh.rotationQuaternion = oldQuaternion;
  28517. return body;
  28518. };
  28519. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28520. var types = [], sizes = [], positions = [], rotations = [];
  28521. var initialMesh = parts[0].mesh;
  28522. for (var index = 0; index < parts.length; index++) {
  28523. var part = parts[index];
  28524. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28525. types.push(bodyParameters.type);
  28526. sizes.push.apply(sizes, bodyParameters.size);
  28527. positions.push.apply(positions, bodyParameters.pos);
  28528. rotations.push.apply(rotations, bodyParameters.rot);
  28529. }
  28530. var body = new OIMO.Body({
  28531. name: initialMesh.uniqueId,
  28532. type: types,
  28533. size: sizes,
  28534. pos: positions,
  28535. rot: rotations,
  28536. move: options.mass != 0,
  28537. config: [options.mass, options.friction, options.restitution],
  28538. world: this._world
  28539. });
  28540. //Reset the body's rotation to be of the initial mesh's.
  28541. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28542. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28543. this._registeredMeshes.push({
  28544. mesh: initialMesh,
  28545. body: body
  28546. });
  28547. return body;
  28548. };
  28549. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28550. var mesh = part.mesh;
  28551. if (!mesh.rotationQuaternion) {
  28552. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28553. }
  28554. // We need the bounding box/sphere info to compute the physics body
  28555. mesh.computeWorldMatrix(true);
  28556. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28557. var bodyParameters = {
  28558. name: mesh.uniqueId,
  28559. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28560. //A bug in Oimo (Body class) prevents us from using rot directly.
  28561. rot: [0, 0, 0],
  28562. //For future reference, if the bug will ever be fixed.
  28563. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28564. };
  28565. var oldQuaternion = mesh.rotationQuaternion;
  28566. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28567. mesh.computeWorldMatrix(true);
  28568. switch (part.impostor) {
  28569. case BABYLON.PhysicsEngine.SphereImpostor:
  28570. var bbox = mesh.getBoundingInfo().boundingBox;
  28571. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28572. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28573. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28574. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28575. bodyParameters.type = 'sphere';
  28576. bodyParameters.size = [size, size, size];
  28577. break;
  28578. case BABYLON.PhysicsEngine.PlaneImpostor:
  28579. case BABYLON.PhysicsEngine.CylinderImpostor:
  28580. case BABYLON.PhysicsEngine.BoxImpostor:
  28581. bbox = mesh.getBoundingInfo().boundingBox;
  28582. var min = bbox.minimumWorld;
  28583. var max = bbox.maximumWorld;
  28584. var box = max.subtract(min);
  28585. var sizeX = this._checkWithEpsilon(box.x);
  28586. var sizeY = this._checkWithEpsilon(box.y);
  28587. var sizeZ = this._checkWithEpsilon(box.z);
  28588. bodyParameters.type = 'box';
  28589. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28590. break;
  28591. }
  28592. mesh.rotationQuaternion = oldQuaternion;
  28593. return bodyParameters;
  28594. };
  28595. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28596. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28597. var registeredMesh = this._registeredMeshes[index];
  28598. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28599. if (registeredMesh.body) {
  28600. this._world.removeRigidBody(registeredMesh.body.body);
  28601. this._unbindBody(registeredMesh.body);
  28602. }
  28603. this._registeredMeshes.splice(index, 1);
  28604. return;
  28605. }
  28606. }
  28607. };
  28608. OimoJSPlugin.prototype._unbindBody = function (body) {
  28609. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28610. var registeredMesh = this._registeredMeshes[index];
  28611. if (registeredMesh.body === body) {
  28612. registeredMesh.body = null;
  28613. }
  28614. }
  28615. };
  28616. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28617. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28618. var registeredMesh = this._registeredMeshes[index];
  28619. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28620. // Get object mass to have a behaviour similar to cannon.js
  28621. var mass = registeredMesh.body.body.massInfo.mass;
  28622. // The force is scaled with the mass of object
  28623. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28624. return;
  28625. }
  28626. }
  28627. };
  28628. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28629. var body1 = null, body2 = null;
  28630. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28631. var registeredMesh = this._registeredMeshes[index];
  28632. if (registeredMesh.mesh === mesh1) {
  28633. body1 = registeredMesh.body.body;
  28634. }
  28635. else if (registeredMesh.mesh === mesh2) {
  28636. body2 = registeredMesh.body.body;
  28637. }
  28638. }
  28639. if (!body1 || !body2) {
  28640. return false;
  28641. }
  28642. if (!options) {
  28643. options = {};
  28644. }
  28645. new OIMO.Link({
  28646. type: options.type,
  28647. body1: body1,
  28648. body2: body2,
  28649. min: options.min,
  28650. max: options.max,
  28651. axe1: options.axe1,
  28652. axe2: options.axe2,
  28653. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28654. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28655. collision: options.collision,
  28656. spring: options.spring,
  28657. world: this._world
  28658. });
  28659. return true;
  28660. };
  28661. OimoJSPlugin.prototype.dispose = function () {
  28662. this._world.clear();
  28663. while (this._registeredMeshes.length) {
  28664. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28665. }
  28666. };
  28667. OimoJSPlugin.prototype.isSupported = function () {
  28668. return OIMO !== undefined;
  28669. };
  28670. OimoJSPlugin.prototype.getWorldObject = function () {
  28671. return this._world;
  28672. };
  28673. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28674. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28675. var registeredMesh = this._registeredMeshes[index];
  28676. if (registeredMesh.mesh === mesh) {
  28677. return registeredMesh.body;
  28678. }
  28679. }
  28680. return null;
  28681. };
  28682. OimoJSPlugin.prototype._getLastShape = function (body) {
  28683. var lastShape = body.shapes;
  28684. while (lastShape.next) {
  28685. lastShape = lastShape.next;
  28686. }
  28687. return lastShape;
  28688. };
  28689. OimoJSPlugin.prototype.runOneStep = function (time) {
  28690. this._world.step();
  28691. // Update the position of all registered meshes
  28692. var i = this._registeredMeshes.length;
  28693. var m;
  28694. while (i--) {
  28695. var body = this._registeredMeshes[i].body.body;
  28696. var mesh = this._registeredMeshes[i].mesh;
  28697. if (!this._registeredMeshes[i].delta) {
  28698. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28699. }
  28700. if (!body.sleeping) {
  28701. //TODO check that
  28702. if (body.shapes.next) {
  28703. var parentShape = this._getLastShape(body);
  28704. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28705. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28706. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28707. }
  28708. else {
  28709. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28710. }
  28711. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28712. mesh.computeWorldMatrix();
  28713. }
  28714. //check if the collide callback is set.
  28715. if (mesh.onPhysicsCollide) {
  28716. var meshUniqueName = mesh.uniqueId;
  28717. var contact = this._world.contacts;
  28718. while (contact !== null) {
  28719. //is this body colliding with any other?
  28720. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  28721. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  28722. //get the mesh and execute the callback
  28723. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  28724. if (otherMesh)
  28725. mesh.onPhysicsCollide(otherMesh);
  28726. }
  28727. contact = contact.next;
  28728. }
  28729. }
  28730. }
  28731. };
  28732. return OimoJSPlugin;
  28733. })();
  28734. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28735. })(BABYLON || (BABYLON = {}));
  28736. var BABYLON;
  28737. (function (BABYLON) {
  28738. var DisplayPassPostProcess = (function (_super) {
  28739. __extends(DisplayPassPostProcess, _super);
  28740. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28741. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28742. }
  28743. return DisplayPassPostProcess;
  28744. })(BABYLON.PostProcess);
  28745. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28746. })(BABYLON || (BABYLON = {}));
  28747. var BABYLON;
  28748. (function (BABYLON) {
  28749. var SimplificationSettings = (function () {
  28750. function SimplificationSettings(quality, distance, optimizeMesh) {
  28751. this.quality = quality;
  28752. this.distance = distance;
  28753. this.optimizeMesh = optimizeMesh;
  28754. }
  28755. return SimplificationSettings;
  28756. })();
  28757. BABYLON.SimplificationSettings = SimplificationSettings;
  28758. var SimplificationQueue = (function () {
  28759. function SimplificationQueue() {
  28760. this.running = false;
  28761. this._simplificationArray = [];
  28762. }
  28763. SimplificationQueue.prototype.addTask = function (task) {
  28764. this._simplificationArray.push(task);
  28765. };
  28766. SimplificationQueue.prototype.executeNext = function () {
  28767. var task = this._simplificationArray.pop();
  28768. if (task) {
  28769. this.running = true;
  28770. this.runSimplification(task);
  28771. }
  28772. else {
  28773. this.running = false;
  28774. }
  28775. };
  28776. SimplificationQueue.prototype.runSimplification = function (task) {
  28777. var _this = this;
  28778. if (task.parallelProcessing) {
  28779. //parallel simplifier
  28780. task.settings.forEach(function (setting) {
  28781. var simplifier = _this.getSimplifier(task);
  28782. simplifier.simplify(setting, function (newMesh) {
  28783. task.mesh.addLODLevel(setting.distance, newMesh);
  28784. newMesh.isVisible = true;
  28785. //check if it is the last
  28786. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28787. //all done, run the success callback.
  28788. task.successCallback();
  28789. }
  28790. _this.executeNext();
  28791. });
  28792. });
  28793. }
  28794. else {
  28795. //single simplifier.
  28796. var simplifier = this.getSimplifier(task);
  28797. var runDecimation = function (setting, callback) {
  28798. simplifier.simplify(setting, function (newMesh) {
  28799. task.mesh.addLODLevel(setting.distance, newMesh);
  28800. newMesh.isVisible = true;
  28801. //run the next quality level
  28802. callback();
  28803. });
  28804. };
  28805. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28806. runDecimation(task.settings[loop.index], function () {
  28807. loop.executeNext();
  28808. });
  28809. }, function () {
  28810. //execution ended, run the success callback.
  28811. if (task.successCallback) {
  28812. task.successCallback();
  28813. }
  28814. _this.executeNext();
  28815. });
  28816. }
  28817. };
  28818. SimplificationQueue.prototype.getSimplifier = function (task) {
  28819. switch (task.simplificationType) {
  28820. case SimplificationType.QUADRATIC:
  28821. default:
  28822. return new QuadraticErrorSimplification(task.mesh);
  28823. }
  28824. };
  28825. return SimplificationQueue;
  28826. })();
  28827. BABYLON.SimplificationQueue = SimplificationQueue;
  28828. /**
  28829. * The implemented types of simplification.
  28830. * At the moment only Quadratic Error Decimation is implemented.
  28831. */
  28832. (function (SimplificationType) {
  28833. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28834. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28835. var SimplificationType = BABYLON.SimplificationType;
  28836. var DecimationTriangle = (function () {
  28837. function DecimationTriangle(vertices) {
  28838. this.vertices = vertices;
  28839. this.error = new Array(4);
  28840. this.deleted = false;
  28841. this.isDirty = false;
  28842. this.deletePending = false;
  28843. this.borderFactor = 0;
  28844. }
  28845. return DecimationTriangle;
  28846. })();
  28847. BABYLON.DecimationTriangle = DecimationTriangle;
  28848. var DecimationVertex = (function () {
  28849. function DecimationVertex(position, id) {
  28850. this.position = position;
  28851. this.id = id;
  28852. this.isBorder = true;
  28853. this.q = new QuadraticMatrix();
  28854. this.triangleCount = 0;
  28855. this.triangleStart = 0;
  28856. this.originalOffsets = [];
  28857. }
  28858. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28859. this.position.copyFrom(newPosition);
  28860. };
  28861. return DecimationVertex;
  28862. })();
  28863. BABYLON.DecimationVertex = DecimationVertex;
  28864. var QuadraticMatrix = (function () {
  28865. function QuadraticMatrix(data) {
  28866. this.data = new Array(10);
  28867. for (var i = 0; i < 10; ++i) {
  28868. if (data && data[i]) {
  28869. this.data[i] = data[i];
  28870. }
  28871. else {
  28872. this.data[i] = 0;
  28873. }
  28874. }
  28875. }
  28876. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28877. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28878. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28879. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28880. return det;
  28881. };
  28882. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28883. for (var i = 0; i < 10; ++i) {
  28884. this.data[i] += matrix.data[i];
  28885. }
  28886. };
  28887. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28888. for (var i = 0; i < 10; ++i) {
  28889. this.data[i] += data[i];
  28890. }
  28891. };
  28892. QuadraticMatrix.prototype.add = function (matrix) {
  28893. var m = new QuadraticMatrix();
  28894. for (var i = 0; i < 10; ++i) {
  28895. m.data[i] = this.data[i] + matrix.data[i];
  28896. }
  28897. return m;
  28898. };
  28899. QuadraticMatrix.FromData = function (a, b, c, d) {
  28900. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28901. };
  28902. //returning an array to avoid garbage collection
  28903. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28904. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28905. };
  28906. return QuadraticMatrix;
  28907. })();
  28908. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28909. var Reference = (function () {
  28910. function Reference(vertexId, triangleId) {
  28911. this.vertexId = vertexId;
  28912. this.triangleId = triangleId;
  28913. }
  28914. return Reference;
  28915. })();
  28916. BABYLON.Reference = Reference;
  28917. /**
  28918. * An implementation of the Quadratic Error simplification algorithm.
  28919. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28920. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28921. * @author RaananW
  28922. */
  28923. var QuadraticErrorSimplification = (function () {
  28924. function QuadraticErrorSimplification(_mesh) {
  28925. this._mesh = _mesh;
  28926. this.initialized = false;
  28927. this.syncIterations = 5000;
  28928. this.aggressiveness = 7;
  28929. this.decimationIterations = 100;
  28930. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28931. }
  28932. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28933. var _this = this;
  28934. this.initDecimatedMesh();
  28935. //iterating through the submeshes array, one after the other.
  28936. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28937. _this.initWithMesh(loop.index, function () {
  28938. _this.runDecimation(settings, loop.index, function () {
  28939. loop.executeNext();
  28940. });
  28941. }, settings.optimizeMesh);
  28942. }, function () {
  28943. setTimeout(function () {
  28944. successCallback(_this._reconstructedMesh);
  28945. }, 0);
  28946. });
  28947. };
  28948. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28949. var _this = this;
  28950. var gCount = 0;
  28951. triangle.vertices.forEach(function (vertex) {
  28952. var count = 0;
  28953. var vPos = vertex.position;
  28954. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28955. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28956. ++count;
  28957. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28958. ++count;
  28959. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28960. ++count;
  28961. if (count > 1) {
  28962. ++gCount;
  28963. }
  28964. ;
  28965. });
  28966. if (gCount > 1) {
  28967. console.log(triangle, gCount);
  28968. }
  28969. return gCount > 1;
  28970. };
  28971. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28972. var _this = this;
  28973. var targetCount = ~~(this.triangles.length * settings.quality);
  28974. var deletedTriangles = 0;
  28975. var triangleCount = this.triangles.length;
  28976. var iterationFunction = function (iteration, callback) {
  28977. setTimeout(function () {
  28978. if (iteration % 5 === 0) {
  28979. _this.updateMesh(iteration === 0);
  28980. }
  28981. for (var i = 0; i < _this.triangles.length; ++i) {
  28982. _this.triangles[i].isDirty = false;
  28983. }
  28984. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28985. var trianglesIterator = function (i) {
  28986. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28987. var t = _this.triangles[tIdx];
  28988. if (!t)
  28989. return;
  28990. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28991. return;
  28992. }
  28993. for (var j = 0; j < 3; ++j) {
  28994. if (t.error[j] < threshold) {
  28995. var deleted0 = [];
  28996. var deleted1 = [];
  28997. var v0 = t.vertices[j];
  28998. var v1 = t.vertices[(j + 1) % 3];
  28999. if (v0.isBorder !== v1.isBorder)
  29000. continue;
  29001. var p = BABYLON.Vector3.Zero();
  29002. var n = BABYLON.Vector3.Zero();
  29003. var uv = BABYLON.Vector2.Zero();
  29004. var color = new BABYLON.Color4(0, 0, 0, 1);
  29005. _this.calculateError(v0, v1, p, n, uv, color);
  29006. var delTr = [];
  29007. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29008. continue;
  29009. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29010. continue;
  29011. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29012. continue;
  29013. var uniqueArray = [];
  29014. delTr.forEach(function (deletedT) {
  29015. if (uniqueArray.indexOf(deletedT) === -1) {
  29016. deletedT.deletePending = true;
  29017. uniqueArray.push(deletedT);
  29018. }
  29019. });
  29020. if (uniqueArray.length % 2 !== 0) {
  29021. continue;
  29022. }
  29023. v0.q = v1.q.add(v0.q);
  29024. v0.updatePosition(p);
  29025. var tStart = _this.references.length;
  29026. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29027. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29028. var tCount = _this.references.length - tStart;
  29029. if (tCount <= v0.triangleCount) {
  29030. if (tCount) {
  29031. for (var c = 0; c < tCount; c++) {
  29032. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29033. }
  29034. }
  29035. }
  29036. else {
  29037. v0.triangleStart = tStart;
  29038. }
  29039. v0.triangleCount = tCount;
  29040. break;
  29041. }
  29042. }
  29043. };
  29044. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29045. }, 0);
  29046. };
  29047. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29048. if (triangleCount - deletedTriangles <= targetCount)
  29049. loop.breakLoop();
  29050. else {
  29051. iterationFunction(loop.index, function () {
  29052. loop.executeNext();
  29053. });
  29054. }
  29055. }, function () {
  29056. setTimeout(function () {
  29057. //reconstruct this part of the mesh
  29058. _this.reconstructMesh(submeshIndex);
  29059. successCallback();
  29060. }, 0);
  29061. });
  29062. };
  29063. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29064. var _this = this;
  29065. this.vertices = [];
  29066. this.triangles = [];
  29067. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29068. var indices = this._mesh.getIndices();
  29069. var submesh = this._mesh.subMeshes[submeshIndex];
  29070. var findInVertices = function (positionToSearch) {
  29071. if (optimizeMesh) {
  29072. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29073. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29074. return _this.vertices[ii];
  29075. }
  29076. }
  29077. }
  29078. return null;
  29079. };
  29080. var vertexReferences = [];
  29081. var vertexInit = function (i) {
  29082. var offset = i + submesh.verticesStart;
  29083. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29084. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29085. vertex.originalOffsets.push(offset);
  29086. if (vertex.id === _this.vertices.length) {
  29087. _this.vertices.push(vertex);
  29088. }
  29089. vertexReferences.push(vertex.id);
  29090. };
  29091. //var totalVertices = mesh.getTotalVertices();
  29092. var totalVertices = submesh.verticesCount;
  29093. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29094. var indicesInit = function (i) {
  29095. var offset = (submesh.indexStart / 3) + i;
  29096. var pos = (offset * 3);
  29097. var i0 = indices[pos + 0];
  29098. var i1 = indices[pos + 1];
  29099. var i2 = indices[pos + 2];
  29100. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29101. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29102. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29103. var triangle = new DecimationTriangle([v0, v1, v2]);
  29104. triangle.originalOffset = pos;
  29105. _this.triangles.push(triangle);
  29106. };
  29107. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29108. _this.init(callback);
  29109. });
  29110. });
  29111. };
  29112. QuadraticErrorSimplification.prototype.init = function (callback) {
  29113. var _this = this;
  29114. var triangleInit1 = function (i) {
  29115. var t = _this.triangles[i];
  29116. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29117. for (var j = 0; j < 3; j++) {
  29118. 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))));
  29119. }
  29120. };
  29121. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29122. var triangleInit2 = function (i) {
  29123. var t = _this.triangles[i];
  29124. for (var j = 0; j < 3; ++j) {
  29125. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29126. }
  29127. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29128. };
  29129. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29130. _this.initialized = true;
  29131. callback();
  29132. });
  29133. });
  29134. };
  29135. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29136. var newTriangles = [];
  29137. var i;
  29138. for (i = 0; i < this.vertices.length; ++i) {
  29139. this.vertices[i].triangleCount = 0;
  29140. }
  29141. var t;
  29142. var j;
  29143. for (i = 0; i < this.triangles.length; ++i) {
  29144. if (!this.triangles[i].deleted) {
  29145. t = this.triangles[i];
  29146. for (j = 0; j < 3; ++j) {
  29147. t.vertices[j].triangleCount = 1;
  29148. }
  29149. newTriangles.push(t);
  29150. }
  29151. }
  29152. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29153. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29154. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29155. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29156. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29157. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29158. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29159. var vertexCount = 0;
  29160. for (i = 0; i < this.vertices.length; ++i) {
  29161. var vertex = this.vertices[i];
  29162. vertex.id = vertexCount;
  29163. if (vertex.triangleCount) {
  29164. vertex.originalOffsets.forEach(function (originalOffset) {
  29165. newPositionData.push(vertex.position.x);
  29166. newPositionData.push(vertex.position.y);
  29167. newPositionData.push(vertex.position.z);
  29168. newNormalData.push(normalData[originalOffset * 3]);
  29169. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29170. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29171. if (uvs && uvs.length) {
  29172. newUVsData.push(uvs[(originalOffset * 2)]);
  29173. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29174. }
  29175. else if (colorsData && colorsData.length) {
  29176. newColorsData.push(colorsData[(originalOffset * 4)]);
  29177. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29178. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29179. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29180. }
  29181. ++vertexCount;
  29182. });
  29183. }
  29184. }
  29185. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29186. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29187. var submeshesArray = this._reconstructedMesh.subMeshes;
  29188. this._reconstructedMesh.subMeshes = [];
  29189. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29190. var originalIndices = this._mesh.getIndices();
  29191. for (i = 0; i < newTriangles.length; ++i) {
  29192. t = newTriangles[i]; //now get the new referencing point for each vertex
  29193. [0, 1, 2].forEach(function (idx) {
  29194. var id = originalIndices[t.originalOffset + idx];
  29195. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29196. if (offset < 0)
  29197. offset = 0;
  29198. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29199. });
  29200. }
  29201. //overwriting the old vertex buffers and indices.
  29202. this._reconstructedMesh.setIndices(newIndicesArray);
  29203. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29204. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29205. if (newUVsData.length > 0)
  29206. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29207. if (newColorsData.length > 0)
  29208. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29209. //create submesh
  29210. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29211. if (submeshIndex > 0) {
  29212. this._reconstructedMesh.subMeshes = [];
  29213. submeshesArray.forEach(function (submesh) {
  29214. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29215. });
  29216. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29217. }
  29218. };
  29219. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29220. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29221. this._reconstructedMesh.material = this._mesh.material;
  29222. this._reconstructedMesh.parent = this._mesh.parent;
  29223. this._reconstructedMesh.isVisible = false;
  29224. };
  29225. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29226. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29227. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29228. if (t.deleted)
  29229. continue;
  29230. var s = this.references[vertex1.triangleStart + i].vertexId;
  29231. var v1 = t.vertices[(s + 1) % 3];
  29232. var v2 = t.vertices[(s + 2) % 3];
  29233. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29234. deletedArray[i] = true;
  29235. delTr.push(t);
  29236. continue;
  29237. }
  29238. var d1 = v1.position.subtract(point);
  29239. d1 = d1.normalize();
  29240. var d2 = v2.position.subtract(point);
  29241. d2 = d2.normalize();
  29242. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29243. return true;
  29244. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29245. deletedArray[i] = false;
  29246. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29247. return true;
  29248. }
  29249. return false;
  29250. };
  29251. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29252. var newDeleted = deletedTriangles;
  29253. for (var i = 0; i < vertex.triangleCount; ++i) {
  29254. var ref = this.references[vertex.triangleStart + i];
  29255. var t = this.triangles[ref.triangleId];
  29256. if (t.deleted)
  29257. continue;
  29258. if (deletedArray[i] && t.deletePending) {
  29259. t.deleted = true;
  29260. newDeleted++;
  29261. continue;
  29262. }
  29263. t.vertices[ref.vertexId] = origVertex;
  29264. t.isDirty = true;
  29265. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29266. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29267. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29268. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29269. this.references.push(ref);
  29270. }
  29271. return newDeleted;
  29272. };
  29273. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29274. for (var i = 0; i < this.vertices.length; ++i) {
  29275. var vCount = [];
  29276. var vId = [];
  29277. var v = this.vertices[i];
  29278. var j;
  29279. for (j = 0; j < v.triangleCount; ++j) {
  29280. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29281. for (var ii = 0; ii < 3; ii++) {
  29282. var ofs = 0;
  29283. var vv = triangle.vertices[ii];
  29284. while (ofs < vCount.length) {
  29285. if (vId[ofs] === vv.id)
  29286. break;
  29287. ++ofs;
  29288. }
  29289. if (ofs === vCount.length) {
  29290. vCount.push(1);
  29291. vId.push(vv.id);
  29292. }
  29293. else {
  29294. vCount[ofs]++;
  29295. }
  29296. }
  29297. }
  29298. for (j = 0; j < vCount.length; ++j) {
  29299. if (vCount[j] === 1) {
  29300. this.vertices[vId[j]].isBorder = true;
  29301. }
  29302. else {
  29303. this.vertices[vId[j]].isBorder = false;
  29304. }
  29305. }
  29306. }
  29307. };
  29308. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29309. if (identifyBorders === void 0) { identifyBorders = false; }
  29310. var i;
  29311. if (!identifyBorders) {
  29312. var newTrianglesVector = [];
  29313. for (i = 0; i < this.triangles.length; ++i) {
  29314. if (!this.triangles[i].deleted) {
  29315. newTrianglesVector.push(this.triangles[i]);
  29316. }
  29317. }
  29318. this.triangles = newTrianglesVector;
  29319. }
  29320. for (i = 0; i < this.vertices.length; ++i) {
  29321. this.vertices[i].triangleCount = 0;
  29322. this.vertices[i].triangleStart = 0;
  29323. }
  29324. var t;
  29325. var j;
  29326. var v;
  29327. for (i = 0; i < this.triangles.length; ++i) {
  29328. t = this.triangles[i];
  29329. for (j = 0; j < 3; ++j) {
  29330. v = t.vertices[j];
  29331. v.triangleCount++;
  29332. }
  29333. }
  29334. var tStart = 0;
  29335. for (i = 0; i < this.vertices.length; ++i) {
  29336. this.vertices[i].triangleStart = tStart;
  29337. tStart += this.vertices[i].triangleCount;
  29338. this.vertices[i].triangleCount = 0;
  29339. }
  29340. var newReferences = new Array(this.triangles.length * 3);
  29341. for (i = 0; i < this.triangles.length; ++i) {
  29342. t = this.triangles[i];
  29343. for (j = 0; j < 3; ++j) {
  29344. v = t.vertices[j];
  29345. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29346. v.triangleCount++;
  29347. }
  29348. }
  29349. this.references = newReferences;
  29350. if (identifyBorders) {
  29351. this.identifyBorder();
  29352. }
  29353. };
  29354. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29355. var x = point.x;
  29356. var y = point.y;
  29357. var z = point.z;
  29358. 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
  29359. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29360. };
  29361. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29362. var q = vertex1.q.add(vertex2.q);
  29363. var border = vertex1.isBorder && vertex2.isBorder;
  29364. var error = 0;
  29365. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29366. if (qDet !== 0 && !border) {
  29367. if (!pointResult) {
  29368. pointResult = BABYLON.Vector3.Zero();
  29369. }
  29370. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29371. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29372. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29373. error = this.vertexError(q, pointResult);
  29374. }
  29375. else {
  29376. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29377. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29378. var error1 = this.vertexError(q, vertex1.position);
  29379. var error2 = this.vertexError(q, vertex2.position);
  29380. var error3 = this.vertexError(q, p3);
  29381. error = Math.min(error1, error2, error3);
  29382. if (error === error1) {
  29383. if (pointResult) {
  29384. pointResult.copyFrom(vertex1.position);
  29385. }
  29386. }
  29387. else if (error === error2) {
  29388. if (pointResult) {
  29389. pointResult.copyFrom(vertex2.position);
  29390. }
  29391. }
  29392. else {
  29393. if (pointResult) {
  29394. pointResult.copyFrom(p3);
  29395. }
  29396. }
  29397. }
  29398. return error;
  29399. };
  29400. return QuadraticErrorSimplification;
  29401. })();
  29402. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29403. })(BABYLON || (BABYLON = {}));
  29404. var BABYLON;
  29405. (function (BABYLON) {
  29406. var serializeLight = function (light) {
  29407. var serializationObject = {};
  29408. serializationObject.name = light.name;
  29409. serializationObject.id = light.id;
  29410. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29411. if (light instanceof BABYLON.PointLight) {
  29412. serializationObject.type = 0;
  29413. serializationObject.position = (light).position.asArray();
  29414. }
  29415. else if (light instanceof BABYLON.DirectionalLight) {
  29416. serializationObject.type = 1;
  29417. var directionalLight = light;
  29418. serializationObject.position = directionalLight.position.asArray();
  29419. serializationObject.direction = directionalLight.direction.asArray();
  29420. }
  29421. else if (light instanceof BABYLON.SpotLight) {
  29422. serializationObject.type = 2;
  29423. var spotLight = light;
  29424. serializationObject.position = spotLight.position.asArray();
  29425. serializationObject.direction = spotLight.position.asArray();
  29426. serializationObject.angle = spotLight.angle;
  29427. serializationObject.exponent = spotLight.exponent;
  29428. }
  29429. else if (light instanceof BABYLON.HemisphericLight) {
  29430. serializationObject.type = 3;
  29431. var hemisphericLight = light;
  29432. serializationObject.direction = hemisphericLight.direction.asArray();
  29433. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29434. }
  29435. if (light.intensity) {
  29436. serializationObject.intensity = light.intensity;
  29437. }
  29438. serializationObject.range = light.range;
  29439. serializationObject.diffuse = light.diffuse.asArray();
  29440. serializationObject.specular = light.specular.asArray();
  29441. return serializationObject;
  29442. };
  29443. var serializeFresnelParameter = function (fresnelParameter) {
  29444. var serializationObject = {};
  29445. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29446. serializationObject.leftColor = fresnelParameter.leftColor;
  29447. serializationObject.rightColor = fresnelParameter.rightColor;
  29448. serializationObject.bias = fresnelParameter.bias;
  29449. serializationObject.power = fresnelParameter.power;
  29450. return serializationObject;
  29451. };
  29452. var serializeAnimation;
  29453. var appendAnimations = function (source, destination) {
  29454. if (source.animations) {
  29455. destination.animations = [];
  29456. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29457. var animation = source.animations[animationIndex];
  29458. destination.animations.push(serializeAnimation(animation));
  29459. }
  29460. }
  29461. };
  29462. var serializeCamera = function (camera) {
  29463. var serializationObject = {};
  29464. serializationObject.name = camera.name;
  29465. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29466. serializationObject.id = camera.id;
  29467. serializationObject.position = camera.position.asArray();
  29468. // Parent
  29469. if (camera.parent) {
  29470. serializationObject.parentId = camera.parent.id;
  29471. }
  29472. serializationObject.fov = camera.fov;
  29473. serializationObject.minZ = camera.minZ;
  29474. serializationObject.maxZ = camera.maxZ;
  29475. serializationObject.inertia = camera.inertia;
  29476. //setting the type
  29477. if (camera instanceof BABYLON.FreeCamera) {
  29478. serializationObject.type = "FreeCamera";
  29479. }
  29480. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29481. serializationObject.type = "ArcRotateCamera";
  29482. }
  29483. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29484. serializationObject.type = "AnaglyphArcRotateCamera";
  29485. }
  29486. else if (camera instanceof BABYLON.GamepadCamera) {
  29487. serializationObject.type = "GamepadCamera";
  29488. }
  29489. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29490. serializationObject.type = "AnaglyphFreeCamera";
  29491. }
  29492. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29493. serializationObject.type = "DeviceOrientationCamera";
  29494. }
  29495. else if (camera instanceof BABYLON.FollowCamera) {
  29496. serializationObject.type = "FollowCamera";
  29497. }
  29498. else if (camera instanceof BABYLON.TouchCamera) {
  29499. serializationObject.type = "TouchCamera";
  29500. }
  29501. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29502. serializationObject.type = "VirtualJoysticksCamera";
  29503. }
  29504. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29505. serializationObject.type = "WebVRFreeCamera";
  29506. }
  29507. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29508. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29509. }
  29510. //special properties of specific cameras
  29511. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29512. var arcCamera = camera;
  29513. serializationObject.alpha = arcCamera.alpha;
  29514. serializationObject.beta = arcCamera.beta;
  29515. serializationObject.radius = arcCamera.radius;
  29516. if (arcCamera.target && arcCamera.target.id) {
  29517. serializationObject.lockedTargetId = arcCamera.target.id;
  29518. }
  29519. }
  29520. else if (camera instanceof BABYLON.FollowCamera) {
  29521. var followCam = camera;
  29522. serializationObject.radius = followCam.radius;
  29523. serializationObject.heightOffset = followCam.heightOffset;
  29524. serializationObject.rotationOffset = followCam.rotationOffset;
  29525. }
  29526. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29527. //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.
  29528. if (camera['_interaxialDistance'] !== undefined) {
  29529. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29530. }
  29531. }
  29532. //general properties that not all cameras have. The [] is due to typescript's type safety
  29533. if (camera['speed'] !== undefined) {
  29534. serializationObject.speed = camera['speed'];
  29535. }
  29536. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29537. serializationObject.target = camera['target'].asArray();
  29538. }
  29539. // Target
  29540. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29541. serializationObject.rotation = camera['rotation'].asArray();
  29542. }
  29543. // Locked target
  29544. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29545. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29546. }
  29547. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29548. serializationObject.applyGravity = camera['applyGravity'] || false;
  29549. if (camera['ellipsoid']) {
  29550. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29551. }
  29552. // Animations
  29553. appendAnimations(camera, serializationObject);
  29554. // Layer mask
  29555. serializationObject.layerMask = camera.layerMask;
  29556. return serializationObject;
  29557. };
  29558. serializeAnimation = function (animation) {
  29559. var serializationObject = {};
  29560. serializationObject.name = animation.name;
  29561. serializationObject.property = animation.targetProperty;
  29562. serializationObject.framePerSecond = animation.framePerSecond;
  29563. serializationObject.dataType = animation.dataType;
  29564. serializationObject.loopBehavior = animation.loopMode;
  29565. var dataType = animation.dataType;
  29566. serializationObject.keys = [];
  29567. var keys = animation.getKeys();
  29568. for (var index = 0; index < keys.length; index++) {
  29569. var animationKey = keys[index];
  29570. var key = {};
  29571. key.frame = animationKey.frame;
  29572. switch (dataType) {
  29573. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29574. key.values = [animationKey.value];
  29575. break;
  29576. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29577. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29578. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29579. key.values = animationKey.value.asArray();
  29580. break;
  29581. }
  29582. serializationObject.keys.push(key);
  29583. }
  29584. return serializationObject;
  29585. };
  29586. var serializeMultiMaterial = function (material) {
  29587. var serializationObject = {};
  29588. serializationObject.name = material.name;
  29589. serializationObject.id = material.id;
  29590. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29591. serializationObject.materials = [];
  29592. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29593. var subMat = material.subMaterials[matIndex];
  29594. if (subMat) {
  29595. serializationObject.materials.push(subMat.id);
  29596. }
  29597. else {
  29598. serializationObject.materials.push(null);
  29599. }
  29600. }
  29601. return serializationObject;
  29602. };
  29603. var serializeTexture;
  29604. var serializeMaterial = function (material) {
  29605. var serializationObject = {};
  29606. serializationObject.name = material.name;
  29607. serializationObject.ambient = material.ambientColor.asArray();
  29608. serializationObject.diffuse = material.diffuseColor.asArray();
  29609. serializationObject.specular = material.specularColor.asArray();
  29610. serializationObject.specularPower = material.specularPower;
  29611. serializationObject.emissive = material.emissiveColor.asArray();
  29612. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29613. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29614. serializationObject.alpha = material.alpha;
  29615. serializationObject.id = material.id;
  29616. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29617. serializationObject.backFaceCulling = material.backFaceCulling;
  29618. if (material.diffuseTexture) {
  29619. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29620. }
  29621. if (material.diffuseFresnelParameters) {
  29622. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29623. }
  29624. if (material.ambientTexture) {
  29625. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29626. }
  29627. if (material.opacityTexture) {
  29628. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29629. }
  29630. if (material.opacityFresnelParameters) {
  29631. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29632. }
  29633. if (material.reflectionTexture) {
  29634. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29635. }
  29636. if (material.reflectionFresnelParameters) {
  29637. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29638. }
  29639. if (material.emissiveTexture) {
  29640. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29641. }
  29642. if (material.lightmapTexture) {
  29643. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29644. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29645. }
  29646. if (material.emissiveFresnelParameters) {
  29647. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29648. }
  29649. if (material.specularTexture) {
  29650. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29651. }
  29652. if (material.bumpTexture) {
  29653. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29654. }
  29655. return serializationObject;
  29656. };
  29657. serializeTexture = function (texture) {
  29658. var serializationObject = {};
  29659. if (!texture.name) {
  29660. return null;
  29661. }
  29662. if (texture instanceof BABYLON.CubeTexture) {
  29663. serializationObject.name = texture.name;
  29664. serializationObject.hasAlpha = texture.hasAlpha;
  29665. serializationObject.isCube = true;
  29666. serializationObject.level = texture.level;
  29667. serializationObject.coordinatesMode = texture.coordinatesMode;
  29668. return serializationObject;
  29669. }
  29670. var index;
  29671. if (texture instanceof BABYLON.MirrorTexture) {
  29672. var mirrorTexture = texture;
  29673. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29674. serializationObject.renderList = [];
  29675. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29676. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29677. }
  29678. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29679. }
  29680. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29681. var renderTargetTexture = texture;
  29682. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29683. serializationObject.renderList = [];
  29684. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29685. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29686. }
  29687. }
  29688. var regularTexture = texture;
  29689. serializationObject.name = texture.name;
  29690. serializationObject.hasAlpha = texture.hasAlpha;
  29691. serializationObject.level = texture.level;
  29692. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29693. serializationObject.coordinatesMode = texture.coordinatesMode;
  29694. serializationObject.uOffset = regularTexture.uOffset;
  29695. serializationObject.vOffset = regularTexture.vOffset;
  29696. serializationObject.uScale = regularTexture.uScale;
  29697. serializationObject.vScale = regularTexture.vScale;
  29698. serializationObject.uAng = regularTexture.uAng;
  29699. serializationObject.vAng = regularTexture.vAng;
  29700. serializationObject.wAng = regularTexture.wAng;
  29701. serializationObject.wrapU = texture.wrapU;
  29702. serializationObject.wrapV = texture.wrapV;
  29703. // Animations
  29704. appendAnimations(texture, serializationObject);
  29705. return serializationObject;
  29706. };
  29707. var serializeSkeleton = function (skeleton) {
  29708. var serializationObject = {};
  29709. serializationObject.name = skeleton.name;
  29710. serializationObject.id = skeleton.id;
  29711. serializationObject.bones = [];
  29712. for (var index = 0; index < skeleton.bones.length; index++) {
  29713. var bone = skeleton.bones[index];
  29714. var serializedBone = {
  29715. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29716. name: bone.name,
  29717. matrix: bone.getLocalMatrix().toArray()
  29718. };
  29719. serializationObject.bones.push(serializedBone);
  29720. if (bone.animations && bone.animations.length > 0) {
  29721. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29722. }
  29723. }
  29724. return serializationObject;
  29725. };
  29726. var serializeParticleSystem = function (particleSystem) {
  29727. var serializationObject = {};
  29728. serializationObject.emitterId = particleSystem.emitter.id;
  29729. serializationObject.capacity = particleSystem.getCapacity();
  29730. if (particleSystem.particleTexture) {
  29731. serializationObject.textureName = particleSystem.particleTexture.name;
  29732. }
  29733. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29734. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29735. serializationObject.minSize = particleSystem.minSize;
  29736. serializationObject.maxSize = particleSystem.maxSize;
  29737. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29738. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29739. serializationObject.emitRate = particleSystem.emitRate;
  29740. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29741. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29742. serializationObject.gravity = particleSystem.gravity.asArray();
  29743. serializationObject.direction1 = particleSystem.direction1.asArray();
  29744. serializationObject.direction2 = particleSystem.direction2.asArray();
  29745. serializationObject.color1 = particleSystem.color1.asArray();
  29746. serializationObject.color2 = particleSystem.color2.asArray();
  29747. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29748. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29749. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29750. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29751. serializationObject.blendMode = particleSystem.blendMode;
  29752. return serializationObject;
  29753. };
  29754. var serializeLensFlareSystem = function (lensFlareSystem) {
  29755. var serializationObject = {};
  29756. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29757. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29758. serializationObject.flares = [];
  29759. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29760. var flare = lensFlareSystem.lensFlares[index];
  29761. serializationObject.flares.push({
  29762. size: flare.size,
  29763. position: flare.position,
  29764. color: flare.color.asArray(),
  29765. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29766. });
  29767. }
  29768. return serializationObject;
  29769. };
  29770. var serializeShadowGenerator = function (light) {
  29771. var serializationObject = {};
  29772. var shadowGenerator = light.getShadowGenerator();
  29773. serializationObject.lightId = light.id;
  29774. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29775. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29776. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29777. serializationObject.renderList = [];
  29778. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29779. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29780. serializationObject.renderList.push(mesh.id);
  29781. }
  29782. return serializationObject;
  29783. };
  29784. var serializedGeometries = [];
  29785. var serializeVertexData;
  29786. var serializeTorusKnot;
  29787. var serializePlane;
  29788. var serializeGround;
  29789. var serializeTorus;
  29790. var serializeCylinder;
  29791. var serializeSphere;
  29792. var serializeBox;
  29793. var serializeGeometry = function (geometry, serializationGeometries) {
  29794. if (serializedGeometries[geometry.id]) {
  29795. return;
  29796. }
  29797. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29798. serializationGeometries.boxes.push(serializeBox(geometry));
  29799. }
  29800. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29801. serializationGeometries.spheres.push(serializeSphere(geometry));
  29802. }
  29803. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29804. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29805. }
  29806. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29807. serializationGeometries.toruses.push(serializeTorus(geometry));
  29808. }
  29809. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29810. serializationGeometries.grounds.push(serializeGround(geometry));
  29811. }
  29812. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29813. serializationGeometries.planes.push(serializePlane(geometry));
  29814. }
  29815. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29816. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29817. }
  29818. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29819. throw new Error("Unknown primitive type");
  29820. }
  29821. else {
  29822. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29823. }
  29824. serializedGeometries[geometry.id] = true;
  29825. };
  29826. var serializeGeometryBase = function (geometry) {
  29827. var serializationObject = {};
  29828. serializationObject.id = geometry.id;
  29829. if (BABYLON.Tags.HasTags(geometry)) {
  29830. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29831. }
  29832. return serializationObject;
  29833. };
  29834. serializeVertexData = function (vertexData) {
  29835. var serializationObject = serializeGeometryBase(vertexData);
  29836. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29837. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29838. }
  29839. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29840. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29841. }
  29842. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29843. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29844. }
  29845. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29846. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29847. }
  29848. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29849. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29850. }
  29851. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29852. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29853. }
  29854. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29855. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29856. }
  29857. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29858. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29859. }
  29860. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29861. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29862. }
  29863. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29864. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29865. serializationObject.matricesIndices._isExpanded = true;
  29866. }
  29867. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29868. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29869. }
  29870. serializationObject.indices = vertexData.getIndices();
  29871. return serializationObject;
  29872. };
  29873. var serializePrimitive = function (primitive) {
  29874. var serializationObject = serializeGeometryBase(primitive);
  29875. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29876. return serializationObject;
  29877. };
  29878. serializeBox = function (box) {
  29879. var serializationObject = serializePrimitive(box);
  29880. serializationObject.size = box.size;
  29881. return serializationObject;
  29882. };
  29883. serializeSphere = function (sphere) {
  29884. var serializationObject = serializePrimitive(sphere);
  29885. serializationObject.segments = sphere.segments;
  29886. serializationObject.diameter = sphere.diameter;
  29887. return serializationObject;
  29888. };
  29889. serializeCylinder = function (cylinder) {
  29890. var serializationObject = serializePrimitive(cylinder);
  29891. serializationObject.height = cylinder.height;
  29892. serializationObject.diameterTop = cylinder.diameterTop;
  29893. serializationObject.diameterBottom = cylinder.diameterBottom;
  29894. serializationObject.tessellation = cylinder.tessellation;
  29895. return serializationObject;
  29896. };
  29897. serializeTorus = function (torus) {
  29898. var serializationObject = serializePrimitive(torus);
  29899. serializationObject.diameter = torus.diameter;
  29900. serializationObject.thickness = torus.thickness;
  29901. serializationObject.tessellation = torus.tessellation;
  29902. return serializationObject;
  29903. };
  29904. serializeGround = function (ground) {
  29905. var serializationObject = serializePrimitive(ground);
  29906. serializationObject.width = ground.width;
  29907. serializationObject.height = ground.height;
  29908. serializationObject.subdivisions = ground.subdivisions;
  29909. return serializationObject;
  29910. };
  29911. serializePlane = function (plane) {
  29912. var serializationObject = serializePrimitive(plane);
  29913. serializationObject.size = plane.size;
  29914. return serializationObject;
  29915. };
  29916. serializeTorusKnot = function (torusKnot) {
  29917. var serializationObject = serializePrimitive(torusKnot);
  29918. serializationObject.radius = torusKnot.radius;
  29919. serializationObject.tube = torusKnot.tube;
  29920. serializationObject.radialSegments = torusKnot.radialSegments;
  29921. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29922. serializationObject.p = torusKnot.p;
  29923. serializationObject.q = torusKnot.q;
  29924. return serializationObject;
  29925. };
  29926. var serializeMesh = function (mesh, serializationScene) {
  29927. var serializationObject = {};
  29928. serializationObject.name = mesh.name;
  29929. serializationObject.id = mesh.id;
  29930. if (BABYLON.Tags.HasTags(mesh)) {
  29931. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29932. }
  29933. serializationObject.position = mesh.position.asArray();
  29934. if (mesh.rotationQuaternion) {
  29935. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29936. }
  29937. else if (mesh.rotation) {
  29938. serializationObject.rotation = mesh.rotation.asArray();
  29939. }
  29940. serializationObject.scaling = mesh.scaling.asArray();
  29941. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29942. serializationObject.isEnabled = mesh.isEnabled();
  29943. serializationObject.isVisible = mesh.isVisible;
  29944. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29945. serializationObject.pickable = mesh.isPickable;
  29946. serializationObject.receiveShadows = mesh.receiveShadows;
  29947. serializationObject.billboardMode = mesh.billboardMode;
  29948. serializationObject.visibility = mesh.visibility;
  29949. serializationObject.checkCollisions = mesh.checkCollisions;
  29950. // Parent
  29951. if (mesh.parent) {
  29952. serializationObject.parentId = mesh.parent.id;
  29953. }
  29954. // Geometry
  29955. var geometry = mesh._geometry;
  29956. if (geometry) {
  29957. var geometryId = geometry.id;
  29958. serializationObject.geometryId = geometryId;
  29959. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29960. // 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
  29961. serializeGeometry(geometry, serializationScene.geometries);
  29962. }
  29963. // SubMeshes
  29964. serializationObject.subMeshes = [];
  29965. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29966. var subMesh = mesh.subMeshes[subIndex];
  29967. serializationObject.subMeshes.push({
  29968. materialIndex: subMesh.materialIndex,
  29969. verticesStart: subMesh.verticesStart,
  29970. verticesCount: subMesh.verticesCount,
  29971. indexStart: subMesh.indexStart,
  29972. indexCount: subMesh.indexCount
  29973. });
  29974. }
  29975. }
  29976. // Material
  29977. if (mesh.material) {
  29978. serializationObject.materialId = mesh.material.id;
  29979. }
  29980. else {
  29981. mesh.material = null;
  29982. }
  29983. // Skeleton
  29984. if (mesh.skeleton) {
  29985. serializationObject.skeletonId = mesh.skeleton.id;
  29986. }
  29987. // Physics
  29988. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29989. serializationObject.physicsMass = mesh.getPhysicsMass();
  29990. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29991. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29992. switch (mesh.getPhysicsImpostor()) {
  29993. case BABYLON.PhysicsEngine.BoxImpostor:
  29994. serializationObject.physicsImpostor = 1;
  29995. break;
  29996. case BABYLON.PhysicsEngine.SphereImpostor:
  29997. serializationObject.physicsImpostor = 2;
  29998. break;
  29999. }
  30000. }
  30001. // Instances
  30002. serializationObject.instances = [];
  30003. for (var index = 0; index < mesh.instances.length; index++) {
  30004. var instance = mesh.instances[index];
  30005. var serializationInstance = {
  30006. name: instance.name,
  30007. position: instance.position.asArray(),
  30008. rotation: instance.rotation.asArray(),
  30009. rotationQuaternion: instance.rotationQuaternion.asArray(),
  30010. scaling: instance.scaling.asArray()
  30011. };
  30012. serializationObject.instances.push(serializationInstance);
  30013. // Animations
  30014. appendAnimations(instance, serializationInstance);
  30015. }
  30016. // Animations
  30017. appendAnimations(mesh, serializationObject);
  30018. // Layer mask
  30019. serializationObject.layerMask = mesh.layerMask;
  30020. return serializationObject;
  30021. };
  30022. var finalizeSingleMesh = function (mesh, serializationObject) {
  30023. //only works if the mesh is already loaded
  30024. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30025. //serialize material
  30026. if (mesh.material) {
  30027. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30028. serializationObject.materials = serializationObject.materials || [];
  30029. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30030. serializationObject.materials.push(serializeMaterial(mesh.material));
  30031. }
  30032. }
  30033. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30034. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30035. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30036. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  30037. }
  30038. }
  30039. }
  30040. //serialize geometry
  30041. var geometry = mesh._geometry;
  30042. if (geometry) {
  30043. if (!serializationObject.geometries) {
  30044. serializationObject.geometries = {};
  30045. serializationObject.geometries.boxes = [];
  30046. serializationObject.geometries.spheres = [];
  30047. serializationObject.geometries.cylinders = [];
  30048. serializationObject.geometries.toruses = [];
  30049. serializationObject.geometries.grounds = [];
  30050. serializationObject.geometries.planes = [];
  30051. serializationObject.geometries.torusKnots = [];
  30052. serializationObject.geometries.vertexData = [];
  30053. }
  30054. serializeGeometry(geometry, serializationObject.geometries);
  30055. }
  30056. // Skeletons
  30057. if (mesh.skeleton) {
  30058. serializationObject.skeletons = serializationObject.skeletons || [];
  30059. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  30060. }
  30061. //serialize the actual mesh
  30062. serializationObject.meshes = serializationObject.meshes || [];
  30063. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30064. }
  30065. };
  30066. var SceneSerializer = (function () {
  30067. function SceneSerializer() {
  30068. }
  30069. SceneSerializer.Serialize = function (scene) {
  30070. var serializationObject = {};
  30071. // Scene
  30072. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30073. serializationObject.autoClear = scene.autoClear;
  30074. serializationObject.clearColor = scene.clearColor.asArray();
  30075. serializationObject.ambientColor = scene.ambientColor.asArray();
  30076. serializationObject.gravity = scene.gravity.asArray();
  30077. // Fog
  30078. if (scene.fogMode && scene.fogMode !== 0) {
  30079. serializationObject.fogMode = scene.fogMode;
  30080. serializationObject.fogColor = scene.fogColor.asArray();
  30081. serializationObject.fogStart = scene.fogStart;
  30082. serializationObject.fogEnd = scene.fogEnd;
  30083. serializationObject.fogDensity = scene.fogDensity;
  30084. }
  30085. // Lights
  30086. serializationObject.lights = [];
  30087. var index;
  30088. var light;
  30089. for (index = 0; index < scene.lights.length; index++) {
  30090. light = scene.lights[index];
  30091. serializationObject.lights.push(serializeLight(light));
  30092. }
  30093. // Cameras
  30094. serializationObject.cameras = [];
  30095. for (index = 0; index < scene.cameras.length; index++) {
  30096. var camera = scene.cameras[index];
  30097. serializationObject.cameras.push(serializeCamera(camera));
  30098. }
  30099. if (scene.activeCamera) {
  30100. serializationObject.activeCameraID = scene.activeCamera.id;
  30101. }
  30102. // Materials
  30103. serializationObject.materials = [];
  30104. serializationObject.multiMaterials = [];
  30105. var material;
  30106. for (index = 0; index < scene.materials.length; index++) {
  30107. material = scene.materials[index];
  30108. serializationObject.materials.push(serializeMaterial(material));
  30109. }
  30110. // MultiMaterials
  30111. serializationObject.multiMaterials = [];
  30112. for (index = 0; index < scene.multiMaterials.length; index++) {
  30113. var multiMaterial = scene.multiMaterials[index];
  30114. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  30115. }
  30116. for (index = 0; index < scene.materials.length; index++) {
  30117. material = scene.materials[index];
  30118. if (material instanceof BABYLON.StandardMaterial) {
  30119. serializationObject.materials.push(serializeMaterial(material));
  30120. }
  30121. else if (material instanceof BABYLON.MultiMaterial) {
  30122. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  30123. }
  30124. }
  30125. // Skeletons
  30126. serializationObject.skeletons = [];
  30127. for (index = 0; index < scene.skeletons.length; index++) {
  30128. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  30129. }
  30130. // Geometries
  30131. serializationObject.geometries = {};
  30132. serializationObject.geometries.boxes = [];
  30133. serializationObject.geometries.spheres = [];
  30134. serializationObject.geometries.cylinders = [];
  30135. serializationObject.geometries.toruses = [];
  30136. serializationObject.geometries.grounds = [];
  30137. serializationObject.geometries.planes = [];
  30138. serializationObject.geometries.torusKnots = [];
  30139. serializationObject.geometries.vertexData = [];
  30140. serializedGeometries = [];
  30141. var geometries = scene.getGeometries();
  30142. for (index = 0; index < geometries.length; index++) {
  30143. var geometry = geometries[index];
  30144. if (geometry.isReady()) {
  30145. serializeGeometry(geometry, serializationObject.geometries);
  30146. }
  30147. }
  30148. // Meshes
  30149. serializationObject.meshes = [];
  30150. for (index = 0; index < scene.meshes.length; index++) {
  30151. var abstractMesh = scene.meshes[index];
  30152. if (abstractMesh instanceof BABYLON.Mesh) {
  30153. var mesh = abstractMesh;
  30154. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30155. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30156. }
  30157. }
  30158. }
  30159. // Particles Systems
  30160. serializationObject.particleSystems = [];
  30161. for (index = 0; index < scene.particleSystems.length; index++) {
  30162. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  30163. }
  30164. // Lens flares
  30165. serializationObject.lensFlareSystems = [];
  30166. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30167. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  30168. }
  30169. // Shadows
  30170. serializationObject.shadowGenerators = [];
  30171. for (index = 0; index < scene.lights.length; index++) {
  30172. light = scene.lights[index];
  30173. if (light.getShadowGenerator()) {
  30174. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  30175. }
  30176. }
  30177. return serializationObject;
  30178. };
  30179. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30180. if (withParents === void 0) { withParents = false; }
  30181. if (withChildren === void 0) { withChildren = false; }
  30182. var serializationObject = {};
  30183. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30184. if (withParents || withChildren) {
  30185. //deliberate for loop! not for each, appended should be processed as well.
  30186. for (var i = 0; i < toSerialize.length; ++i) {
  30187. if (withChildren) {
  30188. toSerialize[i].getDescendants().forEach(function (node) {
  30189. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30190. toSerialize.push(node);
  30191. }
  30192. });
  30193. }
  30194. //make sure the array doesn't contain the object already
  30195. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30196. toSerialize.push(toSerialize[i].parent);
  30197. }
  30198. }
  30199. }
  30200. toSerialize.forEach(function (mesh) {
  30201. finalizeSingleMesh(mesh, serializationObject);
  30202. });
  30203. return serializationObject;
  30204. };
  30205. return SceneSerializer;
  30206. })();
  30207. BABYLON.SceneSerializer = SceneSerializer;
  30208. })(BABYLON || (BABYLON = {}));
  30209. var BABYLON;
  30210. (function (BABYLON) {
  30211. // Unique ID when we import meshes from Babylon to CSG
  30212. var currentCSGMeshId = 0;
  30213. // # class Vertex
  30214. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30215. // one to provide additional features like texture coordinates and vertex
  30216. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30217. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30218. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30219. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30220. // is not used anywhere else.
  30221. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30222. var Vertex = (function () {
  30223. function Vertex(pos, normal, uv) {
  30224. this.pos = pos;
  30225. this.normal = normal;
  30226. this.uv = uv;
  30227. }
  30228. Vertex.prototype.clone = function () {
  30229. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30230. };
  30231. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30232. // orientation of a polygon is flipped.
  30233. Vertex.prototype.flip = function () {
  30234. this.normal = this.normal.scale(-1);
  30235. };
  30236. // Create a new vertex between this vertex and `other` by linearly
  30237. // interpolating all properties using a parameter of `t`. Subclasses should
  30238. // override this to interpolate additional properties.
  30239. Vertex.prototype.interpolate = function (other, t) {
  30240. 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));
  30241. };
  30242. return Vertex;
  30243. })();
  30244. // # class Plane
  30245. // Represents a plane in 3D space.
  30246. var Plane = (function () {
  30247. function Plane(normal, w) {
  30248. this.normal = normal;
  30249. this.w = w;
  30250. }
  30251. Plane.FromPoints = function (a, b, c) {
  30252. var v0 = c.subtract(a);
  30253. var v1 = b.subtract(a);
  30254. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30255. return null;
  30256. }
  30257. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30258. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30259. };
  30260. Plane.prototype.clone = function () {
  30261. return new Plane(this.normal.clone(), this.w);
  30262. };
  30263. Plane.prototype.flip = function () {
  30264. this.normal.scaleInPlace(-1);
  30265. this.w = -this.w;
  30266. };
  30267. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30268. // fragments in the appropriate lists. Coplanar polygons go into either
  30269. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30270. // respect to this plane. Polygons in front or in back of this plane go into
  30271. // either `front` or `back`.
  30272. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30273. var COPLANAR = 0;
  30274. var FRONT = 1;
  30275. var BACK = 2;
  30276. var SPANNING = 3;
  30277. // Classify each point as well as the entire polygon into one of the above
  30278. // four classes.
  30279. var polygonType = 0;
  30280. var types = [];
  30281. var i;
  30282. var t;
  30283. for (i = 0; i < polygon.vertices.length; i++) {
  30284. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30285. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30286. polygonType |= type;
  30287. types.push(type);
  30288. }
  30289. // Put the polygon in the correct list, splitting it when necessary.
  30290. switch (polygonType) {
  30291. case COPLANAR:
  30292. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30293. break;
  30294. case FRONT:
  30295. front.push(polygon);
  30296. break;
  30297. case BACK:
  30298. back.push(polygon);
  30299. break;
  30300. case SPANNING:
  30301. var f = [], b = [];
  30302. for (i = 0; i < polygon.vertices.length; i++) {
  30303. var j = (i + 1) % polygon.vertices.length;
  30304. var ti = types[i], tj = types[j];
  30305. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30306. if (ti !== BACK)
  30307. f.push(vi);
  30308. if (ti !== FRONT)
  30309. b.push(ti !== BACK ? vi.clone() : vi);
  30310. if ((ti | tj) === SPANNING) {
  30311. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30312. var v = vi.interpolate(vj, t);
  30313. f.push(v);
  30314. b.push(v.clone());
  30315. }
  30316. }
  30317. var poly;
  30318. if (f.length >= 3) {
  30319. poly = new Polygon(f, polygon.shared);
  30320. if (poly.plane)
  30321. front.push(poly);
  30322. }
  30323. if (b.length >= 3) {
  30324. poly = new Polygon(b, polygon.shared);
  30325. if (poly.plane)
  30326. back.push(poly);
  30327. }
  30328. break;
  30329. }
  30330. };
  30331. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30332. // point is on the plane.
  30333. Plane.EPSILON = 1e-5;
  30334. return Plane;
  30335. })();
  30336. // # class Polygon
  30337. // Represents a convex polygon. The vertices used to initialize a polygon must
  30338. // be coplanar and form a convex loop.
  30339. //
  30340. // Each convex polygon has a `shared` property, which is shared between all
  30341. // polygons that are clones of each other or were split from the same polygon.
  30342. // This can be used to define per-polygon properties (such as surface color).
  30343. var Polygon = (function () {
  30344. function Polygon(vertices, shared) {
  30345. this.vertices = vertices;
  30346. this.shared = shared;
  30347. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30348. }
  30349. Polygon.prototype.clone = function () {
  30350. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30351. return new Polygon(vertices, this.shared);
  30352. };
  30353. Polygon.prototype.flip = function () {
  30354. this.vertices.reverse().map(function (v) { v.flip(); });
  30355. this.plane.flip();
  30356. };
  30357. return Polygon;
  30358. })();
  30359. // # class Node
  30360. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30361. // by picking a polygon to split along. That polygon (and all other coplanar
  30362. // polygons) are added directly to that node and the other polygons are added to
  30363. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30364. // no distinction between internal and leaf nodes.
  30365. var Node = (function () {
  30366. function Node(polygons) {
  30367. this.plane = null;
  30368. this.front = null;
  30369. this.back = null;
  30370. this.polygons = [];
  30371. if (polygons) {
  30372. this.build(polygons);
  30373. }
  30374. }
  30375. Node.prototype.clone = function () {
  30376. var node = new Node();
  30377. node.plane = this.plane && this.plane.clone();
  30378. node.front = this.front && this.front.clone();
  30379. node.back = this.back && this.back.clone();
  30380. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30381. return node;
  30382. };
  30383. // Convert solid space to empty space and empty space to solid space.
  30384. Node.prototype.invert = function () {
  30385. for (var i = 0; i < this.polygons.length; i++) {
  30386. this.polygons[i].flip();
  30387. }
  30388. if (this.plane) {
  30389. this.plane.flip();
  30390. }
  30391. if (this.front) {
  30392. this.front.invert();
  30393. }
  30394. if (this.back) {
  30395. this.back.invert();
  30396. }
  30397. var temp = this.front;
  30398. this.front = this.back;
  30399. this.back = temp;
  30400. };
  30401. // Recursively remove all polygons in `polygons` that are inside this BSP
  30402. // tree.
  30403. Node.prototype.clipPolygons = function (polygons) {
  30404. if (!this.plane)
  30405. return polygons.slice();
  30406. var front = [], back = [];
  30407. for (var i = 0; i < polygons.length; i++) {
  30408. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30409. }
  30410. if (this.front) {
  30411. front = this.front.clipPolygons(front);
  30412. }
  30413. if (this.back) {
  30414. back = this.back.clipPolygons(back);
  30415. }
  30416. else {
  30417. back = [];
  30418. }
  30419. return front.concat(back);
  30420. };
  30421. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30422. // `bsp`.
  30423. Node.prototype.clipTo = function (bsp) {
  30424. this.polygons = bsp.clipPolygons(this.polygons);
  30425. if (this.front)
  30426. this.front.clipTo(bsp);
  30427. if (this.back)
  30428. this.back.clipTo(bsp);
  30429. };
  30430. // Return a list of all polygons in this BSP tree.
  30431. Node.prototype.allPolygons = function () {
  30432. var polygons = this.polygons.slice();
  30433. if (this.front)
  30434. polygons = polygons.concat(this.front.allPolygons());
  30435. if (this.back)
  30436. polygons = polygons.concat(this.back.allPolygons());
  30437. return polygons;
  30438. };
  30439. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30440. // new polygons are filtered down to the bottom of the tree and become new
  30441. // nodes there. Each set of polygons is partitioned using the first polygon
  30442. // (no heuristic is used to pick a good split).
  30443. Node.prototype.build = function (polygons) {
  30444. if (!polygons.length)
  30445. return;
  30446. if (!this.plane)
  30447. this.plane = polygons[0].plane.clone();
  30448. var front = [], back = [];
  30449. for (var i = 0; i < polygons.length; i++) {
  30450. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30451. }
  30452. if (front.length) {
  30453. if (!this.front)
  30454. this.front = new Node();
  30455. this.front.build(front);
  30456. }
  30457. if (back.length) {
  30458. if (!this.back)
  30459. this.back = new Node();
  30460. this.back.build(back);
  30461. }
  30462. };
  30463. return Node;
  30464. })();
  30465. var CSG = (function () {
  30466. function CSG() {
  30467. this.polygons = new Array();
  30468. }
  30469. // Convert BABYLON.Mesh to BABYLON.CSG
  30470. CSG.FromMesh = function (mesh) {
  30471. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30472. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30473. if (mesh instanceof BABYLON.Mesh) {
  30474. mesh.computeWorldMatrix(true);
  30475. matrix = mesh.getWorldMatrix();
  30476. meshPosition = mesh.position.clone();
  30477. meshRotation = mesh.rotation.clone();
  30478. if (mesh.rotationQuaternion) {
  30479. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30480. }
  30481. meshScaling = mesh.scaling.clone();
  30482. }
  30483. else {
  30484. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30485. }
  30486. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30487. var subMeshes = mesh.subMeshes;
  30488. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30489. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30490. vertices = [];
  30491. for (var j = 0; j < 3; j++) {
  30492. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30493. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30494. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30495. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30496. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30497. vertex = new Vertex(position, normal, uv);
  30498. vertices.push(vertex);
  30499. }
  30500. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30501. // To handle the case of degenerated triangle
  30502. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30503. if (polygon.plane)
  30504. polygons.push(polygon);
  30505. }
  30506. }
  30507. var csg = CSG.FromPolygons(polygons);
  30508. csg.matrix = matrix;
  30509. csg.position = meshPosition;
  30510. csg.rotation = meshRotation;
  30511. csg.scaling = meshScaling;
  30512. csg.rotationQuaternion = meshRotationQuaternion;
  30513. currentCSGMeshId++;
  30514. return csg;
  30515. };
  30516. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30517. CSG.FromPolygons = function (polygons) {
  30518. var csg = new CSG();
  30519. csg.polygons = polygons;
  30520. return csg;
  30521. };
  30522. CSG.prototype.clone = function () {
  30523. var csg = new CSG();
  30524. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30525. csg.copyTransformAttributes(this);
  30526. return csg;
  30527. };
  30528. CSG.prototype.toPolygons = function () {
  30529. return this.polygons;
  30530. };
  30531. CSG.prototype.union = function (csg) {
  30532. var a = new Node(this.clone().polygons);
  30533. var b = new Node(csg.clone().polygons);
  30534. a.clipTo(b);
  30535. b.clipTo(a);
  30536. b.invert();
  30537. b.clipTo(a);
  30538. b.invert();
  30539. a.build(b.allPolygons());
  30540. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30541. };
  30542. CSG.prototype.unionInPlace = function (csg) {
  30543. var a = new Node(this.polygons);
  30544. var b = new Node(csg.polygons);
  30545. a.clipTo(b);
  30546. b.clipTo(a);
  30547. b.invert();
  30548. b.clipTo(a);
  30549. b.invert();
  30550. a.build(b.allPolygons());
  30551. this.polygons = a.allPolygons();
  30552. };
  30553. CSG.prototype.subtract = function (csg) {
  30554. var a = new Node(this.clone().polygons);
  30555. var b = new Node(csg.clone().polygons);
  30556. a.invert();
  30557. a.clipTo(b);
  30558. b.clipTo(a);
  30559. b.invert();
  30560. b.clipTo(a);
  30561. b.invert();
  30562. a.build(b.allPolygons());
  30563. a.invert();
  30564. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30565. };
  30566. CSG.prototype.subtractInPlace = function (csg) {
  30567. var a = new Node(this.polygons);
  30568. var b = new Node(csg.polygons);
  30569. a.invert();
  30570. a.clipTo(b);
  30571. b.clipTo(a);
  30572. b.invert();
  30573. b.clipTo(a);
  30574. b.invert();
  30575. a.build(b.allPolygons());
  30576. a.invert();
  30577. this.polygons = a.allPolygons();
  30578. };
  30579. CSG.prototype.intersect = function (csg) {
  30580. var a = new Node(this.clone().polygons);
  30581. var b = new Node(csg.clone().polygons);
  30582. a.invert();
  30583. b.clipTo(a);
  30584. b.invert();
  30585. a.clipTo(b);
  30586. b.clipTo(a);
  30587. a.build(b.allPolygons());
  30588. a.invert();
  30589. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30590. };
  30591. CSG.prototype.intersectInPlace = function (csg) {
  30592. var a = new Node(this.polygons);
  30593. var b = new Node(csg.polygons);
  30594. a.invert();
  30595. b.clipTo(a);
  30596. b.invert();
  30597. a.clipTo(b);
  30598. b.clipTo(a);
  30599. a.build(b.allPolygons());
  30600. a.invert();
  30601. this.polygons = a.allPolygons();
  30602. };
  30603. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30604. // not modified.
  30605. CSG.prototype.inverse = function () {
  30606. var csg = this.clone();
  30607. csg.inverseInPlace();
  30608. return csg;
  30609. };
  30610. CSG.prototype.inverseInPlace = function () {
  30611. this.polygons.map(function (p) { p.flip(); });
  30612. };
  30613. // This is used to keep meshes transformations so they can be restored
  30614. // when we build back a Babylon Mesh
  30615. // NB : All CSG operations are performed in world coordinates
  30616. CSG.prototype.copyTransformAttributes = function (csg) {
  30617. this.matrix = csg.matrix;
  30618. this.position = csg.position;
  30619. this.rotation = csg.rotation;
  30620. this.scaling = csg.scaling;
  30621. this.rotationQuaternion = csg.rotationQuaternion;
  30622. return this;
  30623. };
  30624. // Build Raw mesh from CSG
  30625. // Coordinates here are in world space
  30626. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30627. var matrix = this.matrix.clone();
  30628. matrix.invert();
  30629. 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;
  30630. if (keepSubMeshes) {
  30631. // Sort Polygons, since subMeshes are indices range
  30632. polygons.sort(function (a, b) {
  30633. if (a.shared.meshId === b.shared.meshId) {
  30634. return a.shared.subMeshId - b.shared.subMeshId;
  30635. }
  30636. else {
  30637. return a.shared.meshId - b.shared.meshId;
  30638. }
  30639. });
  30640. }
  30641. for (var i = 0, il = polygons.length; i < il; i++) {
  30642. polygon = polygons[i];
  30643. // Building SubMeshes
  30644. if (!subMesh_dict[polygon.shared.meshId]) {
  30645. subMesh_dict[polygon.shared.meshId] = {};
  30646. }
  30647. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30648. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30649. indexStart: +Infinity,
  30650. indexEnd: -Infinity,
  30651. materialIndex: polygon.shared.materialIndex
  30652. };
  30653. }
  30654. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30655. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30656. polygonIndices[0] = 0;
  30657. polygonIndices[1] = j - 1;
  30658. polygonIndices[2] = j;
  30659. for (var k = 0; k < 3; k++) {
  30660. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30661. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30662. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30663. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30664. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30665. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30666. // Check if 2 points can be merged
  30667. if (!(typeof vertex_idx !== 'undefined' &&
  30668. normals[vertex_idx * 3] === localNormal.x &&
  30669. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30670. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30671. uvs[vertex_idx * 2] === uv.x &&
  30672. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30673. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30674. uvs.push(uv.x, uv.y);
  30675. normals.push(normal.x, normal.y, normal.z);
  30676. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30677. }
  30678. indices.push(vertex_idx);
  30679. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30680. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30681. currentIndex++;
  30682. }
  30683. }
  30684. }
  30685. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30686. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30687. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30688. mesh.setIndices(indices);
  30689. if (keepSubMeshes) {
  30690. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30691. var materialIndexOffset = 0, materialMaxIndex;
  30692. mesh.subMeshes = new Array();
  30693. for (var m in subMesh_dict) {
  30694. materialMaxIndex = -1;
  30695. for (var sm in subMesh_dict[m]) {
  30696. subMesh_obj = subMesh_dict[m][sm];
  30697. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30698. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30699. }
  30700. materialIndexOffset += ++materialMaxIndex;
  30701. }
  30702. }
  30703. return mesh;
  30704. };
  30705. // Build Mesh from CSG taking material and transforms into account
  30706. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30707. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30708. mesh.material = material;
  30709. mesh.position.copyFrom(this.position);
  30710. mesh.rotation.copyFrom(this.rotation);
  30711. if (this.rotationQuaternion) {
  30712. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30713. }
  30714. mesh.scaling.copyFrom(this.scaling);
  30715. mesh.computeWorldMatrix(true);
  30716. return mesh;
  30717. };
  30718. return CSG;
  30719. })();
  30720. BABYLON.CSG = CSG;
  30721. })(BABYLON || (BABYLON = {}));
  30722. var BABYLON;
  30723. (function (BABYLON) {
  30724. var VRDistortionCorrectionPostProcess = (function (_super) {
  30725. __extends(VRDistortionCorrectionPostProcess, _super);
  30726. //ANY
  30727. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30728. var _this = this;
  30729. _super.call(this, name, "vrDistortionCorrection", [
  30730. 'LensCenter',
  30731. 'Scale',
  30732. 'ScaleIn',
  30733. 'HmdWarpParam'
  30734. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30735. this._isRightEye = isRightEye;
  30736. this._distortionFactors = vrMetrics.distortionK;
  30737. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30738. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30739. this.onSizeChanged = function () {
  30740. _this.aspectRatio = _this.width * .5 / _this.height;
  30741. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30742. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30743. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30744. };
  30745. this.onApply = function (effect) {
  30746. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30747. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30748. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30749. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30750. };
  30751. }
  30752. return VRDistortionCorrectionPostProcess;
  30753. })(BABYLON.PostProcess);
  30754. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30755. })(BABYLON || (BABYLON = {}));
  30756. // Mainly based on these 2 articles :
  30757. // 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
  30758. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30759. var BABYLON;
  30760. (function (BABYLON) {
  30761. (function (JoystickAxis) {
  30762. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30763. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30764. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30765. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30766. var JoystickAxis = BABYLON.JoystickAxis;
  30767. var VirtualJoystick = (function () {
  30768. function VirtualJoystick(leftJoystick) {
  30769. var _this = this;
  30770. if (leftJoystick) {
  30771. this._leftJoystick = true;
  30772. }
  30773. else {
  30774. this._leftJoystick = false;
  30775. }
  30776. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30777. VirtualJoystick._globalJoystickIndex++;
  30778. // By default left & right arrow keys are moving the X
  30779. // and up & down keys are moving the Y
  30780. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30781. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30782. this.reverseLeftRight = false;
  30783. this.reverseUpDown = false;
  30784. // collections of pointers
  30785. this._touches = new BABYLON.SmartCollection();
  30786. this.deltaPosition = BABYLON.Vector3.Zero();
  30787. this._joystickSensibility = 25;
  30788. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30789. this._rotationSpeed = 25;
  30790. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30791. this._rotateOnAxisRelativeToMesh = false;
  30792. this._onResize = function (evt) {
  30793. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30794. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30795. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30796. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30797. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30798. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30799. };
  30800. // injecting a canvas element on top of the canvas 3D game
  30801. if (!VirtualJoystick.vjCanvas) {
  30802. window.addEventListener("resize", this._onResize, false);
  30803. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30804. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30805. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30806. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30807. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30808. VirtualJoystick.vjCanvas.style.width = "100%";
  30809. VirtualJoystick.vjCanvas.style.height = "100%";
  30810. VirtualJoystick.vjCanvas.style.position = "absolute";
  30811. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30812. VirtualJoystick.vjCanvas.style.top = "0px";
  30813. VirtualJoystick.vjCanvas.style.left = "0px";
  30814. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30815. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30816. // Support for jQuery PEP polyfill
  30817. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30818. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30819. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30820. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30821. document.body.appendChild(VirtualJoystick.vjCanvas);
  30822. }
  30823. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30824. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30825. this.pressed = false;
  30826. // default joystick color
  30827. this._joystickColor = "cyan";
  30828. this._joystickPointerID = -1;
  30829. // current joystick position
  30830. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30831. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30832. // origin joystick position
  30833. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30834. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30835. this._onPointerDownHandlerRef = function (evt) {
  30836. _this._onPointerDown(evt);
  30837. };
  30838. this._onPointerMoveHandlerRef = function (evt) {
  30839. _this._onPointerMove(evt);
  30840. };
  30841. this._onPointerOutHandlerRef = function (evt) {
  30842. _this._onPointerUp(evt);
  30843. };
  30844. this._onPointerUpHandlerRef = function (evt) {
  30845. _this._onPointerUp(evt);
  30846. };
  30847. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30848. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30849. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30850. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30851. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30852. evt.preventDefault(); // Disables system menu
  30853. }, false);
  30854. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30855. }
  30856. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30857. this._joystickSensibility = newJoystickSensibility;
  30858. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30859. };
  30860. VirtualJoystick.prototype._onPointerDown = function (e) {
  30861. var positionOnScreenCondition;
  30862. e.preventDefault();
  30863. if (this._leftJoystick === true) {
  30864. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30865. }
  30866. else {
  30867. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30868. }
  30869. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30870. // First contact will be dedicated to the virtual joystick
  30871. this._joystickPointerID = e.pointerId;
  30872. this._joystickPointerStartPos.x = e.clientX;
  30873. this._joystickPointerStartPos.y = e.clientY;
  30874. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30875. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30876. this._deltaJoystickVector.x = 0;
  30877. this._deltaJoystickVector.y = 0;
  30878. this.pressed = true;
  30879. this._touches.add(e.pointerId.toString(), e);
  30880. }
  30881. else {
  30882. // You can only trigger the action buttons with a joystick declared
  30883. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30884. this._action();
  30885. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30886. }
  30887. }
  30888. };
  30889. VirtualJoystick.prototype._onPointerMove = function (e) {
  30890. // If the current pointer is the one associated to the joystick (first touch contact)
  30891. if (this._joystickPointerID == e.pointerId) {
  30892. this._joystickPointerPos.x = e.clientX;
  30893. this._joystickPointerPos.y = e.clientY;
  30894. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30895. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30896. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30897. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30898. switch (this._axisTargetedByLeftAndRight) {
  30899. case JoystickAxis.X:
  30900. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30901. break;
  30902. case JoystickAxis.Y:
  30903. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30904. break;
  30905. case JoystickAxis.Z:
  30906. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30907. break;
  30908. }
  30909. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30910. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30911. switch (this._axisTargetedByUpAndDown) {
  30912. case JoystickAxis.X:
  30913. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30914. break;
  30915. case JoystickAxis.Y:
  30916. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30917. break;
  30918. case JoystickAxis.Z:
  30919. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30920. break;
  30921. }
  30922. }
  30923. else {
  30924. if (this._touches.item(e.pointerId.toString())) {
  30925. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30926. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30927. }
  30928. }
  30929. };
  30930. VirtualJoystick.prototype._onPointerUp = function (e) {
  30931. if (this._joystickPointerID == e.pointerId) {
  30932. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30933. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30934. this._joystickPointerID = -1;
  30935. this.pressed = false;
  30936. }
  30937. else {
  30938. var touch = this._touches.item(e.pointerId.toString());
  30939. if (touch) {
  30940. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30941. }
  30942. }
  30943. this._deltaJoystickVector.x = 0;
  30944. this._deltaJoystickVector.y = 0;
  30945. this._touches.remove(e.pointerId.toString());
  30946. };
  30947. /**
  30948. * Change the color of the virtual joystick
  30949. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30950. */
  30951. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30952. this._joystickColor = newColor;
  30953. };
  30954. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30955. this._action = action;
  30956. };
  30957. // Define which axis you'd like to control for left & right
  30958. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30959. switch (axis) {
  30960. case JoystickAxis.X:
  30961. case JoystickAxis.Y:
  30962. case JoystickAxis.Z:
  30963. this._axisTargetedByLeftAndRight = axis;
  30964. break;
  30965. default:
  30966. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30967. break;
  30968. }
  30969. };
  30970. // Define which axis you'd like to control for up & down
  30971. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30972. switch (axis) {
  30973. case JoystickAxis.X:
  30974. case JoystickAxis.Y:
  30975. case JoystickAxis.Z:
  30976. this._axisTargetedByUpAndDown = axis;
  30977. break;
  30978. default:
  30979. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30980. break;
  30981. }
  30982. };
  30983. VirtualJoystick.prototype._clearCanvas = function () {
  30984. if (this._leftJoystick) {
  30985. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30986. }
  30987. else {
  30988. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30989. }
  30990. };
  30991. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30992. var _this = this;
  30993. if (this.pressed) {
  30994. this._touches.forEach(function (touch) {
  30995. if (touch.pointerId === _this._joystickPointerID) {
  30996. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30997. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30998. VirtualJoystick.vjCanvasContext.beginPath();
  30999. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31000. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31001. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31002. VirtualJoystick.vjCanvasContext.stroke();
  31003. VirtualJoystick.vjCanvasContext.closePath();
  31004. VirtualJoystick.vjCanvasContext.beginPath();
  31005. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31006. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31007. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31008. VirtualJoystick.vjCanvasContext.stroke();
  31009. VirtualJoystick.vjCanvasContext.closePath();
  31010. VirtualJoystick.vjCanvasContext.beginPath();
  31011. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31012. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31013. VirtualJoystick.vjCanvasContext.stroke();
  31014. VirtualJoystick.vjCanvasContext.closePath();
  31015. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31016. }
  31017. else {
  31018. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31019. VirtualJoystick.vjCanvasContext.beginPath();
  31020. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31021. VirtualJoystick.vjCanvasContext.beginPath();
  31022. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31023. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31024. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31025. VirtualJoystick.vjCanvasContext.stroke();
  31026. VirtualJoystick.vjCanvasContext.closePath();
  31027. touch.prevX = touch.x;
  31028. touch.prevY = touch.y;
  31029. }
  31030. ;
  31031. });
  31032. }
  31033. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31034. };
  31035. VirtualJoystick.prototype.releaseCanvas = function () {
  31036. if (VirtualJoystick.vjCanvas) {
  31037. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31038. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31039. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31040. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31041. window.removeEventListener("resize", this._onResize);
  31042. document.body.removeChild(VirtualJoystick.vjCanvas);
  31043. VirtualJoystick.vjCanvas = null;
  31044. }
  31045. };
  31046. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31047. VirtualJoystick._globalJoystickIndex = 0;
  31048. return VirtualJoystick;
  31049. })();
  31050. BABYLON.VirtualJoystick = VirtualJoystick;
  31051. })(BABYLON || (BABYLON = {}));
  31052. var BABYLON;
  31053. (function (BABYLON) {
  31054. // We're mainly based on the logic defined into the FreeCamera code
  31055. var VirtualJoysticksCamera = (function (_super) {
  31056. __extends(VirtualJoysticksCamera, _super);
  31057. function VirtualJoysticksCamera(name, position, scene) {
  31058. _super.call(this, name, position, scene);
  31059. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31060. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31061. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31062. this._leftjoystick.setJoystickSensibility(0.15);
  31063. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31064. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31065. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31066. this._rightjoystick.reverseUpDown = true;
  31067. this._rightjoystick.setJoystickSensibility(0.05);
  31068. this._rightjoystick.setJoystickColor("yellow");
  31069. }
  31070. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31071. return this._leftjoystick;
  31072. };
  31073. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31074. return this._rightjoystick;
  31075. };
  31076. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31077. var speed = this._computeLocalCameraSpeed() * 50;
  31078. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31079. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31080. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31081. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31082. if (!this._leftjoystick.pressed) {
  31083. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31084. }
  31085. if (!this._rightjoystick.pressed) {
  31086. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31087. }
  31088. _super.prototype._checkInputs.call(this);
  31089. };
  31090. VirtualJoysticksCamera.prototype.dispose = function () {
  31091. this._leftjoystick.releaseCanvas();
  31092. _super.prototype.dispose.call(this);
  31093. };
  31094. return VirtualJoysticksCamera;
  31095. })(BABYLON.FreeCamera);
  31096. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31097. })(BABYLON || (BABYLON = {}));
  31098. var BABYLON;
  31099. (function (BABYLON) {
  31100. var AnaglyphPostProcess = (function (_super) {
  31101. __extends(AnaglyphPostProcess, _super);
  31102. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31103. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31104. }
  31105. return AnaglyphPostProcess;
  31106. })(BABYLON.PostProcess);
  31107. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31108. })(BABYLON || (BABYLON = {}));
  31109. var BABYLON;
  31110. (function (BABYLON) {
  31111. var OutlineRenderer = (function () {
  31112. function OutlineRenderer(scene) {
  31113. this._scene = scene;
  31114. }
  31115. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31116. var _this = this;
  31117. if (useOverlay === void 0) { useOverlay = false; }
  31118. var scene = this._scene;
  31119. var engine = this._scene.getEngine();
  31120. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31121. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31122. return;
  31123. }
  31124. var mesh = subMesh.getRenderingMesh();
  31125. var material = subMesh.getMaterial();
  31126. engine.enableEffect(this._effect);
  31127. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31128. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31129. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31130. // Bones
  31131. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31132. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31133. }
  31134. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31135. // Alpha test
  31136. if (material && material.needAlphaTesting()) {
  31137. var alphaTexture = material.getAlphaTestTexture();
  31138. this._effect.setTexture("diffuseSampler", alphaTexture);
  31139. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31140. }
  31141. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31142. };
  31143. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31144. var defines = [];
  31145. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31146. var mesh = subMesh.getMesh();
  31147. var material = subMesh.getMaterial();
  31148. // Alpha test
  31149. if (material && material.needAlphaTesting()) {
  31150. defines.push("#define ALPHATEST");
  31151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31152. attribs.push(BABYLON.VertexBuffer.UVKind);
  31153. defines.push("#define UV1");
  31154. }
  31155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31156. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31157. defines.push("#define UV2");
  31158. }
  31159. }
  31160. // Bones
  31161. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31164. if (mesh.numBoneInfluencers > 4) {
  31165. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31166. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31167. }
  31168. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31169. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31170. }
  31171. else {
  31172. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31173. }
  31174. // Instances
  31175. if (useInstances) {
  31176. defines.push("#define INSTANCES");
  31177. attribs.push("world0");
  31178. attribs.push("world1");
  31179. attribs.push("world2");
  31180. attribs.push("world3");
  31181. }
  31182. // Get correct effect
  31183. var join = defines.join("\n");
  31184. if (this._cachedDefines !== join) {
  31185. this._cachedDefines = join;
  31186. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31187. }
  31188. return this._effect.isReady();
  31189. };
  31190. return OutlineRenderer;
  31191. })();
  31192. BABYLON.OutlineRenderer = OutlineRenderer;
  31193. })(BABYLON || (BABYLON = {}));
  31194. var BABYLON;
  31195. (function (BABYLON) {
  31196. var MeshAssetTask = (function () {
  31197. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31198. this.name = name;
  31199. this.meshesNames = meshesNames;
  31200. this.rootUrl = rootUrl;
  31201. this.sceneFilename = sceneFilename;
  31202. this.isCompleted = false;
  31203. }
  31204. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31205. var _this = this;
  31206. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31207. _this.loadedMeshes = meshes;
  31208. _this.loadedParticleSystems = particleSystems;
  31209. _this.loadedSkeletons = skeletons;
  31210. _this.isCompleted = true;
  31211. if (_this.onSuccess) {
  31212. _this.onSuccess(_this);
  31213. }
  31214. onSuccess();
  31215. }, null, function () {
  31216. if (_this.onError) {
  31217. _this.onError(_this);
  31218. }
  31219. onError();
  31220. });
  31221. };
  31222. return MeshAssetTask;
  31223. })();
  31224. BABYLON.MeshAssetTask = MeshAssetTask;
  31225. var TextFileAssetTask = (function () {
  31226. function TextFileAssetTask(name, url) {
  31227. this.name = name;
  31228. this.url = url;
  31229. this.isCompleted = false;
  31230. }
  31231. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31232. var _this = this;
  31233. BABYLON.Tools.LoadFile(this.url, function (data) {
  31234. _this.text = data;
  31235. _this.isCompleted = true;
  31236. if (_this.onSuccess) {
  31237. _this.onSuccess(_this);
  31238. }
  31239. onSuccess();
  31240. }, null, scene.database, false, function () {
  31241. if (_this.onError) {
  31242. _this.onError(_this);
  31243. }
  31244. onError();
  31245. });
  31246. };
  31247. return TextFileAssetTask;
  31248. })();
  31249. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31250. var BinaryFileAssetTask = (function () {
  31251. function BinaryFileAssetTask(name, url) {
  31252. this.name = name;
  31253. this.url = url;
  31254. this.isCompleted = false;
  31255. }
  31256. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31257. var _this = this;
  31258. BABYLON.Tools.LoadFile(this.url, function (data) {
  31259. _this.data = data;
  31260. _this.isCompleted = true;
  31261. if (_this.onSuccess) {
  31262. _this.onSuccess(_this);
  31263. }
  31264. onSuccess();
  31265. }, null, scene.database, true, function () {
  31266. if (_this.onError) {
  31267. _this.onError(_this);
  31268. }
  31269. onError();
  31270. });
  31271. };
  31272. return BinaryFileAssetTask;
  31273. })();
  31274. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31275. var ImageAssetTask = (function () {
  31276. function ImageAssetTask(name, url) {
  31277. this.name = name;
  31278. this.url = url;
  31279. this.isCompleted = false;
  31280. }
  31281. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31282. var _this = this;
  31283. var img = new Image();
  31284. img.onload = function () {
  31285. _this.image = img;
  31286. _this.isCompleted = true;
  31287. if (_this.onSuccess) {
  31288. _this.onSuccess(_this);
  31289. }
  31290. onSuccess();
  31291. };
  31292. img.onerror = function () {
  31293. if (_this.onError) {
  31294. _this.onError(_this);
  31295. }
  31296. onError();
  31297. };
  31298. img.src = this.url;
  31299. };
  31300. return ImageAssetTask;
  31301. })();
  31302. BABYLON.ImageAssetTask = ImageAssetTask;
  31303. var TextureAssetTask = (function () {
  31304. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31306. this.name = name;
  31307. this.url = url;
  31308. this.noMipmap = noMipmap;
  31309. this.invertY = invertY;
  31310. this.samplingMode = samplingMode;
  31311. this.isCompleted = false;
  31312. }
  31313. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31314. var _this = this;
  31315. var onload = function () {
  31316. _this.isCompleted = true;
  31317. if (_this.onSuccess) {
  31318. _this.onSuccess(_this);
  31319. }
  31320. onSuccess();
  31321. };
  31322. var onerror = function () {
  31323. if (_this.onError) {
  31324. _this.onError(_this);
  31325. }
  31326. onError();
  31327. };
  31328. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31329. };
  31330. return TextureAssetTask;
  31331. })();
  31332. BABYLON.TextureAssetTask = TextureAssetTask;
  31333. var AssetsManager = (function () {
  31334. function AssetsManager(scene) {
  31335. this._tasks = new Array();
  31336. this._waitingTasksCount = 0;
  31337. this.useDefaultLoadingScreen = true;
  31338. this._scene = scene;
  31339. }
  31340. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31341. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31342. this._tasks.push(task);
  31343. return task;
  31344. };
  31345. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31346. var task = new TextFileAssetTask(taskName, url);
  31347. this._tasks.push(task);
  31348. return task;
  31349. };
  31350. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31351. var task = new BinaryFileAssetTask(taskName, url);
  31352. this._tasks.push(task);
  31353. return task;
  31354. };
  31355. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31356. var task = new ImageAssetTask(taskName, url);
  31357. this._tasks.push(task);
  31358. return task;
  31359. };
  31360. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31362. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31363. this._tasks.push(task);
  31364. return task;
  31365. };
  31366. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31367. this._waitingTasksCount--;
  31368. if (this._waitingTasksCount === 0) {
  31369. if (this.onFinish) {
  31370. this.onFinish(this._tasks);
  31371. }
  31372. this._scene.getEngine().hideLoadingUI();
  31373. }
  31374. };
  31375. AssetsManager.prototype._runTask = function (task) {
  31376. var _this = this;
  31377. task.run(this._scene, function () {
  31378. if (_this.onTaskSuccess) {
  31379. _this.onTaskSuccess(task);
  31380. }
  31381. _this._decreaseWaitingTasksCount();
  31382. }, function () {
  31383. if (_this.onTaskError) {
  31384. _this.onTaskError(task);
  31385. }
  31386. _this._decreaseWaitingTasksCount();
  31387. });
  31388. };
  31389. AssetsManager.prototype.reset = function () {
  31390. this._tasks = new Array();
  31391. return this;
  31392. };
  31393. AssetsManager.prototype.load = function () {
  31394. this._waitingTasksCount = this._tasks.length;
  31395. if (this._waitingTasksCount === 0) {
  31396. if (this.onFinish) {
  31397. this.onFinish(this._tasks);
  31398. }
  31399. return this;
  31400. }
  31401. if (this.useDefaultLoadingScreen) {
  31402. this._scene.getEngine().displayLoadingUI();
  31403. }
  31404. for (var index = 0; index < this._tasks.length; index++) {
  31405. var task = this._tasks[index];
  31406. this._runTask(task);
  31407. }
  31408. return this;
  31409. };
  31410. return AssetsManager;
  31411. })();
  31412. BABYLON.AssetsManager = AssetsManager;
  31413. })(BABYLON || (BABYLON = {}));
  31414. var BABYLON;
  31415. (function (BABYLON) {
  31416. var VRDeviceOrientationFreeCamera = (function (_super) {
  31417. __extends(VRDeviceOrientationFreeCamera, _super);
  31418. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31419. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31420. _super.call(this, name, position, scene);
  31421. this._alpha = 0;
  31422. this._beta = 0;
  31423. this._gamma = 0;
  31424. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31425. metrics.compensateDistortion = compensateDistortion;
  31426. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31427. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31428. }
  31429. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31430. this._alpha = +evt.alpha | 0;
  31431. this._beta = +evt.beta | 0;
  31432. this._gamma = +evt.gamma | 0;
  31433. if (this._gamma < 0) {
  31434. this._gamma = 90 + this._gamma;
  31435. }
  31436. else {
  31437. // Incline it in the correct angle.
  31438. this._gamma = 270 - this._gamma;
  31439. }
  31440. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31441. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31442. this.rotation.z = this._beta / 180.0 * Math.PI;
  31443. };
  31444. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31445. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31446. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31447. };
  31448. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31449. _super.prototype.detachControl.call(this, element);
  31450. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31451. };
  31452. return VRDeviceOrientationFreeCamera;
  31453. })(BABYLON.FreeCamera);
  31454. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31455. })(BABYLON || (BABYLON = {}));
  31456. var BABYLON;
  31457. (function (BABYLON) {
  31458. var WebVRFreeCamera = (function (_super) {
  31459. __extends(WebVRFreeCamera, _super);
  31460. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31461. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31462. _super.call(this, name, position, scene);
  31463. this._hmdDevice = null;
  31464. this._sensorDevice = null;
  31465. this._cacheState = null;
  31466. this._cacheQuaternion = new BABYLON.Quaternion();
  31467. this._cacheRotation = BABYLON.Vector3.Zero();
  31468. this._vrEnabled = false;
  31469. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31470. metrics.compensateDistortion = compensateDistortion;
  31471. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31472. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31473. }
  31474. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31475. var size = devices.length;
  31476. var i = 0;
  31477. // Reset devices.
  31478. this._sensorDevice = null;
  31479. this._hmdDevice = null;
  31480. // Search for a HmdDevice.
  31481. while (i < size && this._hmdDevice === null) {
  31482. if (devices[i] instanceof HMDVRDevice) {
  31483. this._hmdDevice = devices[i];
  31484. }
  31485. i++;
  31486. }
  31487. i = 0;
  31488. while (i < size && this._sensorDevice === null) {
  31489. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31490. this._sensorDevice = devices[i];
  31491. }
  31492. i++;
  31493. }
  31494. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31495. };
  31496. WebVRFreeCamera.prototype._checkInputs = function () {
  31497. if (this._vrEnabled) {
  31498. this._cacheState = this._sensorDevice.getState();
  31499. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31500. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31501. this.rotation.x = -this._cacheRotation.z;
  31502. this.rotation.y = -this._cacheRotation.y;
  31503. this.rotation.z = this._cacheRotation.x;
  31504. }
  31505. _super.prototype._checkInputs.call(this);
  31506. };
  31507. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31508. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31509. if (navigator.getVRDevices) {
  31510. navigator.getVRDevices().then(this._getWebVRDevices);
  31511. }
  31512. else if (navigator.mozGetVRDevices) {
  31513. navigator.mozGetVRDevices(this._getWebVRDevices);
  31514. }
  31515. };
  31516. WebVRFreeCamera.prototype.detachControl = function (element) {
  31517. _super.prototype.detachControl.call(this, element);
  31518. this._vrEnabled = false;
  31519. };
  31520. return WebVRFreeCamera;
  31521. })(BABYLON.FreeCamera);
  31522. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31523. })(BABYLON || (BABYLON = {}));
  31524. var BABYLON;
  31525. (function (BABYLON) {
  31526. // Standard optimizations
  31527. var SceneOptimization = (function () {
  31528. function SceneOptimization(priority) {
  31529. if (priority === void 0) { priority = 0; }
  31530. this.priority = priority;
  31531. this.apply = function (scene) {
  31532. return true; // Return true if everything that can be done was applied
  31533. };
  31534. }
  31535. return SceneOptimization;
  31536. })();
  31537. BABYLON.SceneOptimization = SceneOptimization;
  31538. var TextureOptimization = (function (_super) {
  31539. __extends(TextureOptimization, _super);
  31540. function TextureOptimization(priority, maximumSize) {
  31541. var _this = this;
  31542. if (priority === void 0) { priority = 0; }
  31543. if (maximumSize === void 0) { maximumSize = 1024; }
  31544. _super.call(this, priority);
  31545. this.priority = priority;
  31546. this.maximumSize = maximumSize;
  31547. this.apply = function (scene) {
  31548. var allDone = true;
  31549. for (var index = 0; index < scene.textures.length; index++) {
  31550. var texture = scene.textures[index];
  31551. if (!texture.canRescale) {
  31552. continue;
  31553. }
  31554. var currentSize = texture.getSize();
  31555. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31556. if (maxDimension > _this.maximumSize) {
  31557. texture.scale(0.5);
  31558. allDone = false;
  31559. }
  31560. }
  31561. return allDone;
  31562. };
  31563. }
  31564. return TextureOptimization;
  31565. })(SceneOptimization);
  31566. BABYLON.TextureOptimization = TextureOptimization;
  31567. var HardwareScalingOptimization = (function (_super) {
  31568. __extends(HardwareScalingOptimization, _super);
  31569. function HardwareScalingOptimization(priority, maximumScale) {
  31570. var _this = this;
  31571. if (priority === void 0) { priority = 0; }
  31572. if (maximumScale === void 0) { maximumScale = 2; }
  31573. _super.call(this, priority);
  31574. this.priority = priority;
  31575. this.maximumScale = maximumScale;
  31576. this._currentScale = 1;
  31577. this.apply = function (scene) {
  31578. _this._currentScale++;
  31579. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31580. return _this._currentScale >= _this.maximumScale;
  31581. };
  31582. }
  31583. return HardwareScalingOptimization;
  31584. })(SceneOptimization);
  31585. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31586. var ShadowsOptimization = (function (_super) {
  31587. __extends(ShadowsOptimization, _super);
  31588. function ShadowsOptimization() {
  31589. _super.apply(this, arguments);
  31590. this.apply = function (scene) {
  31591. scene.shadowsEnabled = false;
  31592. return true;
  31593. };
  31594. }
  31595. return ShadowsOptimization;
  31596. })(SceneOptimization);
  31597. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31598. var PostProcessesOptimization = (function (_super) {
  31599. __extends(PostProcessesOptimization, _super);
  31600. function PostProcessesOptimization() {
  31601. _super.apply(this, arguments);
  31602. this.apply = function (scene) {
  31603. scene.postProcessesEnabled = false;
  31604. return true;
  31605. };
  31606. }
  31607. return PostProcessesOptimization;
  31608. })(SceneOptimization);
  31609. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31610. var LensFlaresOptimization = (function (_super) {
  31611. __extends(LensFlaresOptimization, _super);
  31612. function LensFlaresOptimization() {
  31613. _super.apply(this, arguments);
  31614. this.apply = function (scene) {
  31615. scene.lensFlaresEnabled = false;
  31616. return true;
  31617. };
  31618. }
  31619. return LensFlaresOptimization;
  31620. })(SceneOptimization);
  31621. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31622. var ParticlesOptimization = (function (_super) {
  31623. __extends(ParticlesOptimization, _super);
  31624. function ParticlesOptimization() {
  31625. _super.apply(this, arguments);
  31626. this.apply = function (scene) {
  31627. scene.particlesEnabled = false;
  31628. return true;
  31629. };
  31630. }
  31631. return ParticlesOptimization;
  31632. })(SceneOptimization);
  31633. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31634. var RenderTargetsOptimization = (function (_super) {
  31635. __extends(RenderTargetsOptimization, _super);
  31636. function RenderTargetsOptimization() {
  31637. _super.apply(this, arguments);
  31638. this.apply = function (scene) {
  31639. scene.renderTargetsEnabled = false;
  31640. return true;
  31641. };
  31642. }
  31643. return RenderTargetsOptimization;
  31644. })(SceneOptimization);
  31645. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31646. var MergeMeshesOptimization = (function (_super) {
  31647. __extends(MergeMeshesOptimization, _super);
  31648. function MergeMeshesOptimization() {
  31649. var _this = this;
  31650. _super.apply(this, arguments);
  31651. this._canBeMerged = function (abstractMesh) {
  31652. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31653. return false;
  31654. }
  31655. var mesh = abstractMesh;
  31656. if (!mesh.isVisible || !mesh.isEnabled()) {
  31657. return false;
  31658. }
  31659. if (mesh.instances.length > 0) {
  31660. return false;
  31661. }
  31662. if (mesh.skeleton || mesh.hasLODLevels) {
  31663. return false;
  31664. }
  31665. if (mesh.parent) {
  31666. return false;
  31667. }
  31668. return true;
  31669. };
  31670. this.apply = function (scene, updateSelectionTree) {
  31671. var globalPool = scene.meshes.slice(0);
  31672. var globalLength = globalPool.length;
  31673. for (var index = 0; index < globalLength; index++) {
  31674. var currentPool = new Array();
  31675. var current = globalPool[index];
  31676. // Checks
  31677. if (!_this._canBeMerged(current)) {
  31678. continue;
  31679. }
  31680. currentPool.push(current);
  31681. // Find compatible meshes
  31682. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31683. var otherMesh = globalPool[subIndex];
  31684. if (!_this._canBeMerged(otherMesh)) {
  31685. continue;
  31686. }
  31687. if (otherMesh.material !== current.material) {
  31688. continue;
  31689. }
  31690. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31691. continue;
  31692. }
  31693. currentPool.push(otherMesh);
  31694. globalLength--;
  31695. globalPool.splice(subIndex, 1);
  31696. subIndex--;
  31697. }
  31698. if (currentPool.length < 2) {
  31699. continue;
  31700. }
  31701. // Merge meshes
  31702. BABYLON.Mesh.MergeMeshes(currentPool);
  31703. }
  31704. if (updateSelectionTree != undefined) {
  31705. if (updateSelectionTree) {
  31706. scene.createOrUpdateSelectionOctree();
  31707. }
  31708. }
  31709. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31710. scene.createOrUpdateSelectionOctree();
  31711. }
  31712. return true;
  31713. };
  31714. }
  31715. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31716. get: function () {
  31717. return MergeMeshesOptimization._UpdateSelectionTree;
  31718. },
  31719. set: function (value) {
  31720. MergeMeshesOptimization._UpdateSelectionTree = value;
  31721. },
  31722. enumerable: true,
  31723. configurable: true
  31724. });
  31725. MergeMeshesOptimization._UpdateSelectionTree = false;
  31726. return MergeMeshesOptimization;
  31727. })(SceneOptimization);
  31728. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31729. // Options
  31730. var SceneOptimizerOptions = (function () {
  31731. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31732. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31733. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31734. this.targetFrameRate = targetFrameRate;
  31735. this.trackerDuration = trackerDuration;
  31736. this.optimizations = new Array();
  31737. }
  31738. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31739. var result = new SceneOptimizerOptions(targetFrameRate);
  31740. var priority = 0;
  31741. result.optimizations.push(new MergeMeshesOptimization(priority));
  31742. result.optimizations.push(new ShadowsOptimization(priority));
  31743. result.optimizations.push(new LensFlaresOptimization(priority));
  31744. // Next priority
  31745. priority++;
  31746. result.optimizations.push(new PostProcessesOptimization(priority));
  31747. result.optimizations.push(new ParticlesOptimization(priority));
  31748. // Next priority
  31749. priority++;
  31750. result.optimizations.push(new TextureOptimization(priority, 1024));
  31751. return result;
  31752. };
  31753. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31754. var result = new SceneOptimizerOptions(targetFrameRate);
  31755. var priority = 0;
  31756. result.optimizations.push(new MergeMeshesOptimization(priority));
  31757. result.optimizations.push(new ShadowsOptimization(priority));
  31758. result.optimizations.push(new LensFlaresOptimization(priority));
  31759. // Next priority
  31760. priority++;
  31761. result.optimizations.push(new PostProcessesOptimization(priority));
  31762. result.optimizations.push(new ParticlesOptimization(priority));
  31763. // Next priority
  31764. priority++;
  31765. result.optimizations.push(new TextureOptimization(priority, 512));
  31766. // Next priority
  31767. priority++;
  31768. result.optimizations.push(new RenderTargetsOptimization(priority));
  31769. // Next priority
  31770. priority++;
  31771. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31772. return result;
  31773. };
  31774. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31775. var result = new SceneOptimizerOptions(targetFrameRate);
  31776. var priority = 0;
  31777. result.optimizations.push(new MergeMeshesOptimization(priority));
  31778. result.optimizations.push(new ShadowsOptimization(priority));
  31779. result.optimizations.push(new LensFlaresOptimization(priority));
  31780. // Next priority
  31781. priority++;
  31782. result.optimizations.push(new PostProcessesOptimization(priority));
  31783. result.optimizations.push(new ParticlesOptimization(priority));
  31784. // Next priority
  31785. priority++;
  31786. result.optimizations.push(new TextureOptimization(priority, 256));
  31787. // Next priority
  31788. priority++;
  31789. result.optimizations.push(new RenderTargetsOptimization(priority));
  31790. // Next priority
  31791. priority++;
  31792. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31793. return result;
  31794. };
  31795. return SceneOptimizerOptions;
  31796. })();
  31797. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31798. // Scene optimizer tool
  31799. var SceneOptimizer = (function () {
  31800. function SceneOptimizer() {
  31801. }
  31802. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31803. // TODO: add an epsilon
  31804. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31805. if (onSuccess) {
  31806. onSuccess();
  31807. }
  31808. return;
  31809. }
  31810. // Apply current level of optimizations
  31811. var allDone = true;
  31812. var noOptimizationApplied = true;
  31813. for (var index = 0; index < options.optimizations.length; index++) {
  31814. var optimization = options.optimizations[index];
  31815. if (optimization.priority === currentPriorityLevel) {
  31816. noOptimizationApplied = false;
  31817. allDone = allDone && optimization.apply(scene);
  31818. }
  31819. }
  31820. // If no optimization was applied, this is a failure :(
  31821. if (noOptimizationApplied) {
  31822. if (onFailure) {
  31823. onFailure();
  31824. }
  31825. return;
  31826. }
  31827. // If all optimizations were done, move to next level
  31828. if (allDone) {
  31829. currentPriorityLevel++;
  31830. }
  31831. // Let's the system running for a specific amount of time before checking FPS
  31832. scene.executeWhenReady(function () {
  31833. setTimeout(function () {
  31834. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31835. }, options.trackerDuration);
  31836. });
  31837. };
  31838. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31839. if (!options) {
  31840. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31841. }
  31842. // Let's the system running for a specific amount of time before checking FPS
  31843. scene.executeWhenReady(function () {
  31844. setTimeout(function () {
  31845. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31846. }, options.trackerDuration);
  31847. });
  31848. };
  31849. return SceneOptimizer;
  31850. })();
  31851. BABYLON.SceneOptimizer = SceneOptimizer;
  31852. })(BABYLON || (BABYLON = {}));
  31853. var BABYLON;
  31854. (function (BABYLON) {
  31855. var Internals;
  31856. (function (Internals) {
  31857. var MeshLODLevel = (function () {
  31858. function MeshLODLevel(distance, mesh) {
  31859. this.distance = distance;
  31860. this.mesh = mesh;
  31861. }
  31862. return MeshLODLevel;
  31863. })();
  31864. Internals.MeshLODLevel = MeshLODLevel;
  31865. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31866. })(BABYLON || (BABYLON = {}));
  31867. var BABYLON;
  31868. (function (BABYLON) {
  31869. var RawTexture = (function (_super) {
  31870. __extends(RawTexture, _super);
  31871. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31873. if (invertY === void 0) { invertY = false; }
  31874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31875. _super.call(this, null, scene, !generateMipMaps, invertY);
  31876. this.format = format;
  31877. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31878. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31879. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31880. }
  31881. RawTexture.prototype.update = function (data) {
  31882. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31883. };
  31884. // Statics
  31885. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31886. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31887. if (invertY === void 0) { invertY = false; }
  31888. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31889. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31890. };
  31891. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31892. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31893. if (invertY === void 0) { invertY = false; }
  31894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31895. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31896. };
  31897. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31898. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31899. if (invertY === void 0) { invertY = false; }
  31900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31901. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31902. };
  31903. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31904. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31905. if (invertY === void 0) { invertY = false; }
  31906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31907. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31908. };
  31909. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31910. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31911. if (invertY === void 0) { invertY = false; }
  31912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31913. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31914. };
  31915. return RawTexture;
  31916. })(BABYLON.Texture);
  31917. BABYLON.RawTexture = RawTexture;
  31918. })(BABYLON || (BABYLON = {}));
  31919. var BABYLON;
  31920. (function (BABYLON) {
  31921. var IndexedVector2 = (function (_super) {
  31922. __extends(IndexedVector2, _super);
  31923. function IndexedVector2(original, index) {
  31924. _super.call(this, original.x, original.y);
  31925. this.index = index;
  31926. }
  31927. return IndexedVector2;
  31928. })(BABYLON.Vector2);
  31929. var PolygonPoints = (function () {
  31930. function PolygonPoints() {
  31931. this.elements = new Array();
  31932. }
  31933. PolygonPoints.prototype.add = function (originalPoints) {
  31934. var _this = this;
  31935. var result = new Array();
  31936. originalPoints.forEach(function (point) {
  31937. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31938. var newPoint = new IndexedVector2(point, _this.elements.length);
  31939. result.push(newPoint);
  31940. _this.elements.push(newPoint);
  31941. }
  31942. });
  31943. return result;
  31944. };
  31945. PolygonPoints.prototype.computeBounds = function () {
  31946. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31947. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31948. this.elements.forEach(function (point) {
  31949. // x
  31950. if (point.x < lmin.x) {
  31951. lmin.x = point.x;
  31952. }
  31953. else if (point.x > lmax.x) {
  31954. lmax.x = point.x;
  31955. }
  31956. // y
  31957. if (point.y < lmin.y) {
  31958. lmin.y = point.y;
  31959. }
  31960. else if (point.y > lmax.y) {
  31961. lmax.y = point.y;
  31962. }
  31963. });
  31964. return {
  31965. min: lmin,
  31966. max: lmax,
  31967. width: lmax.x - lmin.x,
  31968. height: lmax.y - lmin.y
  31969. };
  31970. };
  31971. return PolygonPoints;
  31972. })();
  31973. var Polygon = (function () {
  31974. function Polygon() {
  31975. }
  31976. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31977. return [
  31978. new BABYLON.Vector2(xmin, ymin),
  31979. new BABYLON.Vector2(xmax, ymin),
  31980. new BABYLON.Vector2(xmax, ymax),
  31981. new BABYLON.Vector2(xmin, ymax)
  31982. ];
  31983. };
  31984. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31985. if (cx === void 0) { cx = 0; }
  31986. if (cy === void 0) { cy = 0; }
  31987. if (numberOfSides === void 0) { numberOfSides = 32; }
  31988. var result = new Array();
  31989. var angle = 0;
  31990. var increment = (Math.PI * 2) / numberOfSides;
  31991. for (var i = 0; i < numberOfSides; i++) {
  31992. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31993. angle -= increment;
  31994. }
  31995. return result;
  31996. };
  31997. Polygon.Parse = function (input) {
  31998. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31999. var i, result = [];
  32000. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32001. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32002. }
  32003. return result;
  32004. };
  32005. Polygon.StartingAt = function (x, y) {
  32006. return BABYLON.Path2.StartingAt(x, y);
  32007. };
  32008. return Polygon;
  32009. })();
  32010. BABYLON.Polygon = Polygon;
  32011. var PolygonMeshBuilder = (function () {
  32012. function PolygonMeshBuilder(name, contours, scene) {
  32013. this._points = new PolygonPoints();
  32014. this._outlinepoints = new PolygonPoints();
  32015. this._holes = [];
  32016. if (!("poly2tri" in window)) {
  32017. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32018. }
  32019. this._name = name;
  32020. this._scene = scene;
  32021. var points;
  32022. if (contours instanceof BABYLON.Path2) {
  32023. points = contours.getPoints();
  32024. }
  32025. else {
  32026. points = contours;
  32027. }
  32028. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32029. this._outlinepoints.add(points);
  32030. }
  32031. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32032. this._swctx.addHole(this._points.add(hole));
  32033. var holepoints = new PolygonPoints();
  32034. holepoints.add(hole);
  32035. this._holes.push(holepoints);
  32036. return this;
  32037. };
  32038. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32039. var _this = this;
  32040. if (updatable === void 0) { updatable = false; }
  32041. var result = new BABYLON.Mesh(this._name, this._scene);
  32042. var normals = [];
  32043. var positions = [];
  32044. var uvs = [];
  32045. var bounds = this._points.computeBounds();
  32046. this._points.elements.forEach(function (p) {
  32047. normals.push(0, 1.0, 0);
  32048. positions.push(p.x, 0, p.y);
  32049. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32050. });
  32051. var indices = [];
  32052. this._swctx.triangulate();
  32053. this._swctx.getTriangles().forEach(function (triangle) {
  32054. triangle.getPoints().forEach(function (point) {
  32055. indices.push(point.index);
  32056. });
  32057. });
  32058. if (depth > 0) {
  32059. var positionscount = (positions.length / 3); //get the current pointcount
  32060. this._points.elements.forEach(function (p) {
  32061. normals.push(0, -1.0, 0);
  32062. positions.push(p.x, -depth, p.y);
  32063. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32064. });
  32065. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32066. var p2;
  32067. var poscounter = 0;
  32068. this._swctx.getTriangles().forEach(function (triangle) {
  32069. triangle.getPoints().forEach(function (point) {
  32070. switch (poscounter) {
  32071. case 0:
  32072. p1 = point;
  32073. break;
  32074. case 1:
  32075. p2 = point;
  32076. break;
  32077. case 2:
  32078. indices.push(point.index + positionscount);
  32079. indices.push(p2.index + positionscount);
  32080. indices.push(p1.index + positionscount);
  32081. poscounter = -1;
  32082. break;
  32083. }
  32084. poscounter++;
  32085. //indices.push((<IndexedVector2>point).index + positionscount);
  32086. });
  32087. });
  32088. //Add the sides
  32089. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32090. this._holes.forEach(function (hole) {
  32091. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32092. });
  32093. }
  32094. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32095. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32096. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32097. result.setIndices(indices);
  32098. return result;
  32099. };
  32100. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32101. var StartIndex = positions.length / 3;
  32102. var ulength = 0;
  32103. for (var i = 0; i < points.elements.length; i++) {
  32104. var p = points.elements[i];
  32105. var p1;
  32106. if ((i + 1) > points.elements.length - 1) {
  32107. p1 = points.elements[0];
  32108. }
  32109. else {
  32110. p1 = points.elements[i + 1];
  32111. }
  32112. positions.push(p.x, 0, p.y);
  32113. positions.push(p.x, -depth, p.y);
  32114. positions.push(p1.x, 0, p1.y);
  32115. positions.push(p1.x, -depth, p1.y);
  32116. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32117. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32118. var v3 = v2.subtract(v1);
  32119. var v4 = new BABYLON.Vector3(0, 1, 0);
  32120. var vn = BABYLON.Vector3.Cross(v3, v4);
  32121. vn = vn.normalize();
  32122. uvs.push(ulength / bounds.width, 0);
  32123. uvs.push(ulength / bounds.width, 1);
  32124. ulength += v3.length();
  32125. uvs.push((ulength / bounds.width), 0);
  32126. uvs.push((ulength / bounds.width), 1);
  32127. if (!flip) {
  32128. normals.push(-vn.x, -vn.y, -vn.z);
  32129. normals.push(-vn.x, -vn.y, -vn.z);
  32130. normals.push(-vn.x, -vn.y, -vn.z);
  32131. normals.push(-vn.x, -vn.y, -vn.z);
  32132. indices.push(StartIndex);
  32133. indices.push(StartIndex + 1);
  32134. indices.push(StartIndex + 2);
  32135. indices.push(StartIndex + 1);
  32136. indices.push(StartIndex + 3);
  32137. indices.push(StartIndex + 2);
  32138. }
  32139. else {
  32140. normals.push(vn.x, vn.y, vn.z);
  32141. normals.push(vn.x, vn.y, vn.z);
  32142. normals.push(vn.x, vn.y, vn.z);
  32143. normals.push(vn.x, vn.y, vn.z);
  32144. indices.push(StartIndex);
  32145. indices.push(StartIndex + 2);
  32146. indices.push(StartIndex + 1);
  32147. indices.push(StartIndex + 1);
  32148. indices.push(StartIndex + 2);
  32149. indices.push(StartIndex + 3);
  32150. }
  32151. StartIndex += 4;
  32152. }
  32153. ;
  32154. };
  32155. return PolygonMeshBuilder;
  32156. })();
  32157. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32158. })(BABYLON || (BABYLON = {}));
  32159. var BABYLON;
  32160. (function (BABYLON) {
  32161. var Octree = (function () {
  32162. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32163. if (maxDepth === void 0) { maxDepth = 2; }
  32164. this.maxDepth = maxDepth;
  32165. this.dynamicContent = new Array();
  32166. this._maxBlockCapacity = maxBlockCapacity || 64;
  32167. this._selectionContent = new BABYLON.SmartArray(1024);
  32168. this._creationFunc = creationFunc;
  32169. }
  32170. // Methods
  32171. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32172. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32173. };
  32174. Octree.prototype.addMesh = function (entry) {
  32175. for (var index = 0; index < this.blocks.length; index++) {
  32176. var block = this.blocks[index];
  32177. block.addEntry(entry);
  32178. }
  32179. };
  32180. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32181. this._selectionContent.reset();
  32182. for (var index = 0; index < this.blocks.length; index++) {
  32183. var block = this.blocks[index];
  32184. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32185. }
  32186. if (allowDuplicate) {
  32187. this._selectionContent.concat(this.dynamicContent);
  32188. }
  32189. else {
  32190. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32191. }
  32192. return this._selectionContent;
  32193. };
  32194. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32195. this._selectionContent.reset();
  32196. for (var index = 0; index < this.blocks.length; index++) {
  32197. var block = this.blocks[index];
  32198. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32199. }
  32200. if (allowDuplicate) {
  32201. this._selectionContent.concat(this.dynamicContent);
  32202. }
  32203. else {
  32204. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32205. }
  32206. return this._selectionContent;
  32207. };
  32208. Octree.prototype.intersectsRay = function (ray) {
  32209. this._selectionContent.reset();
  32210. for (var index = 0; index < this.blocks.length; index++) {
  32211. var block = this.blocks[index];
  32212. block.intersectsRay(ray, this._selectionContent);
  32213. }
  32214. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32215. return this._selectionContent;
  32216. };
  32217. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32218. target.blocks = new Array();
  32219. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32220. // Segmenting space
  32221. for (var x = 0; x < 2; x++) {
  32222. for (var y = 0; y < 2; y++) {
  32223. for (var z = 0; z < 2; z++) {
  32224. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32225. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32226. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32227. block.addEntries(entries);
  32228. target.blocks.push(block);
  32229. }
  32230. }
  32231. }
  32232. };
  32233. Octree.CreationFuncForMeshes = function (entry, block) {
  32234. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32235. block.entries.push(entry);
  32236. }
  32237. };
  32238. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32239. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32240. block.entries.push(entry);
  32241. }
  32242. };
  32243. return Octree;
  32244. })();
  32245. BABYLON.Octree = Octree;
  32246. })(BABYLON || (BABYLON = {}));
  32247. var BABYLON;
  32248. (function (BABYLON) {
  32249. var OctreeBlock = (function () {
  32250. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32251. this.entries = new Array();
  32252. this._boundingVectors = new Array();
  32253. this._capacity = capacity;
  32254. this._depth = depth;
  32255. this._maxDepth = maxDepth;
  32256. this._creationFunc = creationFunc;
  32257. this._minPoint = minPoint;
  32258. this._maxPoint = maxPoint;
  32259. this._boundingVectors.push(minPoint.clone());
  32260. this._boundingVectors.push(maxPoint.clone());
  32261. this._boundingVectors.push(minPoint.clone());
  32262. this._boundingVectors[2].x = maxPoint.x;
  32263. this._boundingVectors.push(minPoint.clone());
  32264. this._boundingVectors[3].y = maxPoint.y;
  32265. this._boundingVectors.push(minPoint.clone());
  32266. this._boundingVectors[4].z = maxPoint.z;
  32267. this._boundingVectors.push(maxPoint.clone());
  32268. this._boundingVectors[5].z = minPoint.z;
  32269. this._boundingVectors.push(maxPoint.clone());
  32270. this._boundingVectors[6].x = minPoint.x;
  32271. this._boundingVectors.push(maxPoint.clone());
  32272. this._boundingVectors[7].y = minPoint.y;
  32273. }
  32274. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32275. // Property
  32276. get: function () {
  32277. return this._capacity;
  32278. },
  32279. enumerable: true,
  32280. configurable: true
  32281. });
  32282. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32283. get: function () {
  32284. return this._minPoint;
  32285. },
  32286. enumerable: true,
  32287. configurable: true
  32288. });
  32289. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32290. get: function () {
  32291. return this._maxPoint;
  32292. },
  32293. enumerable: true,
  32294. configurable: true
  32295. });
  32296. // Methods
  32297. OctreeBlock.prototype.addEntry = function (entry) {
  32298. if (this.blocks) {
  32299. for (var index = 0; index < this.blocks.length; index++) {
  32300. var block = this.blocks[index];
  32301. block.addEntry(entry);
  32302. }
  32303. return;
  32304. }
  32305. this._creationFunc(entry, this);
  32306. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32307. this.createInnerBlocks();
  32308. }
  32309. };
  32310. OctreeBlock.prototype.addEntries = function (entries) {
  32311. for (var index = 0; index < entries.length; index++) {
  32312. var mesh = entries[index];
  32313. this.addEntry(mesh);
  32314. }
  32315. };
  32316. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32317. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32318. if (this.blocks) {
  32319. for (var index = 0; index < this.blocks.length; index++) {
  32320. var block = this.blocks[index];
  32321. block.select(frustumPlanes, selection, allowDuplicate);
  32322. }
  32323. return;
  32324. }
  32325. if (allowDuplicate) {
  32326. selection.concat(this.entries);
  32327. }
  32328. else {
  32329. selection.concatWithNoDuplicate(this.entries);
  32330. }
  32331. }
  32332. };
  32333. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32334. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32335. if (this.blocks) {
  32336. for (var index = 0; index < this.blocks.length; index++) {
  32337. var block = this.blocks[index];
  32338. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32339. }
  32340. return;
  32341. }
  32342. if (allowDuplicate) {
  32343. selection.concat(this.entries);
  32344. }
  32345. else {
  32346. selection.concatWithNoDuplicate(this.entries);
  32347. }
  32348. }
  32349. };
  32350. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32351. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32352. if (this.blocks) {
  32353. for (var index = 0; index < this.blocks.length; index++) {
  32354. var block = this.blocks[index];
  32355. block.intersectsRay(ray, selection);
  32356. }
  32357. return;
  32358. }
  32359. selection.concatWithNoDuplicate(this.entries);
  32360. }
  32361. };
  32362. OctreeBlock.prototype.createInnerBlocks = function () {
  32363. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32364. };
  32365. return OctreeBlock;
  32366. })();
  32367. BABYLON.OctreeBlock = OctreeBlock;
  32368. })(BABYLON || (BABYLON = {}));
  32369. var BABYLON;
  32370. (function (BABYLON) {
  32371. var BlurPostProcess = (function (_super) {
  32372. __extends(BlurPostProcess, _super);
  32373. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32374. var _this = this;
  32375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32376. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32377. this.direction = direction;
  32378. this.blurWidth = blurWidth;
  32379. this.onApply = function (effect) {
  32380. effect.setFloat2("screenSize", _this.width, _this.height);
  32381. effect.setVector2("direction", _this.direction);
  32382. effect.setFloat("blurWidth", _this.blurWidth);
  32383. };
  32384. }
  32385. return BlurPostProcess;
  32386. })(BABYLON.PostProcess);
  32387. BABYLON.BlurPostProcess = BlurPostProcess;
  32388. })(BABYLON || (BABYLON = {}));
  32389. var BABYLON;
  32390. (function (BABYLON) {
  32391. var RefractionPostProcess = (function (_super) {
  32392. __extends(RefractionPostProcess, _super);
  32393. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32394. var _this = this;
  32395. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32396. this.color = color;
  32397. this.depth = depth;
  32398. this.colorLevel = colorLevel;
  32399. this.onActivate = function (cam) {
  32400. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32401. };
  32402. this.onApply = function (effect) {
  32403. effect.setColor3("baseColor", _this.color);
  32404. effect.setFloat("depth", _this.depth);
  32405. effect.setFloat("colorLevel", _this.colorLevel);
  32406. effect.setTexture("refractionSampler", _this._refRexture);
  32407. };
  32408. }
  32409. // Methods
  32410. RefractionPostProcess.prototype.dispose = function (camera) {
  32411. if (this._refRexture) {
  32412. this._refRexture.dispose();
  32413. }
  32414. _super.prototype.dispose.call(this, camera);
  32415. };
  32416. return RefractionPostProcess;
  32417. })(BABYLON.PostProcess);
  32418. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32419. })(BABYLON || (BABYLON = {}));
  32420. var BABYLON;
  32421. (function (BABYLON) {
  32422. var BlackAndWhitePostProcess = (function (_super) {
  32423. __extends(BlackAndWhitePostProcess, _super);
  32424. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32425. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32426. }
  32427. return BlackAndWhitePostProcess;
  32428. })(BABYLON.PostProcess);
  32429. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32430. })(BABYLON || (BABYLON = {}));
  32431. var BABYLON;
  32432. (function (BABYLON) {
  32433. var ConvolutionPostProcess = (function (_super) {
  32434. __extends(ConvolutionPostProcess, _super);
  32435. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32436. var _this = this;
  32437. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32438. this.kernel = kernel;
  32439. this.onApply = function (effect) {
  32440. effect.setFloat2("screenSize", _this.width, _this.height);
  32441. effect.setArray("kernel", _this.kernel);
  32442. };
  32443. }
  32444. // Statics
  32445. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32446. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32447. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32448. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32449. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32450. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32451. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32452. return ConvolutionPostProcess;
  32453. })(BABYLON.PostProcess);
  32454. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32455. })(BABYLON || (BABYLON = {}));
  32456. var BABYLON;
  32457. (function (BABYLON) {
  32458. var FilterPostProcess = (function (_super) {
  32459. __extends(FilterPostProcess, _super);
  32460. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32461. var _this = this;
  32462. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32463. this.kernelMatrix = kernelMatrix;
  32464. this.onApply = function (effect) {
  32465. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32466. };
  32467. }
  32468. return FilterPostProcess;
  32469. })(BABYLON.PostProcess);
  32470. BABYLON.FilterPostProcess = FilterPostProcess;
  32471. })(BABYLON || (BABYLON = {}));
  32472. var BABYLON;
  32473. (function (BABYLON) {
  32474. var FxaaPostProcess = (function (_super) {
  32475. __extends(FxaaPostProcess, _super);
  32476. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32477. var _this = this;
  32478. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32479. this.onSizeChanged = function () {
  32480. _this.texelWidth = 1.0 / _this.width;
  32481. _this.texelHeight = 1.0 / _this.height;
  32482. };
  32483. this.onApply = function (effect) {
  32484. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32485. };
  32486. }
  32487. return FxaaPostProcess;
  32488. })(BABYLON.PostProcess);
  32489. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32490. })(BABYLON || (BABYLON = {}));
  32491. var BABYLON;
  32492. (function (BABYLON) {
  32493. var StereoscopicInterlacePostProcess = (function (_super) {
  32494. __extends(StereoscopicInterlacePostProcess, _super);
  32495. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32496. var _this = this;
  32497. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32498. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32499. this.onSizeChanged = function () {
  32500. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32501. };
  32502. this.onApply = function (effect) {
  32503. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32504. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32505. };
  32506. }
  32507. return StereoscopicInterlacePostProcess;
  32508. })(BABYLON.PostProcess);
  32509. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32510. })(BABYLON || (BABYLON = {}));
  32511. var BABYLON;
  32512. (function (BABYLON) {
  32513. var LensFlare = (function () {
  32514. function LensFlare(size, position, color, imgUrl, system) {
  32515. this.size = size;
  32516. this.position = position;
  32517. this.dispose = function () {
  32518. if (this.texture) {
  32519. this.texture.dispose();
  32520. }
  32521. // Remove from scene
  32522. var index = this._system.lensFlares.indexOf(this);
  32523. this._system.lensFlares.splice(index, 1);
  32524. };
  32525. this.color = color || new BABYLON.Color3(1, 1, 1);
  32526. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32527. this._system = system;
  32528. system.lensFlares.push(this);
  32529. }
  32530. return LensFlare;
  32531. })();
  32532. BABYLON.LensFlare = LensFlare;
  32533. })(BABYLON || (BABYLON = {}));
  32534. var BABYLON;
  32535. (function (BABYLON) {
  32536. var LensFlareSystem = (function () {
  32537. function LensFlareSystem(name, emitter, scene) {
  32538. this.name = name;
  32539. this.lensFlares = new Array();
  32540. this.borderLimit = 300;
  32541. this.layerMask = 0x0FFFFFFF;
  32542. this._vertexDeclaration = [2];
  32543. this._vertexStrideSize = 2 * 4;
  32544. this._isEnabled = true;
  32545. this._scene = scene;
  32546. this._emitter = emitter;
  32547. scene.lensFlareSystems.push(this);
  32548. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32549. // VBO
  32550. var vertices = [];
  32551. vertices.push(1, 1);
  32552. vertices.push(-1, 1);
  32553. vertices.push(-1, -1);
  32554. vertices.push(1, -1);
  32555. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32556. // Indices
  32557. var indices = [];
  32558. indices.push(0);
  32559. indices.push(1);
  32560. indices.push(2);
  32561. indices.push(0);
  32562. indices.push(2);
  32563. indices.push(3);
  32564. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32565. // Effects
  32566. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32567. }
  32568. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32569. get: function () {
  32570. return this._isEnabled;
  32571. },
  32572. set: function (value) {
  32573. this._isEnabled = value;
  32574. },
  32575. enumerable: true,
  32576. configurable: true
  32577. });
  32578. LensFlareSystem.prototype.getScene = function () {
  32579. return this._scene;
  32580. };
  32581. LensFlareSystem.prototype.getEmitter = function () {
  32582. return this._emitter;
  32583. };
  32584. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32585. this._emitter = newEmitter;
  32586. };
  32587. LensFlareSystem.prototype.getEmitterPosition = function () {
  32588. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32589. };
  32590. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32591. var position = this.getEmitterPosition();
  32592. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32593. this._positionX = position.x;
  32594. this._positionY = position.y;
  32595. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32596. if (position.z > 0) {
  32597. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32598. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32599. return true;
  32600. }
  32601. }
  32602. return false;
  32603. };
  32604. LensFlareSystem.prototype._isVisible = function () {
  32605. if (!this._isEnabled) {
  32606. return false;
  32607. }
  32608. var emitterPosition = this.getEmitterPosition();
  32609. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32610. var distance = direction.length();
  32611. direction.normalize();
  32612. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32613. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32614. return !pickInfo.hit || pickInfo.distance > distance;
  32615. };
  32616. LensFlareSystem.prototype.render = function () {
  32617. if (!this._effect.isReady())
  32618. return false;
  32619. var engine = this._scene.getEngine();
  32620. var viewport = this._scene.activeCamera.viewport;
  32621. var globalViewport = viewport.toGlobal(engine);
  32622. // Position
  32623. if (!this.computeEffectivePosition(globalViewport)) {
  32624. return false;
  32625. }
  32626. // Visibility
  32627. if (!this._isVisible()) {
  32628. return false;
  32629. }
  32630. // Intensity
  32631. var awayX;
  32632. var awayY;
  32633. if (this._positionX < this.borderLimit + globalViewport.x) {
  32634. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32635. }
  32636. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32637. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32638. }
  32639. else {
  32640. awayX = 0;
  32641. }
  32642. if (this._positionY < this.borderLimit + globalViewport.y) {
  32643. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32644. }
  32645. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32646. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32647. }
  32648. else {
  32649. awayY = 0;
  32650. }
  32651. var away = (awayX > awayY) ? awayX : awayY;
  32652. if (away > this.borderLimit) {
  32653. away = this.borderLimit;
  32654. }
  32655. var intensity = 1.0 - (away / this.borderLimit);
  32656. if (intensity < 0) {
  32657. return false;
  32658. }
  32659. if (intensity > 1.0) {
  32660. intensity = 1.0;
  32661. }
  32662. // Position
  32663. var centerX = globalViewport.x + globalViewport.width / 2;
  32664. var centerY = globalViewport.y + globalViewport.height / 2;
  32665. var distX = centerX - this._positionX;
  32666. var distY = centerY - this._positionY;
  32667. // Effects
  32668. engine.enableEffect(this._effect);
  32669. engine.setState(false);
  32670. engine.setDepthBuffer(false);
  32671. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32672. // VBOs
  32673. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32674. // Flares
  32675. for (var index = 0; index < this.lensFlares.length; index++) {
  32676. var flare = this.lensFlares[index];
  32677. var x = centerX - (distX * flare.position);
  32678. var y = centerY - (distY * flare.position);
  32679. var cw = flare.size;
  32680. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32681. var cx = 2 * (x / globalViewport.width) - 1.0;
  32682. var cy = 1.0 - 2 * (y / globalViewport.height);
  32683. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32684. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32685. // Texture
  32686. this._effect.setTexture("textureSampler", flare.texture);
  32687. // Color
  32688. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32689. // Draw order
  32690. engine.draw(true, 0, 6);
  32691. }
  32692. engine.setDepthBuffer(true);
  32693. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32694. return true;
  32695. };
  32696. LensFlareSystem.prototype.dispose = function () {
  32697. if (this._vertexBuffer) {
  32698. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32699. this._vertexBuffer = null;
  32700. }
  32701. if (this._indexBuffer) {
  32702. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32703. this._indexBuffer = null;
  32704. }
  32705. while (this.lensFlares.length) {
  32706. this.lensFlares[0].dispose();
  32707. }
  32708. // Remove from scene
  32709. var index = this._scene.lensFlareSystems.indexOf(this);
  32710. this._scene.lensFlareSystems.splice(index, 1);
  32711. };
  32712. return LensFlareSystem;
  32713. })();
  32714. BABYLON.LensFlareSystem = LensFlareSystem;
  32715. })(BABYLON || (BABYLON = {}));
  32716. var BABYLON;
  32717. (function (BABYLON) {
  32718. // We're mainly based on the logic defined into the FreeCamera code
  32719. var DeviceOrientationCamera = (function (_super) {
  32720. __extends(DeviceOrientationCamera, _super);
  32721. function DeviceOrientationCamera(name, position, scene) {
  32722. var _this = this;
  32723. _super.call(this, name, position, scene);
  32724. this._offsetX = null;
  32725. this._offsetY = null;
  32726. this._orientationGamma = 0;
  32727. this._orientationBeta = 0;
  32728. this._initialOrientationGamma = 0;
  32729. this._initialOrientationBeta = 0;
  32730. this.angularSensibility = 10000.0;
  32731. this.moveSensibility = 50.0;
  32732. window.addEventListener("resize", function () {
  32733. _this._initialOrientationGamma = null;
  32734. }, false);
  32735. }
  32736. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32737. var _this = this;
  32738. if (this._attachedCanvas) {
  32739. return;
  32740. }
  32741. this._attachedCanvas = canvas;
  32742. if (!this._orientationChanged) {
  32743. this._orientationChanged = function (evt) {
  32744. if (!_this._initialOrientationGamma) {
  32745. _this._initialOrientationGamma = evt.gamma;
  32746. _this._initialOrientationBeta = evt.beta;
  32747. }
  32748. _this._orientationGamma = evt.gamma;
  32749. _this._orientationBeta = evt.beta;
  32750. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32751. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32752. };
  32753. }
  32754. window.addEventListener("deviceorientation", this._orientationChanged);
  32755. };
  32756. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32757. if (this._attachedCanvas != canvas) {
  32758. return;
  32759. }
  32760. window.removeEventListener("deviceorientation", this._orientationChanged);
  32761. this._attachedCanvas = null;
  32762. this._orientationGamma = 0;
  32763. this._orientationBeta = 0;
  32764. this._initialOrientationGamma = 0;
  32765. this._initialOrientationBeta = 0;
  32766. };
  32767. DeviceOrientationCamera.prototype._checkInputs = function () {
  32768. if (!this._offsetX) {
  32769. return;
  32770. }
  32771. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32772. var speed = this._computeLocalCameraSpeed();
  32773. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32774. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32775. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32776. _super.prototype._checkInputs.call(this);
  32777. };
  32778. return DeviceOrientationCamera;
  32779. })(BABYLON.FreeCamera);
  32780. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32781. })(BABYLON || (BABYLON = {}));
  32782. var BABYLON;
  32783. (function (BABYLON) {
  32784. var Gamepads = (function () {
  32785. function Gamepads(ongamedpadconnected) {
  32786. var _this = this;
  32787. this.babylonGamepads = [];
  32788. this.oneGamepadConnected = false;
  32789. this.isMonitoring = false;
  32790. this.gamepadEventSupported = 'GamepadEvent' in window;
  32791. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32792. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32793. 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=";
  32794. this._callbackGamepadConnected = ongamedpadconnected;
  32795. if (this.gamepadSupportAvailable) {
  32796. // Checking if the gamepad connected event is supported (like in Firefox)
  32797. if (this.gamepadEventSupported) {
  32798. window.addEventListener('gamepadconnected', function (evt) {
  32799. _this._onGamepadConnected(evt);
  32800. }, false);
  32801. window.addEventListener('gamepaddisconnected', function (evt) {
  32802. _this._onGamepadDisconnected(evt);
  32803. }, false);
  32804. }
  32805. else {
  32806. this._startMonitoringGamepads();
  32807. }
  32808. if (!this.oneGamepadConnected) {
  32809. this._insertGamepadDOMInstructions();
  32810. }
  32811. }
  32812. else {
  32813. this._insertGamepadDOMNotSupported();
  32814. }
  32815. }
  32816. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32817. Gamepads.gamepadDOMInfo = document.createElement("div");
  32818. var buttonAImage = document.createElement("img");
  32819. buttonAImage.src = this.buttonADataURL;
  32820. var spanMessage = document.createElement("span");
  32821. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32822. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32823. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32824. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32825. Gamepads.gamepadDOMInfo.style.width = "100%";
  32826. Gamepads.gamepadDOMInfo.style.height = "48px";
  32827. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32828. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32829. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32830. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32831. buttonAImage.style.position = "relative";
  32832. buttonAImage.style.bottom = "8px";
  32833. spanMessage.style.position = "relative";
  32834. spanMessage.style.fontSize = "32px";
  32835. spanMessage.style.bottom = "32px";
  32836. spanMessage.style.color = "green";
  32837. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32838. };
  32839. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32840. Gamepads.gamepadDOMInfo = document.createElement("div");
  32841. var spanMessage = document.createElement("span");
  32842. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32843. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32844. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32845. Gamepads.gamepadDOMInfo.style.width = "100%";
  32846. Gamepads.gamepadDOMInfo.style.height = "40px";
  32847. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32848. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32849. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32850. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32851. spanMessage.style.position = "relative";
  32852. spanMessage.style.fontSize = "32px";
  32853. spanMessage.style.color = "red";
  32854. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32855. };
  32856. Gamepads.prototype.dispose = function () {
  32857. if (Gamepads.gamepadDOMInfo) {
  32858. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32859. }
  32860. };
  32861. Gamepads.prototype._onGamepadConnected = function (evt) {
  32862. var newGamepad = this._addNewGamepad(evt.gamepad);
  32863. if (this._callbackGamepadConnected)
  32864. this._callbackGamepadConnected(newGamepad);
  32865. this._startMonitoringGamepads();
  32866. };
  32867. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32868. if (!this.oneGamepadConnected) {
  32869. this.oneGamepadConnected = true;
  32870. if (Gamepads.gamepadDOMInfo) {
  32871. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32872. Gamepads.gamepadDOMInfo = null;
  32873. }
  32874. }
  32875. var newGamepad;
  32876. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32877. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32878. }
  32879. else {
  32880. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32881. }
  32882. this.babylonGamepads.push(newGamepad);
  32883. return newGamepad;
  32884. };
  32885. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32886. // Remove the gamepad from the list of gamepads to monitor.
  32887. for (var i in this.babylonGamepads) {
  32888. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32889. this.babylonGamepads.splice(i, 1);
  32890. break;
  32891. }
  32892. }
  32893. // If no gamepads are left, stop the polling loop.
  32894. if (this.babylonGamepads.length == 0) {
  32895. this._stopMonitoringGamepads();
  32896. }
  32897. };
  32898. Gamepads.prototype._startMonitoringGamepads = function () {
  32899. if (!this.isMonitoring) {
  32900. this.isMonitoring = true;
  32901. this._checkGamepadsStatus();
  32902. }
  32903. };
  32904. Gamepads.prototype._stopMonitoringGamepads = function () {
  32905. this.isMonitoring = false;
  32906. };
  32907. Gamepads.prototype._checkGamepadsStatus = function () {
  32908. var _this = this;
  32909. // updating gamepad objects
  32910. this._updateGamepadObjects();
  32911. for (var i in this.babylonGamepads) {
  32912. this.babylonGamepads[i].update();
  32913. }
  32914. if (this.isMonitoring) {
  32915. if (window.requestAnimationFrame) {
  32916. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32917. }
  32918. else if (window.mozRequestAnimationFrame) {
  32919. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32920. }
  32921. else if (window.webkitRequestAnimationFrame) {
  32922. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32923. }
  32924. }
  32925. };
  32926. // This function is called only on Chrome, which does not yet support
  32927. // connection/disconnection events, but requires you to monitor
  32928. // an array for changes.
  32929. Gamepads.prototype._updateGamepadObjects = function () {
  32930. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32931. for (var i = 0; i < gamepads.length; i++) {
  32932. if (gamepads[i]) {
  32933. if (!(gamepads[i].index in this.babylonGamepads)) {
  32934. var newGamepad = this._addNewGamepad(gamepads[i]);
  32935. if (this._callbackGamepadConnected) {
  32936. this._callbackGamepadConnected(newGamepad);
  32937. }
  32938. }
  32939. else {
  32940. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32941. }
  32942. }
  32943. }
  32944. };
  32945. return Gamepads;
  32946. })();
  32947. BABYLON.Gamepads = Gamepads;
  32948. var StickValues = (function () {
  32949. function StickValues(x, y) {
  32950. this.x = x;
  32951. this.y = y;
  32952. }
  32953. return StickValues;
  32954. })();
  32955. BABYLON.StickValues = StickValues;
  32956. var Gamepad = (function () {
  32957. function Gamepad(id, index, browserGamepad) {
  32958. this.id = id;
  32959. this.index = index;
  32960. this.browserGamepad = browserGamepad;
  32961. if (this.browserGamepad.axes.length >= 2) {
  32962. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32963. }
  32964. if (this.browserGamepad.axes.length >= 4) {
  32965. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32966. }
  32967. }
  32968. Gamepad.prototype.onleftstickchanged = function (callback) {
  32969. this._onleftstickchanged = callback;
  32970. };
  32971. Gamepad.prototype.onrightstickchanged = function (callback) {
  32972. this._onrightstickchanged = callback;
  32973. };
  32974. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32975. get: function () {
  32976. return this._leftStick;
  32977. },
  32978. set: function (newValues) {
  32979. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32980. this._onleftstickchanged(newValues);
  32981. }
  32982. this._leftStick = newValues;
  32983. },
  32984. enumerable: true,
  32985. configurable: true
  32986. });
  32987. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32988. get: function () {
  32989. return this._rightStick;
  32990. },
  32991. set: function (newValues) {
  32992. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32993. this._onrightstickchanged(newValues);
  32994. }
  32995. this._rightStick = newValues;
  32996. },
  32997. enumerable: true,
  32998. configurable: true
  32999. });
  33000. Gamepad.prototype.update = function () {
  33001. if (this._leftStick) {
  33002. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33003. }
  33004. if (this._rightStick) {
  33005. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33006. }
  33007. };
  33008. return Gamepad;
  33009. })();
  33010. BABYLON.Gamepad = Gamepad;
  33011. var GenericPad = (function (_super) {
  33012. __extends(GenericPad, _super);
  33013. function GenericPad(id, index, gamepad) {
  33014. _super.call(this, id, index, gamepad);
  33015. this.id = id;
  33016. this.index = index;
  33017. this.gamepad = gamepad;
  33018. this._buttons = new Array(gamepad.buttons.length);
  33019. }
  33020. GenericPad.prototype.onbuttondown = function (callback) {
  33021. this._onbuttondown = callback;
  33022. };
  33023. GenericPad.prototype.onbuttonup = function (callback) {
  33024. this._onbuttonup = callback;
  33025. };
  33026. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33027. if (newValue !== currentValue) {
  33028. if (this._onbuttondown && newValue === 1) {
  33029. this._onbuttondown(buttonIndex);
  33030. }
  33031. if (this._onbuttonup && newValue === 0) {
  33032. this._onbuttonup(buttonIndex);
  33033. }
  33034. }
  33035. return newValue;
  33036. };
  33037. GenericPad.prototype.update = function () {
  33038. _super.prototype.update.call(this);
  33039. for (var index = 0; index < this._buttons.length; index++) {
  33040. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33041. }
  33042. };
  33043. return GenericPad;
  33044. })(Gamepad);
  33045. BABYLON.GenericPad = GenericPad;
  33046. (function (Xbox360Button) {
  33047. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33048. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33049. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33050. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33051. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33052. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33053. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33054. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33055. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33056. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33057. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33058. var Xbox360Button = BABYLON.Xbox360Button;
  33059. (function (Xbox360Dpad) {
  33060. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33061. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33062. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33063. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33064. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33065. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33066. var Xbox360Pad = (function (_super) {
  33067. __extends(Xbox360Pad, _super);
  33068. function Xbox360Pad() {
  33069. _super.apply(this, arguments);
  33070. this._leftTrigger = 0;
  33071. this._rightTrigger = 0;
  33072. this._buttonA = 0;
  33073. this._buttonB = 0;
  33074. this._buttonX = 0;
  33075. this._buttonY = 0;
  33076. this._buttonBack = 0;
  33077. this._buttonStart = 0;
  33078. this._buttonLB = 0;
  33079. this._buttonRB = 0;
  33080. this._buttonLeftStick = 0;
  33081. this._buttonRightStick = 0;
  33082. this._dPadUp = 0;
  33083. this._dPadDown = 0;
  33084. this._dPadLeft = 0;
  33085. this._dPadRight = 0;
  33086. }
  33087. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33088. this._onlefttriggerchanged = callback;
  33089. };
  33090. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33091. this._onrighttriggerchanged = callback;
  33092. };
  33093. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33094. get: function () {
  33095. return this._leftTrigger;
  33096. },
  33097. set: function (newValue) {
  33098. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33099. this._onlefttriggerchanged(newValue);
  33100. }
  33101. this._leftTrigger = newValue;
  33102. },
  33103. enumerable: true,
  33104. configurable: true
  33105. });
  33106. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33107. get: function () {
  33108. return this._rightTrigger;
  33109. },
  33110. set: function (newValue) {
  33111. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33112. this._onrighttriggerchanged(newValue);
  33113. }
  33114. this._rightTrigger = newValue;
  33115. },
  33116. enumerable: true,
  33117. configurable: true
  33118. });
  33119. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33120. this._onbuttondown = callback;
  33121. };
  33122. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33123. this._onbuttonup = callback;
  33124. };
  33125. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33126. this._ondpaddown = callback;
  33127. };
  33128. Xbox360Pad.prototype.ondpadup = function (callback) {
  33129. this._ondpadup = callback;
  33130. };
  33131. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33132. if (newValue !== currentValue) {
  33133. if (this._onbuttondown && newValue === 1) {
  33134. this._onbuttondown(buttonType);
  33135. }
  33136. if (this._onbuttonup && newValue === 0) {
  33137. this._onbuttonup(buttonType);
  33138. }
  33139. }
  33140. return newValue;
  33141. };
  33142. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33143. if (newValue !== currentValue) {
  33144. if (this._ondpaddown && newValue === 1) {
  33145. this._ondpaddown(buttonType);
  33146. }
  33147. if (this._ondpadup && newValue === 0) {
  33148. this._ondpadup(buttonType);
  33149. }
  33150. }
  33151. return newValue;
  33152. };
  33153. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33154. get: function () {
  33155. return this._buttonA;
  33156. },
  33157. set: function (value) {
  33158. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33159. },
  33160. enumerable: true,
  33161. configurable: true
  33162. });
  33163. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33164. get: function () {
  33165. return this._buttonB;
  33166. },
  33167. set: function (value) {
  33168. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33169. },
  33170. enumerable: true,
  33171. configurable: true
  33172. });
  33173. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33174. get: function () {
  33175. return this._buttonX;
  33176. },
  33177. set: function (value) {
  33178. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33179. },
  33180. enumerable: true,
  33181. configurable: true
  33182. });
  33183. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33184. get: function () {
  33185. return this._buttonY;
  33186. },
  33187. set: function (value) {
  33188. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33189. },
  33190. enumerable: true,
  33191. configurable: true
  33192. });
  33193. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33194. get: function () {
  33195. return this._buttonStart;
  33196. },
  33197. set: function (value) {
  33198. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33204. get: function () {
  33205. return this._buttonBack;
  33206. },
  33207. set: function (value) {
  33208. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33209. },
  33210. enumerable: true,
  33211. configurable: true
  33212. });
  33213. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33214. get: function () {
  33215. return this._buttonLB;
  33216. },
  33217. set: function (value) {
  33218. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33219. },
  33220. enumerable: true,
  33221. configurable: true
  33222. });
  33223. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33224. get: function () {
  33225. return this._buttonRB;
  33226. },
  33227. set: function (value) {
  33228. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33229. },
  33230. enumerable: true,
  33231. configurable: true
  33232. });
  33233. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33234. get: function () {
  33235. return this._buttonLeftStick;
  33236. },
  33237. set: function (value) {
  33238. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33239. },
  33240. enumerable: true,
  33241. configurable: true
  33242. });
  33243. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33244. get: function () {
  33245. return this._buttonRightStick;
  33246. },
  33247. set: function (value) {
  33248. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33249. },
  33250. enumerable: true,
  33251. configurable: true
  33252. });
  33253. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33254. get: function () {
  33255. return this._dPadUp;
  33256. },
  33257. set: function (value) {
  33258. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33259. },
  33260. enumerable: true,
  33261. configurable: true
  33262. });
  33263. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33264. get: function () {
  33265. return this._dPadDown;
  33266. },
  33267. set: function (value) {
  33268. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33269. },
  33270. enumerable: true,
  33271. configurable: true
  33272. });
  33273. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33274. get: function () {
  33275. return this._dPadLeft;
  33276. },
  33277. set: function (value) {
  33278. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33284. get: function () {
  33285. return this._dPadRight;
  33286. },
  33287. set: function (value) {
  33288. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33289. },
  33290. enumerable: true,
  33291. configurable: true
  33292. });
  33293. Xbox360Pad.prototype.update = function () {
  33294. _super.prototype.update.call(this);
  33295. this.buttonA = this.browserGamepad.buttons[0].value;
  33296. this.buttonB = this.browserGamepad.buttons[1].value;
  33297. this.buttonX = this.browserGamepad.buttons[2].value;
  33298. this.buttonY = this.browserGamepad.buttons[3].value;
  33299. this.buttonLB = this.browserGamepad.buttons[4].value;
  33300. this.buttonRB = this.browserGamepad.buttons[5].value;
  33301. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33302. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33303. this.buttonBack = this.browserGamepad.buttons[8].value;
  33304. this.buttonStart = this.browserGamepad.buttons[9].value;
  33305. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33306. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33307. this.dPadUp = this.browserGamepad.buttons[12].value;
  33308. this.dPadDown = this.browserGamepad.buttons[13].value;
  33309. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33310. this.dPadRight = this.browserGamepad.buttons[15].value;
  33311. };
  33312. return Xbox360Pad;
  33313. })(Gamepad);
  33314. BABYLON.Xbox360Pad = Xbox360Pad;
  33315. })(BABYLON || (BABYLON = {}));
  33316. var BABYLON;
  33317. (function (BABYLON) {
  33318. // We're mainly based on the logic defined into the FreeCamera code
  33319. var GamepadCamera = (function (_super) {
  33320. __extends(GamepadCamera, _super);
  33321. function GamepadCamera(name, position, scene) {
  33322. var _this = this;
  33323. _super.call(this, name, position, scene);
  33324. this.angularSensibility = 200;
  33325. this.moveSensibility = 75;
  33326. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33327. }
  33328. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33329. // Only the first gamepad can control the camera
  33330. if (gamepad.index === 0) {
  33331. this._gamepad = gamepad;
  33332. }
  33333. };
  33334. GamepadCamera.prototype._checkInputs = function () {
  33335. if (this._gamepad) {
  33336. var LSValues = this._gamepad.leftStick;
  33337. var normalizedLX = LSValues.x / this.moveSensibility;
  33338. var normalizedLY = LSValues.y / this.moveSensibility;
  33339. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33340. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33341. var RSValues = this._gamepad.rightStick;
  33342. var normalizedRX = RSValues.x / this.angularSensibility;
  33343. var normalizedRY = RSValues.y / this.angularSensibility;
  33344. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33345. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33346. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33347. var speed = this._computeLocalCameraSpeed() * 50.0;
  33348. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33349. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33350. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33351. }
  33352. _super.prototype._checkInputs.call(this);
  33353. };
  33354. GamepadCamera.prototype.dispose = function () {
  33355. this._gamepads.dispose();
  33356. _super.prototype.dispose.call(this);
  33357. };
  33358. return GamepadCamera;
  33359. })(BABYLON.FreeCamera);
  33360. BABYLON.GamepadCamera = GamepadCamera;
  33361. })(BABYLON || (BABYLON = {}));
  33362. var BABYLON;
  33363. (function (BABYLON) {
  33364. var Analyser = (function () {
  33365. function Analyser(scene) {
  33366. this.SMOOTHING = 0.75;
  33367. this.FFT_SIZE = 512;
  33368. this.BARGRAPHAMPLITUDE = 256;
  33369. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33370. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33371. this._scene = scene;
  33372. this._audioEngine = BABYLON.Engine.audioEngine;
  33373. if (this._audioEngine.canUseWebAudio) {
  33374. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33375. this._webAudioAnalyser.minDecibels = -140;
  33376. this._webAudioAnalyser.maxDecibels = 0;
  33377. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33378. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33379. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33380. }
  33381. }
  33382. Analyser.prototype.getFrequencyBinCount = function () {
  33383. if (this._audioEngine.canUseWebAudio) {
  33384. return this._webAudioAnalyser.frequencyBinCount;
  33385. }
  33386. else {
  33387. return 0;
  33388. }
  33389. };
  33390. Analyser.prototype.getByteFrequencyData = function () {
  33391. if (this._audioEngine.canUseWebAudio) {
  33392. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33393. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33394. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33395. }
  33396. return this._byteFreqs;
  33397. };
  33398. Analyser.prototype.getByteTimeDomainData = function () {
  33399. if (this._audioEngine.canUseWebAudio) {
  33400. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33401. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33402. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33403. }
  33404. return this._byteTime;
  33405. };
  33406. Analyser.prototype.getFloatFrequencyData = function () {
  33407. if (this._audioEngine.canUseWebAudio) {
  33408. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33409. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33410. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33411. }
  33412. return this._floatFreqs;
  33413. };
  33414. Analyser.prototype.drawDebugCanvas = function () {
  33415. var _this = this;
  33416. if (this._audioEngine.canUseWebAudio) {
  33417. if (!this._debugCanvas) {
  33418. this._debugCanvas = document.createElement("canvas");
  33419. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33420. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33421. this._debugCanvas.style.position = "absolute";
  33422. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33423. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33424. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33425. document.body.appendChild(this._debugCanvas);
  33426. this._registerFunc = function () {
  33427. _this.drawDebugCanvas();
  33428. };
  33429. this._scene.registerBeforeRender(this._registerFunc);
  33430. }
  33431. if (this._registerFunc) {
  33432. var workingArray = this.getByteFrequencyData();
  33433. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33434. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33435. // Draw the frequency domain chart.
  33436. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33437. var value = workingArray[i];
  33438. var percent = value / this.BARGRAPHAMPLITUDE;
  33439. var height = this.DEBUGCANVASSIZE.height * percent;
  33440. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33441. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33442. var hue = i / this.getFrequencyBinCount() * 360;
  33443. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33444. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33445. }
  33446. }
  33447. }
  33448. };
  33449. Analyser.prototype.stopDebugCanvas = function () {
  33450. if (this._debugCanvas) {
  33451. this._scene.unregisterBeforeRender(this._registerFunc);
  33452. this._registerFunc = null;
  33453. document.body.removeChild(this._debugCanvas);
  33454. this._debugCanvas = null;
  33455. this._debugCanvasContext = null;
  33456. }
  33457. };
  33458. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33459. if (this._audioEngine.canUseWebAudio) {
  33460. inputAudioNode.connect(this._webAudioAnalyser);
  33461. this._webAudioAnalyser.connect(outputAudioNode);
  33462. }
  33463. };
  33464. Analyser.prototype.dispose = function () {
  33465. if (this._audioEngine.canUseWebAudio) {
  33466. this._webAudioAnalyser.disconnect();
  33467. }
  33468. };
  33469. return Analyser;
  33470. })();
  33471. BABYLON.Analyser = Analyser;
  33472. })(BABYLON || (BABYLON = {}));
  33473. var BABYLON;
  33474. (function (BABYLON) {
  33475. var AudioEngine = (function () {
  33476. function AudioEngine() {
  33477. this._audioContext = null;
  33478. this._audioContextInitialized = false;
  33479. this.canUseWebAudio = false;
  33480. this.WarnedWebAudioUnsupported = false;
  33481. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33482. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33483. this.canUseWebAudio = true;
  33484. }
  33485. }
  33486. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33487. get: function () {
  33488. if (!this._audioContextInitialized) {
  33489. this._initializeAudioContext();
  33490. }
  33491. return this._audioContext;
  33492. },
  33493. enumerable: true,
  33494. configurable: true
  33495. });
  33496. AudioEngine.prototype._initializeAudioContext = function () {
  33497. try {
  33498. if (this.canUseWebAudio) {
  33499. this._audioContext = new AudioContext();
  33500. // create a global volume gain node
  33501. this.masterGain = this._audioContext.createGain();
  33502. this.masterGain.gain.value = 1;
  33503. this.masterGain.connect(this._audioContext.destination);
  33504. this._audioContextInitialized = true;
  33505. }
  33506. }
  33507. catch (e) {
  33508. this.canUseWebAudio = false;
  33509. BABYLON.Tools.Error("Web Audio: " + e.message);
  33510. }
  33511. };
  33512. AudioEngine.prototype.dispose = function () {
  33513. if (this.canUseWebAudio && this._audioContextInitialized) {
  33514. if (this._connectedAnalyser) {
  33515. this._connectedAnalyser.stopDebugCanvas();
  33516. this._connectedAnalyser.dispose();
  33517. this.masterGain.disconnect();
  33518. this.masterGain.connect(this._audioContext.destination);
  33519. this._connectedAnalyser = null;
  33520. }
  33521. this.masterGain.gain.value = 1;
  33522. }
  33523. this.WarnedWebAudioUnsupported = false;
  33524. };
  33525. AudioEngine.prototype.getGlobalVolume = function () {
  33526. if (this.canUseWebAudio && this._audioContextInitialized) {
  33527. return this.masterGain.gain.value;
  33528. }
  33529. else {
  33530. return -1;
  33531. }
  33532. };
  33533. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33534. if (this.canUseWebAudio && this._audioContextInitialized) {
  33535. this.masterGain.gain.value = newVolume;
  33536. }
  33537. };
  33538. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33539. if (this._connectedAnalyser) {
  33540. this._connectedAnalyser.stopDebugCanvas();
  33541. }
  33542. if (this.canUseWebAudio && this._audioContextInitialized) {
  33543. this._connectedAnalyser = analyser;
  33544. this.masterGain.disconnect();
  33545. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33546. }
  33547. };
  33548. return AudioEngine;
  33549. })();
  33550. BABYLON.AudioEngine = AudioEngine;
  33551. })(BABYLON || (BABYLON = {}));
  33552. var BABYLON;
  33553. (function (BABYLON) {
  33554. var Sound = (function () {
  33555. /**
  33556. * Create a sound and attach it to a scene
  33557. * @param name Name of your sound
  33558. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33559. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33560. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33561. */
  33562. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33563. var _this = this;
  33564. this.autoplay = false;
  33565. this.loop = false;
  33566. this.useCustomAttenuation = false;
  33567. this.spatialSound = false;
  33568. this.refDistance = 1;
  33569. this.rolloffFactor = 1;
  33570. this.maxDistance = 100;
  33571. this.distanceModel = "linear";
  33572. this._panningModel = "equalpower";
  33573. this._playbackRate = 1;
  33574. this._streaming = false;
  33575. this._startTime = 0;
  33576. this._startOffset = 0;
  33577. this._position = BABYLON.Vector3.Zero();
  33578. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33579. this._volume = 1;
  33580. this._isLoaded = false;
  33581. this._isReadyToPlay = false;
  33582. this.isPlaying = false;
  33583. this.isPaused = false;
  33584. this._isDirectional = false;
  33585. // Used if you'd like to create a directional sound.
  33586. // If not set, the sound will be omnidirectional
  33587. this._coneInnerAngle = 360;
  33588. this._coneOuterAngle = 360;
  33589. this._coneOuterGain = 0;
  33590. this._isOutputConnected = false;
  33591. this.name = name;
  33592. this._scene = scene;
  33593. this._readyToPlayCallback = readyToPlayCallback;
  33594. // Default custom attenuation function is a linear attenuation
  33595. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33596. if (currentDistance < maxDistance) {
  33597. return currentVolume * (1 - currentDistance / maxDistance);
  33598. }
  33599. else {
  33600. return 0;
  33601. }
  33602. };
  33603. if (options) {
  33604. this.autoplay = options.autoplay || false;
  33605. this.loop = options.loop || false;
  33606. // if volume === 0, we need another way to check this option
  33607. if (options.volume !== undefined) {
  33608. this._volume = options.volume;
  33609. }
  33610. this.spatialSound = options.spatialSound || false;
  33611. this.maxDistance = options.maxDistance || 100;
  33612. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33613. this.rolloffFactor = options.rolloffFactor || 1;
  33614. this.refDistance = options.refDistance || 1;
  33615. this.distanceModel = options.distanceModel || "linear";
  33616. this._playbackRate = options.playbackRate || 1;
  33617. this._streaming = options.streaming || false;
  33618. }
  33619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33620. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33621. this._soundGain.gain.value = this._volume;
  33622. this._inputAudioNode = this._soundGain;
  33623. this._ouputAudioNode = this._soundGain;
  33624. if (this.spatialSound) {
  33625. this._createSpatialParameters();
  33626. }
  33627. this._scene.mainSoundTrack.AddSound(this);
  33628. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33629. if (urlOrArrayBuffer) {
  33630. // If it's an URL
  33631. if (typeof (urlOrArrayBuffer) === "string") {
  33632. // Loading sound using XHR2
  33633. if (!this._streaming) {
  33634. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33635. }
  33636. else {
  33637. this._htmlAudioElement = new Audio();
  33638. this._htmlAudioElement.src = urlOrArrayBuffer;
  33639. this._htmlAudioElement.controls = false;
  33640. this._htmlAudioElement.loop = this.loop;
  33641. this._htmlAudioElement.crossOrigin = "anonymous";
  33642. this._isReadyToPlay = true;
  33643. document.body.appendChild(this._htmlAudioElement);
  33644. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33645. if (this._readyToPlayCallback) {
  33646. window.setTimeout(function () {
  33647. _this._readyToPlayCallback();
  33648. }, 1000);
  33649. }
  33650. if (this.autoplay) {
  33651. this.play();
  33652. }
  33653. }
  33654. }
  33655. else {
  33656. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33657. this._soundLoaded(urlOrArrayBuffer);
  33658. }
  33659. else {
  33660. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33661. }
  33662. }
  33663. }
  33664. }
  33665. else {
  33666. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33667. this._scene.mainSoundTrack.AddSound(this);
  33668. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33669. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33670. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33671. }
  33672. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33673. if (this._readyToPlayCallback) {
  33674. window.setTimeout(function () {
  33675. _this._readyToPlayCallback();
  33676. }, 1000);
  33677. }
  33678. }
  33679. }
  33680. Sound.prototype.dispose = function () {
  33681. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33682. if (this.isPlaying) {
  33683. this.stop();
  33684. }
  33685. this._isReadyToPlay = false;
  33686. if (this.soundTrackId === -1) {
  33687. this._scene.mainSoundTrack.RemoveSound(this);
  33688. }
  33689. else {
  33690. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33691. }
  33692. if (this._soundGain) {
  33693. this._soundGain.disconnect();
  33694. this._soundGain = null;
  33695. }
  33696. if (this._soundPanner) {
  33697. this._soundPanner.disconnect();
  33698. this._soundPanner = null;
  33699. }
  33700. if (this._soundSource) {
  33701. this._soundSource.disconnect();
  33702. this._soundSource = null;
  33703. }
  33704. this._audioBuffer = null;
  33705. if (this._htmlAudioElement) {
  33706. this._htmlAudioElement.pause();
  33707. this._htmlAudioElement.src = "";
  33708. document.body.removeChild(this._htmlAudioElement);
  33709. }
  33710. if (this._connectedMesh) {
  33711. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33712. this._connectedMesh = null;
  33713. }
  33714. }
  33715. };
  33716. Sound.prototype._soundLoaded = function (audioData) {
  33717. var _this = this;
  33718. this._isLoaded = true;
  33719. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33720. _this._audioBuffer = buffer;
  33721. _this._isReadyToPlay = true;
  33722. if (_this.autoplay) {
  33723. _this.play();
  33724. }
  33725. if (_this._readyToPlayCallback) {
  33726. _this._readyToPlayCallback();
  33727. }
  33728. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33729. };
  33730. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33731. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33732. this._audioBuffer = audioBuffer;
  33733. this._isReadyToPlay = true;
  33734. }
  33735. };
  33736. Sound.prototype.updateOptions = function (options) {
  33737. if (options) {
  33738. this.loop = options.loop || this.loop;
  33739. this.maxDistance = options.maxDistance || this.maxDistance;
  33740. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33741. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33742. this.refDistance = options.refDistance || this.refDistance;
  33743. this.distanceModel = options.distanceModel || this.distanceModel;
  33744. this._playbackRate = options.playbackRate || this._playbackRate;
  33745. this._updateSpatialParameters();
  33746. if (this.isPlaying) {
  33747. if (this._streaming) {
  33748. this._htmlAudioElement.playbackRate = this._playbackRate;
  33749. }
  33750. else {
  33751. this._soundSource.playbackRate.value = this._playbackRate;
  33752. }
  33753. }
  33754. }
  33755. };
  33756. Sound.prototype._createSpatialParameters = function () {
  33757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33758. if (this._scene.headphone) {
  33759. this._panningModel = "HRTF";
  33760. }
  33761. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33762. this._updateSpatialParameters();
  33763. this._soundPanner.connect(this._ouputAudioNode);
  33764. this._inputAudioNode = this._soundPanner;
  33765. }
  33766. };
  33767. Sound.prototype._updateSpatialParameters = function () {
  33768. if (this.spatialSound) {
  33769. if (this.useCustomAttenuation) {
  33770. // Tricks to disable in a way embedded Web Audio attenuation
  33771. this._soundPanner.distanceModel = "linear";
  33772. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33773. this._soundPanner.refDistance = 1;
  33774. this._soundPanner.rolloffFactor = 1;
  33775. this._soundPanner.panningModel = this._panningModel;
  33776. }
  33777. else {
  33778. this._soundPanner.distanceModel = this.distanceModel;
  33779. this._soundPanner.maxDistance = this.maxDistance;
  33780. this._soundPanner.refDistance = this.refDistance;
  33781. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33782. this._soundPanner.panningModel = this._panningModel;
  33783. }
  33784. }
  33785. };
  33786. Sound.prototype.switchPanningModelToHRTF = function () {
  33787. this._panningModel = "HRTF";
  33788. this._switchPanningModel();
  33789. };
  33790. Sound.prototype.switchPanningModelToEqualPower = function () {
  33791. this._panningModel = "equalpower";
  33792. this._switchPanningModel();
  33793. };
  33794. Sound.prototype._switchPanningModel = function () {
  33795. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33796. this._soundPanner.panningModel = this._panningModel;
  33797. }
  33798. };
  33799. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33800. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33801. if (this._isOutputConnected) {
  33802. this._ouputAudioNode.disconnect();
  33803. }
  33804. this._ouputAudioNode.connect(soundTrackAudioNode);
  33805. this._isOutputConnected = true;
  33806. }
  33807. };
  33808. /**
  33809. * Transform this sound into a directional source
  33810. * @param coneInnerAngle Size of the inner cone in degree
  33811. * @param coneOuterAngle Size of the outer cone in degree
  33812. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33813. */
  33814. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33815. if (coneOuterAngle < coneInnerAngle) {
  33816. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33817. return;
  33818. }
  33819. this._coneInnerAngle = coneInnerAngle;
  33820. this._coneOuterAngle = coneOuterAngle;
  33821. this._coneOuterGain = coneOuterGain;
  33822. this._isDirectional = true;
  33823. if (this.isPlaying && this.loop) {
  33824. this.stop();
  33825. this.play();
  33826. }
  33827. };
  33828. Sound.prototype.setPosition = function (newPosition) {
  33829. this._position = newPosition;
  33830. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33831. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33832. }
  33833. };
  33834. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33835. this._localDirection = newLocalDirection;
  33836. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33837. this._updateDirection();
  33838. }
  33839. };
  33840. Sound.prototype._updateDirection = function () {
  33841. var mat = this._connectedMesh.getWorldMatrix();
  33842. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33843. direction.normalize();
  33844. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33845. };
  33846. Sound.prototype.updateDistanceFromListener = function () {
  33847. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33848. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33849. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33850. }
  33851. };
  33852. Sound.prototype.setAttenuationFunction = function (callback) {
  33853. this._customAttenuationFunction = callback;
  33854. };
  33855. /**
  33856. * Play the sound
  33857. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33858. */
  33859. Sound.prototype.play = function (time) {
  33860. var _this = this;
  33861. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33862. try {
  33863. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33864. if (!this._soundSource || !this._streamingSource) {
  33865. if (this.spatialSound) {
  33866. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33867. if (this._isDirectional) {
  33868. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33869. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33870. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33871. if (this._connectedMesh) {
  33872. this._updateDirection();
  33873. }
  33874. else {
  33875. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33876. }
  33877. }
  33878. }
  33879. }
  33880. if (this._streaming) {
  33881. if (!this._streamingSource) {
  33882. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33883. this._htmlAudioElement.onended = function () { _this._onended(); };
  33884. this._htmlAudioElement.playbackRate = this._playbackRate;
  33885. }
  33886. this._streamingSource.disconnect();
  33887. this._streamingSource.connect(this._inputAudioNode);
  33888. this._htmlAudioElement.play();
  33889. }
  33890. else {
  33891. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33892. this._soundSource.buffer = this._audioBuffer;
  33893. this._soundSource.connect(this._inputAudioNode);
  33894. this._soundSource.loop = this.loop;
  33895. this._soundSource.playbackRate.value = this._playbackRate;
  33896. this._soundSource.onended = function () { _this._onended(); };
  33897. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33898. }
  33899. this._startTime = startTime;
  33900. this.isPlaying = true;
  33901. this.isPaused = false;
  33902. }
  33903. catch (ex) {
  33904. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33905. }
  33906. }
  33907. };
  33908. Sound.prototype._onended = function () {
  33909. this.isPlaying = false;
  33910. if (this.onended) {
  33911. this.onended();
  33912. }
  33913. };
  33914. /**
  33915. * Stop the sound
  33916. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33917. */
  33918. Sound.prototype.stop = function (time) {
  33919. if (this.isPlaying) {
  33920. if (this._streaming) {
  33921. this._htmlAudioElement.pause();
  33922. // Test needed for Firefox or it will generate an Invalid State Error
  33923. if (this._htmlAudioElement.currentTime > 0) {
  33924. this._htmlAudioElement.currentTime = 0;
  33925. }
  33926. }
  33927. else {
  33928. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33929. this._soundSource.stop(stopTime);
  33930. }
  33931. this.isPlaying = false;
  33932. }
  33933. };
  33934. Sound.prototype.pause = function () {
  33935. if (this.isPlaying) {
  33936. if (this._streaming) {
  33937. this._htmlAudioElement.pause();
  33938. }
  33939. else {
  33940. this.stop(0);
  33941. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33942. }
  33943. this.isPaused = true;
  33944. }
  33945. };
  33946. Sound.prototype.setVolume = function (newVolume, time) {
  33947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33948. if (time) {
  33949. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33950. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33951. }
  33952. else {
  33953. this._soundGain.gain.value = newVolume;
  33954. }
  33955. }
  33956. this._volume = newVolume;
  33957. };
  33958. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33959. this._playbackRate = newPlaybackRate;
  33960. if (this.isPlaying) {
  33961. if (this._streaming) {
  33962. this._htmlAudioElement.playbackRate = this._playbackRate;
  33963. }
  33964. else {
  33965. this._soundSource.playbackRate.value = this._playbackRate;
  33966. }
  33967. }
  33968. };
  33969. Sound.prototype.getVolume = function () {
  33970. return this._volume;
  33971. };
  33972. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33973. var _this = this;
  33974. this._connectedMesh = meshToConnectTo;
  33975. if (!this.spatialSound) {
  33976. this.spatialSound = true;
  33977. this._createSpatialParameters();
  33978. if (this.isPlaying && this.loop) {
  33979. this.stop();
  33980. this.play();
  33981. }
  33982. }
  33983. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33984. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33985. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33986. };
  33987. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33988. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33989. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33990. this._updateDirection();
  33991. }
  33992. };
  33993. return Sound;
  33994. })();
  33995. BABYLON.Sound = Sound;
  33996. })(BABYLON || (BABYLON = {}));
  33997. var BABYLON;
  33998. (function (BABYLON) {
  33999. var SoundTrack = (function () {
  34000. function SoundTrack(scene, options) {
  34001. this.id = -1;
  34002. this._isMainTrack = false;
  34003. this._isInitialized = false;
  34004. this._scene = scene;
  34005. this.soundCollection = new Array();
  34006. this._options = options;
  34007. if (!this._isMainTrack) {
  34008. this._scene.soundTracks.push(this);
  34009. this.id = this._scene.soundTracks.length - 1;
  34010. }
  34011. }
  34012. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34014. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34015. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34016. if (this._options) {
  34017. if (this._options.volume) {
  34018. this._outputAudioNode.gain.value = this._options.volume;
  34019. }
  34020. if (this._options.mainTrack) {
  34021. this._isMainTrack = this._options.mainTrack;
  34022. }
  34023. }
  34024. this._isInitialized = true;
  34025. }
  34026. };
  34027. SoundTrack.prototype.dispose = function () {
  34028. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34029. if (this._connectedAnalyser) {
  34030. this._connectedAnalyser.stopDebugCanvas();
  34031. }
  34032. while (this.soundCollection.length) {
  34033. this.soundCollection[0].dispose();
  34034. }
  34035. if (this._outputAudioNode) {
  34036. this._outputAudioNode.disconnect();
  34037. }
  34038. this._outputAudioNode = null;
  34039. }
  34040. };
  34041. SoundTrack.prototype.AddSound = function (sound) {
  34042. if (!this._isInitialized) {
  34043. this._initializeSoundTrackAudioGraph();
  34044. }
  34045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34046. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34047. }
  34048. if (sound.soundTrackId) {
  34049. if (sound.soundTrackId === -1) {
  34050. this._scene.mainSoundTrack.RemoveSound(sound);
  34051. }
  34052. else {
  34053. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34054. }
  34055. }
  34056. this.soundCollection.push(sound);
  34057. sound.soundTrackId = this.id;
  34058. };
  34059. SoundTrack.prototype.RemoveSound = function (sound) {
  34060. var index = this.soundCollection.indexOf(sound);
  34061. if (index !== -1) {
  34062. this.soundCollection.splice(index, 1);
  34063. }
  34064. };
  34065. SoundTrack.prototype.setVolume = function (newVolume) {
  34066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34067. this._outputAudioNode.gain.value = newVolume;
  34068. }
  34069. };
  34070. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34071. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34072. for (var i = 0; i < this.soundCollection.length; i++) {
  34073. this.soundCollection[i].switchPanningModelToHRTF();
  34074. }
  34075. }
  34076. };
  34077. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34078. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34079. for (var i = 0; i < this.soundCollection.length; i++) {
  34080. this.soundCollection[i].switchPanningModelToEqualPower();
  34081. }
  34082. }
  34083. };
  34084. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34085. if (this._connectedAnalyser) {
  34086. this._connectedAnalyser.stopDebugCanvas();
  34087. }
  34088. this._connectedAnalyser = analyser;
  34089. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34090. this._outputAudioNode.disconnect();
  34091. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34092. }
  34093. };
  34094. return SoundTrack;
  34095. })();
  34096. BABYLON.SoundTrack = SoundTrack;
  34097. })(BABYLON || (BABYLON = {}));
  34098. var BABYLON;
  34099. (function (BABYLON) {
  34100. var DepthRenderer = (function () {
  34101. function DepthRenderer(scene, type) {
  34102. var _this = this;
  34103. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34104. this._viewMatrix = BABYLON.Matrix.Zero();
  34105. this._projectionMatrix = BABYLON.Matrix.Zero();
  34106. this._transformMatrix = BABYLON.Matrix.Zero();
  34107. this._worldViewProjection = BABYLON.Matrix.Zero();
  34108. this._scene = scene;
  34109. var engine = scene.getEngine();
  34110. // Render target
  34111. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34112. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34113. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34114. this._depthMap.refreshRate = 1;
  34115. this._depthMap.renderParticles = false;
  34116. this._depthMap.renderList = null;
  34117. // set default depth value to 1.0 (far away)
  34118. this._depthMap.onClear = function (engine) {
  34119. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34120. };
  34121. // Custom render function
  34122. var renderSubMesh = function (subMesh) {
  34123. var mesh = subMesh.getRenderingMesh();
  34124. var scene = _this._scene;
  34125. var engine = scene.getEngine();
  34126. // Culling
  34127. engine.setState(subMesh.getMaterial().backFaceCulling);
  34128. // Managing instances
  34129. var batch = mesh._getInstancesRenderList(subMesh._id);
  34130. if (batch.mustReturn) {
  34131. return;
  34132. }
  34133. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34134. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34135. engine.enableEffect(_this._effect);
  34136. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34137. var material = subMesh.getMaterial();
  34138. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34139. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34140. // Alpha test
  34141. if (material && material.needAlphaTesting()) {
  34142. var alphaTexture = material.getAlphaTestTexture();
  34143. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34144. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34145. }
  34146. // Bones
  34147. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34148. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34149. }
  34150. // Draw
  34151. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34152. }
  34153. };
  34154. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34155. var index;
  34156. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34157. renderSubMesh(opaqueSubMeshes.data[index]);
  34158. }
  34159. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34160. renderSubMesh(alphaTestSubMeshes.data[index]);
  34161. }
  34162. };
  34163. }
  34164. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34165. var defines = [];
  34166. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34167. var mesh = subMesh.getMesh();
  34168. var scene = mesh.getScene();
  34169. var material = subMesh.getMaterial();
  34170. // Alpha test
  34171. if (material && material.needAlphaTesting()) {
  34172. defines.push("#define ALPHATEST");
  34173. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34174. attribs.push(BABYLON.VertexBuffer.UVKind);
  34175. defines.push("#define UV1");
  34176. }
  34177. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34178. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34179. defines.push("#define UV2");
  34180. }
  34181. }
  34182. // Bones
  34183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34184. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34185. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34186. if (mesh.numBoneInfluencers > 4) {
  34187. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34188. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34189. }
  34190. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34191. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34192. }
  34193. else {
  34194. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34195. }
  34196. // Instances
  34197. if (useInstances) {
  34198. defines.push("#define INSTANCES");
  34199. attribs.push("world0");
  34200. attribs.push("world1");
  34201. attribs.push("world2");
  34202. attribs.push("world3");
  34203. }
  34204. // Get correct effect
  34205. var join = defines.join("\n");
  34206. if (this._cachedDefines !== join) {
  34207. this._cachedDefines = join;
  34208. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34209. }
  34210. return this._effect.isReady();
  34211. };
  34212. DepthRenderer.prototype.getDepthMap = function () {
  34213. return this._depthMap;
  34214. };
  34215. // Methods
  34216. DepthRenderer.prototype.dispose = function () {
  34217. this._depthMap.dispose();
  34218. };
  34219. return DepthRenderer;
  34220. })();
  34221. BABYLON.DepthRenderer = DepthRenderer;
  34222. })(BABYLON || (BABYLON = {}));
  34223. var BABYLON;
  34224. (function (BABYLON) {
  34225. var SSAORenderingPipeline = (function (_super) {
  34226. __extends(SSAORenderingPipeline, _super);
  34227. /**
  34228. * @constructor
  34229. * @param {string} name - The rendering pipeline name
  34230. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34231. * @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 }
  34232. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34233. */
  34234. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34235. var _this = this;
  34236. _super.call(this, scene.getEngine(), name);
  34237. // Members
  34238. /**
  34239. * The PassPostProcess id in the pipeline that contains the original scene color
  34240. * @type {string}
  34241. */
  34242. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34243. /**
  34244. * The SSAO PostProcess id in the pipeline
  34245. * @type {string}
  34246. */
  34247. this.SSAORenderEffect = "SSAORenderEffect";
  34248. /**
  34249. * The horizontal blur PostProcess id in the pipeline
  34250. * @type {string}
  34251. */
  34252. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34253. /**
  34254. * The vertical blur PostProcess id in the pipeline
  34255. * @type {string}
  34256. */
  34257. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34258. /**
  34259. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34260. * @type {string}
  34261. */
  34262. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34263. /**
  34264. * The output strength of the SSAO post-process. Default value is 1.0.
  34265. * @type {number}
  34266. */
  34267. this.totalStrength = 1.0;
  34268. /**
  34269. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  34270. * @type {number}
  34271. */
  34272. this.radius = 0.0002;
  34273. /**
  34274. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34275. * Must not be equal to fallOff and superior to fallOff.
  34276. * Default value is 0.0075
  34277. * @type {number}
  34278. */
  34279. this.area = 0.0075;
  34280. /**
  34281. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34282. * Must not be equal to area and inferior to area.
  34283. * Default value is 0.0002
  34284. * @type {number}
  34285. */
  34286. this.fallOff = 0.0002;
  34287. this._firstUpdate = true;
  34288. this._scene = scene;
  34289. // Set up assets
  34290. this._createRandomTexture();
  34291. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34292. var ssaoRatio = ratio.ssaoRatio || ratio;
  34293. var combineRatio = ratio.combineRatio || ratio;
  34294. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34295. this._createSSAOPostProcess(ssaoRatio);
  34296. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 4.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34297. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 4.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34298. this._createSSAOCombinePostProcess(combineRatio);
  34299. // Set up pipeline
  34300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34301. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34305. // Finish
  34306. scene.postProcessRenderPipelineManager.addPipeline(this);
  34307. if (cameras)
  34308. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34309. }
  34310. // Public Methods
  34311. /**
  34312. * Returns the horizontal blur PostProcess
  34313. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34314. */
  34315. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34316. return this._blurHPostProcess;
  34317. };
  34318. /**
  34319. * Returns the vertical blur PostProcess
  34320. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34321. */
  34322. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34323. return this._blurVPostProcess;
  34324. };
  34325. /**
  34326. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34327. */
  34328. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34329. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34330. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34331. this._originalColorPostProcess = undefined;
  34332. this._ssaoPostProcess = undefined;
  34333. this._blurHPostProcess = undefined;
  34334. this._blurVPostProcess = undefined;
  34335. this._ssaoCombinePostProcess = undefined;
  34336. this._randomTexture.dispose();
  34337. if (disableDepthRender)
  34338. this._scene.disableDepthRenderer();
  34339. };
  34340. // Private Methods
  34341. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34342. var _this = this;
  34343. var sampleSphere = [
  34344. 0.5381, 0.1856, -0.4319,
  34345. 0.1379, 0.2486, 0.4430,
  34346. 0.3371, 0.5679, -0.0057,
  34347. -0.6999, -0.0451, -0.0019,
  34348. 0.0689, -0.1598, -0.8547,
  34349. 0.0560, 0.0069, -0.1843,
  34350. -0.0146, 0.1402, 0.0762,
  34351. 0.0100, -0.1924, -0.0344,
  34352. -0.3577, -0.5301, -0.4358,
  34353. -0.3169, 0.1063, 0.0158,
  34354. 0.0103, -0.5869, 0.0046,
  34355. -0.0897, -0.4940, 0.3287,
  34356. 0.7119, -0.0154, -0.0918,
  34357. -0.0533, 0.0596, -0.5411,
  34358. 0.0352, -0.0631, 0.5460,
  34359. -0.4776, 0.2847, -0.0271
  34360. ];
  34361. var samplesFactor = 1.0 / 16.0;
  34362. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34363. this._ssaoPostProcess.onApply = function (effect) {
  34364. if (_this._firstUpdate) {
  34365. effect.setArray3("sampleSphere", sampleSphere);
  34366. effect.setFloat("samplesFactor", samplesFactor);
  34367. effect.setFloat("randTextureTiles", 4.0);
  34368. _this._firstUpdate = false;
  34369. }
  34370. effect.setFloat("totalStrength", _this.totalStrength);
  34371. effect.setFloat("radius", _this.radius);
  34372. effect.setFloat("area", _this.area);
  34373. effect.setFloat("fallOff", _this.fallOff);
  34374. effect.setTexture("textureSampler", _this._depthTexture);
  34375. effect.setTexture("randomSampler", _this._randomTexture);
  34376. };
  34377. };
  34378. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34379. var _this = this;
  34380. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34381. this._ssaoCombinePostProcess.onApply = function (effect) {
  34382. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34383. };
  34384. };
  34385. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34386. var size = 512;
  34387. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34388. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34389. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34390. var context = this._randomTexture.getContext();
  34391. var rand = function (min, max) {
  34392. return Math.random() * (max - min) + min;
  34393. };
  34394. for (var x = 0; x < size; x++) {
  34395. for (var y = 0; y < size; y++) {
  34396. var randVector = BABYLON.Vector3.Zero();
  34397. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  34398. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  34399. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  34400. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34401. context.fillRect(x, y, 1, 1);
  34402. }
  34403. }
  34404. this._randomTexture.update(false);
  34405. };
  34406. return SSAORenderingPipeline;
  34407. })(BABYLON.PostProcessRenderPipeline);
  34408. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34409. })(BABYLON || (BABYLON = {}));
  34410. var BABYLON;
  34411. (function (BABYLON) {
  34412. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34413. var VolumetricLightScatteringPostProcess = (function (_super) {
  34414. __extends(VolumetricLightScatteringPostProcess, _super);
  34415. /**
  34416. * @constructor
  34417. * @param {string} name - The post-process name
  34418. * @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)
  34419. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34420. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34421. * @param {number} samples - The post-process quality, default 100
  34422. * @param {number} samplingMode - The post-process filtering mode
  34423. * @param {BABYLON.Engine} engine - The babylon engine
  34424. * @param {boolean} reusable - If the post-process is reusable
  34425. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34426. */
  34427. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34428. var _this = this;
  34429. if (samples === void 0) { samples = 100; }
  34430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34431. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34432. this._screenCoordinates = BABYLON.Vector2.Zero();
  34433. /**
  34434. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34435. * @type {boolean}
  34436. */
  34437. this.useCustomMeshPosition = false;
  34438. /**
  34439. * If the post-process should inverse the light scattering direction
  34440. * @type {boolean}
  34441. */
  34442. this.invert = true;
  34443. /**
  34444. * Set to true to use the diffuseColor instead of the diffuseTexture
  34445. * @type {boolean}
  34446. */
  34447. this.useDiffuseColor = false;
  34448. /**
  34449. * Array containing the excluded meshes not rendered in the internal pass
  34450. */
  34451. this.excludedMeshes = new Array();
  34452. /**
  34453. * Controls the overall intensity of the post-process
  34454. * @type {number}
  34455. */
  34456. this.exposure = 0.3;
  34457. /**
  34458. * Dissipates each sample's contribution in range [0, 1]
  34459. * @type {number}
  34460. */
  34461. this.decay = 0.96815;
  34462. /**
  34463. * Controls the overall intensity of each sample
  34464. * @type {number}
  34465. */
  34466. this.weight = 0.58767;
  34467. /**
  34468. * Controls the density of each sample
  34469. * @type {number}
  34470. */
  34471. this.density = 0.926;
  34472. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34473. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34474. // Configure mesh
  34475. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34476. // Configure
  34477. this._createPass(scene, ratio.passRatio || ratio);
  34478. this.onActivate = function (camera) {
  34479. if (!_this.isSupported) {
  34480. _this.dispose(camera);
  34481. }
  34482. _this.onActivate = null;
  34483. };
  34484. this.onApply = function (effect) {
  34485. _this._updateMeshScreenCoordinates(scene);
  34486. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34487. effect.setFloat("exposure", _this.exposure);
  34488. effect.setFloat("decay", _this.decay);
  34489. effect.setFloat("weight", _this.weight);
  34490. effect.setFloat("density", _this.density);
  34491. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34492. };
  34493. }
  34494. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34495. var mesh = subMesh.getMesh();
  34496. var defines = [];
  34497. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34498. var material = subMesh.getMaterial();
  34499. var needUV = false;
  34500. // Render this.mesh as default
  34501. if (mesh === this.mesh) {
  34502. if (this.useDiffuseColor) {
  34503. defines.push("#define DIFFUSE_COLOR_RENDER");
  34504. }
  34505. else if (material) {
  34506. if (material.diffuseTexture !== undefined) {
  34507. defines.push("#define BASIC_RENDER");
  34508. }
  34509. else {
  34510. defines.push("#define DIFFUSE_COLOR_RENDER");
  34511. }
  34512. }
  34513. defines.push("#define NEED_UV");
  34514. needUV = true;
  34515. }
  34516. // Alpha test
  34517. if (material) {
  34518. if (material.needAlphaTesting()) {
  34519. defines.push("#define ALPHATEST");
  34520. }
  34521. if (material.opacityTexture !== undefined) {
  34522. defines.push("#define OPACITY");
  34523. if (material.opacityTexture.getAlphaFromRGB) {
  34524. defines.push("#define OPACITYRGB");
  34525. }
  34526. if (!needUV) {
  34527. defines.push("#define NEED_UV");
  34528. }
  34529. }
  34530. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34531. attribs.push(BABYLON.VertexBuffer.UVKind);
  34532. defines.push("#define UV1");
  34533. }
  34534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34535. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34536. defines.push("#define UV2");
  34537. }
  34538. }
  34539. // Bones
  34540. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34543. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34545. }
  34546. else {
  34547. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34548. }
  34549. // Instances
  34550. if (useInstances) {
  34551. defines.push("#define INSTANCES");
  34552. attribs.push("world0");
  34553. attribs.push("world1");
  34554. attribs.push("world2");
  34555. attribs.push("world3");
  34556. }
  34557. // Get correct effect
  34558. var join = defines.join("\n");
  34559. if (this._cachedDefines !== join) {
  34560. this._cachedDefines = join;
  34561. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34562. }
  34563. return this._volumetricLightScatteringPass.isReady();
  34564. };
  34565. /**
  34566. * Sets the new light position for light scattering effect
  34567. * @param {BABYLON.Vector3} The new custom light position
  34568. */
  34569. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34570. this._customMeshPosition = position;
  34571. };
  34572. /**
  34573. * Returns the light position for light scattering effect
  34574. * @return {BABYLON.Vector3} The custom light position
  34575. */
  34576. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34577. return this._customMeshPosition;
  34578. };
  34579. /**
  34580. * Disposes the internal assets and detaches the post-process from the camera
  34581. */
  34582. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34583. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34584. if (rttIndex !== -1) {
  34585. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34586. }
  34587. this._volumetricLightScatteringRTT.dispose();
  34588. _super.prototype.dispose.call(this, camera);
  34589. };
  34590. /**
  34591. * Returns the render target texture used by the post-process
  34592. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34593. */
  34594. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34595. return this._volumetricLightScatteringRTT;
  34596. };
  34597. // Private methods
  34598. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34599. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34600. return true;
  34601. }
  34602. return false;
  34603. };
  34604. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34605. var _this = this;
  34606. var engine = scene.getEngine();
  34607. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34608. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34609. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34610. this._volumetricLightScatteringRTT.renderList = null;
  34611. this._volumetricLightScatteringRTT.renderParticles = false;
  34612. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34613. // Custom render function for submeshes
  34614. var renderSubMesh = function (subMesh) {
  34615. var mesh = subMesh.getRenderingMesh();
  34616. if (_this._meshExcluded(mesh)) {
  34617. return;
  34618. }
  34619. var scene = mesh.getScene();
  34620. var engine = scene.getEngine();
  34621. // Culling
  34622. engine.setState(subMesh.getMaterial().backFaceCulling);
  34623. // Managing instances
  34624. var batch = mesh._getInstancesRenderList(subMesh._id);
  34625. if (batch.mustReturn) {
  34626. return;
  34627. }
  34628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34629. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34630. engine.enableEffect(_this._volumetricLightScatteringPass);
  34631. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34632. var material = subMesh.getMaterial();
  34633. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34634. // Alpha test
  34635. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34636. var alphaTexture = material.getAlphaTestTexture();
  34637. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34638. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34639. }
  34640. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34641. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34642. if (alphaTexture) {
  34643. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34644. }
  34645. }
  34646. if (material.opacityTexture !== undefined) {
  34647. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34648. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34649. }
  34650. }
  34651. // Bones
  34652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34653. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34654. }
  34655. // Draw
  34656. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34657. }
  34658. };
  34659. // Render target texture callbacks
  34660. var savedSceneClearColor;
  34661. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34662. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34663. savedSceneClearColor = scene.clearColor;
  34664. scene.clearColor = sceneClearColor;
  34665. };
  34666. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34667. scene.clearColor = savedSceneClearColor;
  34668. };
  34669. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34670. var engine = scene.getEngine();
  34671. var index;
  34672. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34673. renderSubMesh(opaqueSubMeshes.data[index]);
  34674. }
  34675. engine.setAlphaTesting(true);
  34676. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34677. renderSubMesh(alphaTestSubMeshes.data[index]);
  34678. }
  34679. engine.setAlphaTesting(false);
  34680. if (transparentSubMeshes.length) {
  34681. // Sort sub meshes
  34682. for (index = 0; index < transparentSubMeshes.length; index++) {
  34683. var submesh = transparentSubMeshes.data[index];
  34684. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34685. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34686. }
  34687. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34688. sortedArray.sort(function (a, b) {
  34689. // Alpha index first
  34690. if (a._alphaIndex > b._alphaIndex) {
  34691. return 1;
  34692. }
  34693. if (a._alphaIndex < b._alphaIndex) {
  34694. return -1;
  34695. }
  34696. // Then distance to camera
  34697. if (a._distanceToCamera < b._distanceToCamera) {
  34698. return 1;
  34699. }
  34700. if (a._distanceToCamera > b._distanceToCamera) {
  34701. return -1;
  34702. }
  34703. return 0;
  34704. });
  34705. // Render sub meshes
  34706. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34707. for (index = 0; index < sortedArray.length; index++) {
  34708. renderSubMesh(sortedArray[index]);
  34709. }
  34710. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34711. }
  34712. };
  34713. };
  34714. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34715. var transform = scene.getTransformMatrix();
  34716. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34717. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34718. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34719. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34720. if (this.invert)
  34721. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34722. };
  34723. // Static methods
  34724. /**
  34725. * Creates a default mesh for the Volumeric Light Scattering post-process
  34726. * @param {string} The mesh name
  34727. * @param {BABYLON.Scene} The scene where to create the mesh
  34728. * @return {BABYLON.Mesh} the default mesh
  34729. */
  34730. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34731. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34732. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34733. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34734. return mesh;
  34735. };
  34736. return VolumetricLightScatteringPostProcess;
  34737. })(BABYLON.PostProcess);
  34738. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34739. })(BABYLON || (BABYLON = {}));
  34740. var BABYLON;
  34741. (function (BABYLON) {
  34742. var LensRenderingPipeline = (function (_super) {
  34743. __extends(LensRenderingPipeline, _super);
  34744. /**
  34745. * @constructor
  34746. *
  34747. * Effect parameters are as follow:
  34748. * {
  34749. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34750. * edge_blur: number; // from 0 to x (1 for realism)
  34751. * distortion: number; // from 0 to x (1 for realism)
  34752. * grain_amount: number; // from 0 to 1
  34753. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34754. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34755. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34756. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34757. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34758. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34759. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34760. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34761. * }
  34762. * Note: if an effect parameter is unset, effect is disabled
  34763. *
  34764. * @param {string} name - The rendering pipeline name
  34765. * @param {object} parameters - An object containing all parameters (see above)
  34766. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34767. * @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)
  34768. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34769. */
  34770. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34771. var _this = this;
  34772. if (ratio === void 0) { ratio = 1.0; }
  34773. _super.call(this, scene.getEngine(), name);
  34774. // Lens effects can be of the following:
  34775. // - chromatic aberration (slight shift of RGB colors)
  34776. // - blur on the edge of the lens
  34777. // - lens distortion
  34778. // - depth-of-field blur & highlights enhancing
  34779. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34780. // - grain effect (noise or custom texture)
  34781. // Two additional texture samplers are needed:
  34782. // - depth map (for depth-of-field)
  34783. // - grain texture
  34784. /**
  34785. * The chromatic aberration PostProcess id in the pipeline
  34786. * @type {string}
  34787. */
  34788. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34789. /**
  34790. * The highlights enhancing PostProcess id in the pipeline
  34791. * @type {string}
  34792. */
  34793. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34794. /**
  34795. * The depth-of-field PostProcess id in the pipeline
  34796. * @type {string}
  34797. */
  34798. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34799. this._scene = scene;
  34800. // Fetch texture samplers
  34801. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34802. if (parameters.grain_texture) {
  34803. this._grainTexture = parameters.grain_texture;
  34804. }
  34805. else {
  34806. this._createGrainTexture();
  34807. }
  34808. // save parameters
  34809. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34810. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34811. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34812. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34813. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34814. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34815. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34816. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34817. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34818. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34819. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34820. // Create effects
  34821. this._createChromaticAberrationPostProcess(ratio);
  34822. this._createHighlightsPostProcess(ratio);
  34823. this._createDepthOfFieldPostProcess(ratio / 4);
  34824. // Set up pipeline
  34825. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34828. if (this._highlightsGain === -1) {
  34829. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34830. }
  34831. // Finish
  34832. scene.postProcessRenderPipelineManager.addPipeline(this);
  34833. if (cameras) {
  34834. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34835. }
  34836. }
  34837. // public methods (self explanatory)
  34838. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34839. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34840. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34841. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34842. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34843. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34844. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34845. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34846. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34847. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34848. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34849. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34850. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  34851. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  34852. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34853. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34854. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34855. this._highlightsGain = amount;
  34856. };
  34857. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34858. if (this._highlightsGain === -1) {
  34859. this._highlightsGain = 1.0;
  34860. }
  34861. this._highlightsThreshold = amount;
  34862. };
  34863. LensRenderingPipeline.prototype.disableHighlights = function () {
  34864. this._highlightsGain = -1;
  34865. };
  34866. /**
  34867. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34868. */
  34869. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34870. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34871. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34872. this._chromaticAberrationPostProcess = undefined;
  34873. this._highlightsPostProcess = undefined;
  34874. this._depthOfFieldPostProcess = undefined;
  34875. this._grainTexture.dispose();
  34876. if (disableDepthRender)
  34877. this._scene.disableDepthRenderer();
  34878. };
  34879. // colors shifting and distortion
  34880. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34881. var _this = this;
  34882. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34883. [], // samplers
  34884. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34885. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34886. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34887. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34888. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34889. };
  34890. };
  34891. // highlights enhancing
  34892. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34893. var _this = this;
  34894. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  34895. [], // samplers
  34896. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34897. this._highlightsPostProcess.onApply = function (effect) {
  34898. effect.setFloat('gain', _this._highlightsGain);
  34899. effect.setFloat('threshold', _this._highlightsThreshold);
  34900. effect.setBool('pentagon', _this._dofPentagon);
  34901. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34902. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34903. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34904. };
  34905. };
  34906. // colors shifting and distortion
  34907. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34908. var _this = this;
  34909. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34910. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34911. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34912. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34913. this._depthOfFieldPostProcess.onApply = function (effect) {
  34914. effect.setTexture("depthSampler", _this._depthTexture);
  34915. effect.setTexture("grainSampler", _this._grainTexture);
  34916. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34917. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34918. effect.setFloat('grain_amount', _this._grainAmount);
  34919. effect.setBool('blur_noise', _this._blurNoise);
  34920. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34921. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34922. effect.setFloat('distortion', _this._distortion);
  34923. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34924. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34925. effect.setFloat('aperture', _this._dofAperture);
  34926. effect.setFloat('darken', _this._dofDarken);
  34927. effect.setFloat('edge_blur', _this._edgeBlur);
  34928. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34929. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34930. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34931. };
  34932. };
  34933. // creates a black and white random noise texture, 512x512
  34934. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34935. var size = 512;
  34936. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34937. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34938. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34939. var context = this._grainTexture.getContext();
  34940. var rand = function (min, max) {
  34941. return Math.random() * (max - min) + min;
  34942. };
  34943. var value;
  34944. for (var x = 0; x < size; x++) {
  34945. for (var y = 0; y < size; y++) {
  34946. value = Math.floor(rand(0.42, 0.58) * 255);
  34947. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34948. context.fillRect(x, y, 1, 1);
  34949. }
  34950. }
  34951. this._grainTexture.update(false);
  34952. };
  34953. return LensRenderingPipeline;
  34954. })(BABYLON.PostProcessRenderPipeline);
  34955. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34956. })(BABYLON || (BABYLON = {}));
  34957. //
  34958. // This post-process allows the modification of rendered colors by using
  34959. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34960. //
  34961. // The object needs to be provided an url to a texture containing the color
  34962. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34963. // Use an image editing software to tweak the LUT to match your needs.
  34964. //
  34965. // For an example of a color LUT, see here:
  34966. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34967. // For explanations on color grading, see here:
  34968. // http://udn.epicgames.com/Three/ColorGrading.html
  34969. //
  34970. var BABYLON;
  34971. (function (BABYLON) {
  34972. var ColorCorrectionPostProcess = (function (_super) {
  34973. __extends(ColorCorrectionPostProcess, _super);
  34974. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34975. var _this = this;
  34976. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34977. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34978. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34979. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34980. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34981. this.onApply = function (effect) {
  34982. effect.setTexture("colorTable", _this._colorTableTexture);
  34983. };
  34984. }
  34985. return ColorCorrectionPostProcess;
  34986. })(BABYLON.PostProcess);
  34987. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34988. })(BABYLON || (BABYLON = {}));
  34989. var BABYLON;
  34990. (function (BABYLON) {
  34991. var AnaglyphFreeCamera = (function (_super) {
  34992. __extends(AnaglyphFreeCamera, _super);
  34993. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34994. _super.call(this, name, position, scene);
  34995. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34996. }
  34997. return AnaglyphFreeCamera;
  34998. })(BABYLON.FreeCamera);
  34999. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35000. var AnaglyphArcRotateCamera = (function (_super) {
  35001. __extends(AnaglyphArcRotateCamera, _super);
  35002. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35003. _super.call(this, name, alpha, beta, radius, target, scene);
  35004. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35005. }
  35006. return AnaglyphArcRotateCamera;
  35007. })(BABYLON.ArcRotateCamera);
  35008. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35009. var AnaglyphGamepadCamera = (function (_super) {
  35010. __extends(AnaglyphGamepadCamera, _super);
  35011. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35012. _super.call(this, name, position, scene);
  35013. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35014. }
  35015. return AnaglyphGamepadCamera;
  35016. })(BABYLON.GamepadCamera);
  35017. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35018. var StereoscopicFreeCamera = (function (_super) {
  35019. __extends(StereoscopicFreeCamera, _super);
  35020. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35021. _super.call(this, name, position, scene);
  35022. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35023. }
  35024. return StereoscopicFreeCamera;
  35025. })(BABYLON.FreeCamera);
  35026. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35027. var StereoscopicArcRotateCamera = (function (_super) {
  35028. __extends(StereoscopicArcRotateCamera, _super);
  35029. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35030. _super.call(this, name, alpha, beta, radius, target, scene);
  35031. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35032. }
  35033. return StereoscopicArcRotateCamera;
  35034. })(BABYLON.ArcRotateCamera);
  35035. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35036. var StereoscopicGamepadCamera = (function (_super) {
  35037. __extends(StereoscopicGamepadCamera, _super);
  35038. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35039. _super.call(this, name, position, scene);
  35040. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35041. }
  35042. return StereoscopicGamepadCamera;
  35043. })(BABYLON.GamepadCamera);
  35044. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35045. })(BABYLON || (BABYLON = {}));
  35046. var BABYLON;
  35047. (function (BABYLON) {
  35048. var HDRRenderingPipeline = (function (_super) {
  35049. __extends(HDRRenderingPipeline, _super);
  35050. /**
  35051. * @constructor
  35052. * @param {string} name - The rendering pipeline name
  35053. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35054. * @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)
  35055. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35056. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35057. */
  35058. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35059. var _this = this;
  35060. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35061. _super.call(this, scene.getEngine(), name);
  35062. /**
  35063. * Public members
  35064. */
  35065. // Gaussian Blur
  35066. /**
  35067. * Gaussian blur coefficient
  35068. * @type {number}
  35069. */
  35070. this.gaussCoeff = 0.3;
  35071. /**
  35072. * Gaussian blur mean
  35073. * @type {number}
  35074. */
  35075. this.gaussMean = 1.0;
  35076. /**
  35077. * Gaussian blur standard deviation
  35078. * @type {number}
  35079. */
  35080. this.gaussStandDev = 0.8;
  35081. // HDR
  35082. /**
  35083. * Exposure, controls the overall intensity of the pipeline
  35084. * @type {number}
  35085. */
  35086. this.exposure = 1.0;
  35087. /**
  35088. * Minimum luminance that the post-process can output. Luminance is >= 0
  35089. * @type {number}
  35090. */
  35091. this.minimumLuminance = 1.0;
  35092. /**
  35093. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35094. * @type {number}
  35095. */
  35096. this.maximumLuminance = 1e20;
  35097. /**
  35098. * Increase rate for luminance: eye adaptation speed to dark
  35099. * @type {number}
  35100. */
  35101. this.luminanceIncreaserate = 0.5;
  35102. /**
  35103. * Decrease rate for luminance: eye adaptation speed to bright
  35104. * @type {number}
  35105. */
  35106. this.luminanceDecreaseRate = 0.5;
  35107. // Bright pass
  35108. /**
  35109. * Minimum luminance needed to compute HDR
  35110. * @type {number}
  35111. */
  35112. this.brightThreshold = 0.8;
  35113. this._needUpdate = true;
  35114. this._scene = scene;
  35115. // Bright pass
  35116. this._createBrightPassPostProcess(scene, ratio);
  35117. // Down sample X4
  35118. this._createDownSampleX4PostProcess(scene, ratio);
  35119. // Create gaussian blur post-processes
  35120. this._createGaussianBlurPostProcess(scene, ratio);
  35121. // Texture adder
  35122. this._createTextureAdderPostProcess(scene, ratio);
  35123. // Luminance generator
  35124. this._createLuminanceGeneratorPostProcess(scene);
  35125. // HDR
  35126. this._createHDRPostProcess(scene, ratio);
  35127. // Pass postprocess
  35128. if (originalPostProcess === null) {
  35129. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35130. }
  35131. else {
  35132. this._originalPostProcess = originalPostProcess;
  35133. }
  35134. // Configure pipeline
  35135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35141. var addDownSamplerPostProcess = function (id) {
  35142. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35143. };
  35144. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35145. addDownSamplerPostProcess(i);
  35146. }
  35147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35148. // Finish
  35149. scene.postProcessRenderPipelineManager.addPipeline(this);
  35150. if (cameras !== null) {
  35151. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35152. }
  35153. this.update();
  35154. }
  35155. /**
  35156. * Tells the pipeline to update its post-processes
  35157. */
  35158. HDRRenderingPipeline.prototype.update = function () {
  35159. this._needUpdate = true;
  35160. };
  35161. /**
  35162. * Returns the current calculated luminance
  35163. */
  35164. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35165. return this._hdrCurrentLuminance;
  35166. };
  35167. /**
  35168. * Returns the currently drawn luminance
  35169. */
  35170. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35171. return this._hdrOutputLuminance;
  35172. };
  35173. /**
  35174. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35175. */
  35176. HDRRenderingPipeline.prototype.dispose = function () {
  35177. this._originalPostProcess = undefined;
  35178. this._brightPassPostProcess = undefined;
  35179. this._downSampleX4PostProcess = undefined;
  35180. this._guassianBlurHPostProcess = undefined;
  35181. this._guassianBlurVPostProcess = undefined;
  35182. this._textureAdderPostProcess = undefined;
  35183. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35184. this._downSamplePostProcesses[i] = undefined;
  35185. }
  35186. this._hdrPostProcess = undefined;
  35187. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35188. };
  35189. /**
  35190. * Creates the HDR post-process and computes the luminance adaptation
  35191. */
  35192. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35193. var _this = this;
  35194. var hdrLastLuminance = 0.0;
  35195. this._hdrOutputLuminance = -1.0;
  35196. this._hdrCurrentLuminance = 1.0;
  35197. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35198. this._hdrPostProcess.onApply = function (effect) {
  35199. if (_this._hdrOutputLuminance < 0.0) {
  35200. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35201. }
  35202. else {
  35203. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35204. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35205. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35206. }
  35207. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35208. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35209. }
  35210. else {
  35211. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35212. }
  35213. }
  35214. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35215. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35216. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35217. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35218. effect.setFloat("exposure", _this.exposure);
  35219. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35220. _this._needUpdate = false;
  35221. };
  35222. };
  35223. /**
  35224. * Texture Adder post-process
  35225. */
  35226. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35227. var _this = this;
  35228. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35229. this._textureAdderPostProcess.onApply = function (effect) {
  35230. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35231. };
  35232. };
  35233. /**
  35234. * Down sample X4 post-process
  35235. */
  35236. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35237. var _this = this;
  35238. var downSampleX4Offsets = new Array(32);
  35239. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35240. this._downSampleX4PostProcess.onApply = function (effect) {
  35241. if (_this._needUpdate) {
  35242. var id = 0;
  35243. for (var i = -2; i < 2; i++) {
  35244. for (var j = -2; j < 2; j++) {
  35245. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35246. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35247. id += 2;
  35248. }
  35249. }
  35250. }
  35251. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35252. };
  35253. };
  35254. /**
  35255. * Bright pass post-process
  35256. */
  35257. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35258. var _this = this;
  35259. var brightOffsets = new Array(8);
  35260. var brightPassCallback = function (effect) {
  35261. if (_this._needUpdate) {
  35262. var sU = (1.0 / _this._brightPassPostProcess.width);
  35263. var sV = (1.0 / _this._brightPassPostProcess.height);
  35264. brightOffsets[0] = -0.5 * sU;
  35265. brightOffsets[1] = 0.5 * sV;
  35266. brightOffsets[2] = 0.5 * sU;
  35267. brightOffsets[3] = 0.5 * sV;
  35268. brightOffsets[4] = -0.5 * sU;
  35269. brightOffsets[5] = -0.5 * sV;
  35270. brightOffsets[6] = 0.5 * sU;
  35271. brightOffsets[7] = -0.5 * sV;
  35272. }
  35273. effect.setArray2("dsOffsets", brightOffsets);
  35274. effect.setFloat("brightThreshold", _this.brightThreshold);
  35275. };
  35276. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35277. this._brightPassPostProcess.onApply = brightPassCallback;
  35278. };
  35279. /**
  35280. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35281. */
  35282. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35283. var _this = this;
  35284. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35285. var luminanceOffsets = new Array(8);
  35286. var downSampleOffsets = new Array(18);
  35287. var halfDestPixelSize;
  35288. this._downSamplePostProcesses = new Array(lumSteps);
  35289. // Utils for luminance
  35290. var luminanceUpdateSourceOffsets = function (width, height) {
  35291. var sU = (1.0 / width);
  35292. var sV = (1.0 / height);
  35293. luminanceOffsets[0] = -0.5 * sU;
  35294. luminanceOffsets[1] = 0.5 * sV;
  35295. luminanceOffsets[2] = 0.5 * sU;
  35296. luminanceOffsets[3] = 0.5 * sV;
  35297. luminanceOffsets[4] = -0.5 * sU;
  35298. luminanceOffsets[5] = -0.5 * sV;
  35299. luminanceOffsets[6] = 0.5 * sU;
  35300. luminanceOffsets[7] = -0.5 * sV;
  35301. };
  35302. var luminanceUpdateDestOffsets = function (width, height) {
  35303. var id = 0;
  35304. for (var x = -1; x < 2; x++) {
  35305. for (var y = -1; y < 2; y++) {
  35306. downSampleOffsets[id] = (x) / width;
  35307. downSampleOffsets[id + 1] = (y) / height;
  35308. id += 2;
  35309. }
  35310. }
  35311. };
  35312. // Luminance callback
  35313. var luminanceCallback = function (effect) {
  35314. if (_this._needUpdate) {
  35315. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35316. }
  35317. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35318. effect.setArray2("lumOffsets", luminanceOffsets);
  35319. };
  35320. // Down sample callbacks
  35321. var downSampleCallback = function (indice) {
  35322. var i = indice;
  35323. return function (effect) {
  35324. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35325. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35326. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35327. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35328. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35329. effect.setArray2("dsOffsets", downSampleOffsets);
  35330. };
  35331. };
  35332. var downSampleAfterRenderCallback = function (effect) {
  35333. // Unpack result
  35334. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35335. 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);
  35336. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35337. };
  35338. // Create luminance post-process
  35339. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35340. 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);
  35341. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35342. // Create down sample post-processes
  35343. for (var i = lumSteps - 2; i >= 0; i--) {
  35344. var length = Math.pow(3, i);
  35345. ratio = { width: length, height: length };
  35346. var defines = "#define DOWN_SAMPLE\n";
  35347. if (i === 0) {
  35348. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35349. }
  35350. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35351. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35352. if (i === 0) {
  35353. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35354. }
  35355. }
  35356. };
  35357. /**
  35358. * Gaussian blur post-processes. Horizontal and Vertical
  35359. */
  35360. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35361. var _this = this;
  35362. var blurOffsetsW = new Array(9);
  35363. var blurOffsetsH = new Array(9);
  35364. var blurWeights = new Array(9);
  35365. var uniforms = ["blurOffsets", "blurWeights"];
  35366. // Utils for gaussian blur
  35367. var calculateBlurOffsets = function (height) {
  35368. var lastOutputDimensions = {
  35369. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  35370. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  35371. };
  35372. for (var i = 0; i < 9; i++) {
  35373. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35374. if (height) {
  35375. blurOffsetsH[i] = value;
  35376. }
  35377. else {
  35378. blurOffsetsW[i] = value;
  35379. }
  35380. }
  35381. };
  35382. var calculateWeights = function () {
  35383. var x = 0.0;
  35384. for (var i = 0; i < 9; i++) {
  35385. x = (i - 4.0) / 4.0;
  35386. 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));
  35387. }
  35388. };
  35389. // Callback
  35390. var gaussianBlurCallback = function (height) {
  35391. return function (effect) {
  35392. if (_this._needUpdate) {
  35393. calculateWeights();
  35394. calculateBlurOffsets(height);
  35395. }
  35396. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35397. effect.setArray("blurWeights", blurWeights);
  35398. };
  35399. };
  35400. // Create horizontal gaussian blur post-processes
  35401. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35402. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35403. // Create vertical gaussian blur post-process
  35404. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35405. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35406. };
  35407. // Luminance generator
  35408. HDRRenderingPipeline.LUM_STEPS = 6;
  35409. return HDRRenderingPipeline;
  35410. })(BABYLON.PostProcessRenderPipeline);
  35411. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35412. })(BABYLON || (BABYLON = {}));
  35413. var BABYLON;
  35414. (function (BABYLON) {
  35415. var FaceAdjacencies = (function () {
  35416. function FaceAdjacencies() {
  35417. this.edges = new Array();
  35418. this.edgesConnectedCount = 0;
  35419. }
  35420. return FaceAdjacencies;
  35421. })();
  35422. var EdgesRenderer = (function () {
  35423. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35424. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35425. if (epsilon === void 0) { epsilon = 0.95; }
  35426. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35427. this._linesPositions = new Array();
  35428. this._linesNormals = new Array();
  35429. this._linesIndices = new Array();
  35430. this._buffers = new Array();
  35431. this._checkVerticesInsteadOfIndices = false;
  35432. this._source = source;
  35433. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35434. this._epsilon = epsilon;
  35435. this._prepareRessources();
  35436. this._generateEdgesLines();
  35437. }
  35438. EdgesRenderer.prototype._prepareRessources = function () {
  35439. if (this._lineShader) {
  35440. return;
  35441. }
  35442. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35443. attributes: ["position", "normal"],
  35444. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35445. });
  35446. this._lineShader.disableDepthWrite = true;
  35447. this._lineShader.backFaceCulling = false;
  35448. };
  35449. EdgesRenderer.prototype.dispose = function () {
  35450. this._vb0.dispose();
  35451. this._vb1.dispose();
  35452. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35453. this._lineShader.dispose();
  35454. };
  35455. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35456. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35457. return 0;
  35458. }
  35459. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35460. return 1;
  35461. }
  35462. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35463. return 2;
  35464. }
  35465. return -1;
  35466. };
  35467. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35468. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35469. return 0;
  35470. }
  35471. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35472. return 1;
  35473. }
  35474. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35475. return 2;
  35476. }
  35477. return -1;
  35478. };
  35479. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35480. var needToCreateLine;
  35481. if (edge === undefined) {
  35482. needToCreateLine = true;
  35483. }
  35484. else {
  35485. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35486. needToCreateLine = dotProduct < this._epsilon;
  35487. }
  35488. if (needToCreateLine) {
  35489. var offset = this._linesPositions.length / 3;
  35490. var normal = p0.subtract(p1);
  35491. normal.normalize();
  35492. // Positions
  35493. this._linesPositions.push(p0.x);
  35494. this._linesPositions.push(p0.y);
  35495. this._linesPositions.push(p0.z);
  35496. this._linesPositions.push(p0.x);
  35497. this._linesPositions.push(p0.y);
  35498. this._linesPositions.push(p0.z);
  35499. this._linesPositions.push(p1.x);
  35500. this._linesPositions.push(p1.y);
  35501. this._linesPositions.push(p1.z);
  35502. this._linesPositions.push(p1.x);
  35503. this._linesPositions.push(p1.y);
  35504. this._linesPositions.push(p1.z);
  35505. // Normals
  35506. this._linesNormals.push(p1.x);
  35507. this._linesNormals.push(p1.y);
  35508. this._linesNormals.push(p1.z);
  35509. this._linesNormals.push(-1);
  35510. this._linesNormals.push(p1.x);
  35511. this._linesNormals.push(p1.y);
  35512. this._linesNormals.push(p1.z);
  35513. this._linesNormals.push(1);
  35514. this._linesNormals.push(p0.x);
  35515. this._linesNormals.push(p0.y);
  35516. this._linesNormals.push(p0.z);
  35517. this._linesNormals.push(-1);
  35518. this._linesNormals.push(p0.x);
  35519. this._linesNormals.push(p0.y);
  35520. this._linesNormals.push(p0.z);
  35521. this._linesNormals.push(1);
  35522. // Indices
  35523. this._linesIndices.push(offset);
  35524. this._linesIndices.push(offset + 1);
  35525. this._linesIndices.push(offset + 2);
  35526. this._linesIndices.push(offset);
  35527. this._linesIndices.push(offset + 2);
  35528. this._linesIndices.push(offset + 3);
  35529. }
  35530. };
  35531. EdgesRenderer.prototype._generateEdgesLines = function () {
  35532. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35533. var indices = this._source.getIndices();
  35534. // First let's find adjacencies
  35535. var adjacencies = new Array();
  35536. var faceNormals = new Array();
  35537. var index;
  35538. var faceAdjacencies;
  35539. // Prepare faces
  35540. for (index = 0; index < indices.length; index += 3) {
  35541. faceAdjacencies = new FaceAdjacencies();
  35542. var p0Index = indices[index];
  35543. var p1Index = indices[index + 1];
  35544. var p2Index = indices[index + 2];
  35545. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35546. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35547. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35548. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35549. faceNormal.normalize();
  35550. faceNormals.push(faceNormal);
  35551. adjacencies.push(faceAdjacencies);
  35552. }
  35553. // Scan
  35554. for (index = 0; index < adjacencies.length; index++) {
  35555. faceAdjacencies = adjacencies[index];
  35556. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35557. var otherFaceAdjacencies = adjacencies[otherIndex];
  35558. if (faceAdjacencies.edgesConnectedCount === 3) {
  35559. break;
  35560. }
  35561. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35562. continue;
  35563. }
  35564. var otherP0 = indices[otherIndex * 3];
  35565. var otherP1 = indices[otherIndex * 3 + 1];
  35566. var otherP2 = indices[otherIndex * 3 + 2];
  35567. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35568. var otherEdgeIndex;
  35569. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35570. continue;
  35571. }
  35572. switch (edgeIndex) {
  35573. case 0:
  35574. if (this._checkVerticesInsteadOfIndices) {
  35575. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35576. }
  35577. else {
  35578. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35579. }
  35580. break;
  35581. case 1:
  35582. if (this._checkVerticesInsteadOfIndices) {
  35583. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35584. }
  35585. else {
  35586. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35587. }
  35588. break;
  35589. case 2:
  35590. if (this._checkVerticesInsteadOfIndices) {
  35591. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35592. }
  35593. else {
  35594. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35595. }
  35596. break;
  35597. }
  35598. if (otherEdgeIndex === -1) {
  35599. continue;
  35600. }
  35601. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35602. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35603. faceAdjacencies.edgesConnectedCount++;
  35604. otherFaceAdjacencies.edgesConnectedCount++;
  35605. if (faceAdjacencies.edgesConnectedCount === 3) {
  35606. break;
  35607. }
  35608. }
  35609. }
  35610. }
  35611. // Create lines
  35612. for (index = 0; index < adjacencies.length; index++) {
  35613. // 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
  35614. var current = adjacencies[index];
  35615. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35616. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35617. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35618. }
  35619. // Merge into a single mesh
  35620. var engine = this._source.getScene().getEngine();
  35621. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35622. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35623. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35624. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35625. this._ib = engine.createIndexBuffer(this._linesIndices);
  35626. this._indicesCount = this._linesIndices.length;
  35627. };
  35628. EdgesRenderer.prototype.render = function () {
  35629. if (!this._lineShader.isReady()) {
  35630. return;
  35631. }
  35632. var scene = this._source.getScene();
  35633. var engine = scene.getEngine();
  35634. this._lineShader._preBind();
  35635. // VBOs
  35636. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35637. scene.resetCachedMaterial();
  35638. this._lineShader.setColor4("color", this._source.edgesColor);
  35639. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35640. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35641. this._lineShader.bind(this._source.getWorldMatrix());
  35642. // Draw order
  35643. engine.draw(true, 0, this._indicesCount);
  35644. this._lineShader.unbind();
  35645. engine.setDepthWrite(true);
  35646. };
  35647. return EdgesRenderer;
  35648. })();
  35649. BABYLON.EdgesRenderer = EdgesRenderer;
  35650. })(BABYLON || (BABYLON = {}));
  35651. var BABYLON;
  35652. (function (BABYLON) {
  35653. (function (TonemappingOperator) {
  35654. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35655. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35656. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35657. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35658. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35659. var TonemappingOperator = BABYLON.TonemappingOperator;
  35660. ;
  35661. var TonemapPostProcess = (function (_super) {
  35662. __extends(TonemapPostProcess, _super);
  35663. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35664. var _this = this;
  35665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35666. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35667. this._operator = operator;
  35668. this._exposureAdjustment = exposureAdjustment;
  35669. var params = ["_ExposureAdjustment"];
  35670. var defines = "#define ";
  35671. if (operator === TonemappingOperator.Hable)
  35672. defines += "HABLE_TONEMAPPING";
  35673. else if (operator === TonemappingOperator.Reinhard)
  35674. defines += "REINHARD_TONEMAPPING";
  35675. else if (operator === TonemappingOperator.HejiDawson)
  35676. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35677. else if (operator === TonemappingOperator.Photographic)
  35678. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35679. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35680. this.onApply = function (effect) {
  35681. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35682. };
  35683. }
  35684. return TonemapPostProcess;
  35685. })(BABYLON.PostProcess);
  35686. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35687. })(BABYLON || (BABYLON = {}));
  35688. var BABYLON;
  35689. (function (BABYLON) {
  35690. var maxSimultaneousLights = 4;
  35691. var PBRMaterialDefines = (function (_super) {
  35692. __extends(PBRMaterialDefines, _super);
  35693. function PBRMaterialDefines() {
  35694. _super.call(this);
  35695. this.ALBEDO = false;
  35696. this.CLIPPLANE = false;
  35697. this.ALPHATEST = false;
  35698. this.FOG = false;
  35699. this.NORMAL = false;
  35700. this.UV1 = false;
  35701. this.UV2 = false;
  35702. this.VERTEXCOLOR = false;
  35703. this.VERTEXALPHA = false;
  35704. this.NUM_BONE_INFLUENCERS = 0;
  35705. this.BonesPerMesh = 0;
  35706. this.INSTANCES = false;
  35707. this.POINTSIZE = false;
  35708. this._keys = Object.keys(this);
  35709. }
  35710. return PBRMaterialDefines;
  35711. })(BABYLON.MaterialDefines);
  35712. var PBRMaterial = (function (_super) {
  35713. __extends(PBRMaterial, _super);
  35714. function PBRMaterial(name, scene) {
  35715. _super.call(this, name, scene);
  35716. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35717. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35718. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35719. this._scaledDiffuse = new BABYLON.Color3();
  35720. this._scaledSpecular = new BABYLON.Color3();
  35721. this._defines = new PBRMaterialDefines();
  35722. this._cachedDefines = new PBRMaterialDefines();
  35723. this._cachedDefines.BonesPerMesh = -1;
  35724. }
  35725. PBRMaterial.prototype.needAlphaBlending = function () {
  35726. return this.alpha < 1.0;
  35727. };
  35728. PBRMaterial.prototype.needAlphaTesting = function () {
  35729. return false;
  35730. };
  35731. PBRMaterial.prototype.getAlphaTestTexture = function () {
  35732. return null;
  35733. };
  35734. // Methods
  35735. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  35736. if (this.checkReadyOnlyOnce) {
  35737. if (this._wasPreviouslyReady) {
  35738. return true;
  35739. }
  35740. }
  35741. var scene = this.getScene();
  35742. if (!this.checkReadyOnEveryCall) {
  35743. if (this._renderId === scene.getRenderId()) {
  35744. return true;
  35745. }
  35746. }
  35747. var engine = scene.getEngine();
  35748. var needNormals = false;
  35749. var needUVs = false;
  35750. this._defines.reset();
  35751. // Textures
  35752. if (scene.texturesEnabled) {
  35753. }
  35754. // Effect
  35755. if (scene.clipPlane) {
  35756. this._defines.CLIPPLANE = true;
  35757. }
  35758. if (engine.getAlphaTesting()) {
  35759. this._defines.ALPHATEST = true;
  35760. }
  35761. // Point size
  35762. if (this.pointsCloud || scene.forcePointsCloud) {
  35763. this._defines.POINTSIZE = true;
  35764. }
  35765. // Fog
  35766. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  35767. this._defines.FOG = true;
  35768. }
  35769. // Lights
  35770. // Attribs
  35771. if (mesh) {
  35772. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35773. this._defines.NORMAL = true;
  35774. }
  35775. if (needUVs) {
  35776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35777. this._defines.UV1 = true;
  35778. }
  35779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35780. this._defines.UV2 = true;
  35781. }
  35782. }
  35783. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35784. this._defines.VERTEXCOLOR = true;
  35785. if (mesh.hasVertexAlpha) {
  35786. this._defines.VERTEXALPHA = true;
  35787. }
  35788. }
  35789. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35790. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  35791. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  35792. }
  35793. // Instances
  35794. if (useInstances) {
  35795. this._defines.INSTANCES = true;
  35796. }
  35797. }
  35798. // Get correct effect
  35799. if (!this._defines.isEqual(this._cachedDefines)) {
  35800. this._defines.cloneTo(this._cachedDefines);
  35801. scene.resetCachedMaterial();
  35802. // Fallbacks
  35803. var fallbacks = new BABYLON.EffectFallbacks();
  35804. if (this._defines.FOG) {
  35805. fallbacks.addFallback(1, "FOG");
  35806. }
  35807. //Attributes
  35808. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35809. if (this._defines.NORMAL) {
  35810. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35811. }
  35812. if (this._defines.UV1) {
  35813. attribs.push(BABYLON.VertexBuffer.UVKind);
  35814. }
  35815. if (this._defines.UV2) {
  35816. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35817. }
  35818. if (this._defines.VERTEXCOLOR) {
  35819. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35820. }
  35821. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  35822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35824. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  35825. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35826. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35827. }
  35828. }
  35829. if (this._defines.INSTANCES) {
  35830. attribs.push("world0");
  35831. attribs.push("world1");
  35832. attribs.push("world2");
  35833. attribs.push("world3");
  35834. }
  35835. // Legacy browser patch
  35836. var join = this._defines.toString();
  35837. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  35838. "vFogInfos", "vFogColor", "pointSize",
  35839. "mBones",
  35840. "vClipPlane",
  35841. ], [], join, fallbacks, this.onCompiled, this.onError);
  35842. }
  35843. if (!this._effect.isReady()) {
  35844. return false;
  35845. }
  35846. this._renderId = scene.getRenderId();
  35847. this._wasPreviouslyReady = true;
  35848. return true;
  35849. };
  35850. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35851. this._effect.setMatrix("world", world);
  35852. };
  35853. PBRMaterial.prototype.bind = function (world, mesh) {
  35854. var scene = this.getScene();
  35855. // Matrices
  35856. this.bindOnlyWorldMatrix(world);
  35857. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35858. // Bones
  35859. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35860. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35861. }
  35862. if (scene.getCachedMaterial() !== this) {
  35863. // Clip plane
  35864. if (scene.clipPlane) {
  35865. var clipPlane = scene.clipPlane;
  35866. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35867. }
  35868. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  35869. }
  35870. // Point size
  35871. if (this.pointsCloud) {
  35872. this._effect.setFloat("pointSize", this.pointSize);
  35873. }
  35874. // Colors
  35875. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  35876. // View
  35877. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35878. this._effect.setMatrix("view", scene.getViewMatrix());
  35879. }
  35880. // Fog
  35881. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35882. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35883. this._effect.setColor3("vFogColor", scene.fogColor);
  35884. }
  35885. _super.prototype.bind.call(this, world, mesh);
  35886. };
  35887. PBRMaterial.prototype.getAnimatables = function () {
  35888. var results = [];
  35889. return results;
  35890. };
  35891. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  35892. _super.prototype.dispose.call(this, forceDisposeEffect);
  35893. };
  35894. PBRMaterial.prototype.clone = function (name) {
  35895. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  35896. // Base material
  35897. this.copyTo(newPBRMaterial);
  35898. // PBRMaterial material
  35899. newPBRMaterial.albedoColor = this.albedoColor.clone();
  35900. return newPBRMaterial;
  35901. };
  35902. return PBRMaterial;
  35903. })(BABYLON.Material);
  35904. BABYLON.PBRMaterial = PBRMaterial;
  35905. })(BABYLON || (BABYLON = {}));
  35906. var BABYLON;
  35907. (function (BABYLON) {
  35908. var ReflectionProbe = (function () {
  35909. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35910. var _this = this;
  35911. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35912. this.name = name;
  35913. this._viewMatrix = BABYLON.Matrix.Identity();
  35914. this._target = BABYLON.Vector3.Zero();
  35915. this._add = BABYLON.Vector3.Zero();
  35916. this.position = BABYLON.Vector3.Zero();
  35917. this._scene = scene;
  35918. this._scene.reflectionProbes.push(this);
  35919. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35920. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35921. switch (faceIndex) {
  35922. case 0:
  35923. _this._add.copyFromFloats(1, 0, 0);
  35924. break;
  35925. case 1:
  35926. _this._add.copyFromFloats(-1, 0, 0);
  35927. break;
  35928. case 2:
  35929. _this._add.copyFromFloats(0, -1, 0);
  35930. break;
  35931. case 3:
  35932. _this._add.copyFromFloats(0, 1, 0);
  35933. break;
  35934. case 4:
  35935. _this._add.copyFromFloats(0, 0, 1);
  35936. break;
  35937. case 5:
  35938. _this._add.copyFromFloats(0, 0, -1);
  35939. break;
  35940. }
  35941. if (_this._attachedMesh) {
  35942. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35943. }
  35944. _this.position.addToRef(_this._add, _this._target);
  35945. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35946. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35947. };
  35948. this._renderTargetTexture.onAfterUnbind = function () {
  35949. scene.updateTransformMatrix(true);
  35950. };
  35951. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35952. }
  35953. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35954. get: function () {
  35955. return this._renderTargetTexture.refreshRate;
  35956. },
  35957. set: function (value) {
  35958. this._renderTargetTexture.refreshRate = value;
  35959. },
  35960. enumerable: true,
  35961. configurable: true
  35962. });
  35963. ReflectionProbe.prototype.getScene = function () {
  35964. return this._scene;
  35965. };
  35966. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35967. get: function () {
  35968. return this._renderTargetTexture;
  35969. },
  35970. enumerable: true,
  35971. configurable: true
  35972. });
  35973. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35974. get: function () {
  35975. return this._renderTargetTexture.renderList;
  35976. },
  35977. enumerable: true,
  35978. configurable: true
  35979. });
  35980. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35981. this._attachedMesh = mesh;
  35982. };
  35983. ReflectionProbe.prototype.dispose = function () {
  35984. var index = this._scene.reflectionProbes.indexOf(this);
  35985. if (index !== -1) {
  35986. // Remove from the scene if found
  35987. this._scene.reflectionProbes.splice(index, 1);
  35988. }
  35989. };
  35990. return ReflectionProbe;
  35991. })();
  35992. BABYLON.ReflectionProbe = ReflectionProbe;
  35993. })(BABYLON || (BABYLON = {}));
  35994. var BABYLON;
  35995. (function (BABYLON) {
  35996. var SolidParticle = (function () {
  35997. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35998. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35999. this.position = BABYLON.Vector3.Zero(); // position
  36000. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36001. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36002. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36003. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36004. this.alive = true; // alive
  36005. this.idx = particleIndex;
  36006. this._pos = positionIndex;
  36007. this._model = model;
  36008. this.shapeId = shapeId;
  36009. this.idxInShape = idxInShape;
  36010. }
  36011. return SolidParticle;
  36012. })();
  36013. BABYLON.SolidParticle = SolidParticle;
  36014. var ModelShape = (function () {
  36015. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36016. this.shapeID = id;
  36017. this._shape = shape;
  36018. this._shapeUV = shapeUV;
  36019. this._positionFunction = posFunction;
  36020. this._vertexFunction = vtxFunction;
  36021. }
  36022. return ModelShape;
  36023. })();
  36024. BABYLON.ModelShape = ModelShape;
  36025. })(BABYLON || (BABYLON = {}));
  36026. var BABYLON;
  36027. (function (BABYLON) {
  36028. var SolidParticleSystem = (function () {
  36029. function SolidParticleSystem(name, scene, options) {
  36030. // public members
  36031. this.particles = new Array();
  36032. this.nbParticles = 0;
  36033. this.billboard = false;
  36034. this.counter = 0;
  36035. this.vars = {};
  36036. this._positions = new Array();
  36037. this._indices = new Array();
  36038. this._normals = new Array();
  36039. this._colors = new Array();
  36040. this._uvs = new Array();
  36041. this._index = 0; // indices index
  36042. this._updatable = true;
  36043. this._pickable = false;
  36044. this._alwaysVisible = false;
  36045. this._shapeCounter = 0;
  36046. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36047. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36048. this._computeParticleColor = true;
  36049. this._computeParticleTexture = true;
  36050. this._computeParticleRotation = true;
  36051. this._computeParticleVertex = false;
  36052. this._cam_axisZ = BABYLON.Vector3.Zero();
  36053. this._cam_axisY = BABYLON.Vector3.Zero();
  36054. this._cam_axisX = BABYLON.Vector3.Zero();
  36055. this._axisX = BABYLON.Axis.X;
  36056. this._axisY = BABYLON.Axis.Y;
  36057. this._axisZ = BABYLON.Axis.Z;
  36058. this._fakeCamPos = BABYLON.Vector3.Zero();
  36059. this._rotMatrix = new BABYLON.Matrix();
  36060. this._rotated = BABYLON.Vector3.Zero();
  36061. this._quaternion = new BABYLON.Quaternion();
  36062. this._vertex = BABYLON.Vector3.Zero();
  36063. this._normal = BABYLON.Vector3.Zero();
  36064. this._yaw = 0.0;
  36065. this._pitch = 0.0;
  36066. this._roll = 0.0;
  36067. this._halfroll = 0.0;
  36068. this._halfpitch = 0.0;
  36069. this._halfyaw = 0.0;
  36070. this._sinRoll = 0.0;
  36071. this._cosRoll = 0.0;
  36072. this._sinPitch = 0.0;
  36073. this._cosPitch = 0.0;
  36074. this._sinYaw = 0.0;
  36075. this._cosYaw = 0.0;
  36076. this._w = 0.0;
  36077. this.name = name;
  36078. this._scene = scene;
  36079. this._camera = scene.activeCamera;
  36080. this._pickable = options ? options.isPickable : false;
  36081. if (options && options.updatable) {
  36082. this._updatable = options.updatable;
  36083. }
  36084. else {
  36085. this._updatable = true;
  36086. }
  36087. if (this._pickable) {
  36088. this.pickedParticles = [];
  36089. }
  36090. }
  36091. // build the SPS mesh : returns the mesh
  36092. SolidParticleSystem.prototype.buildMesh = function () {
  36093. if (this.nbParticles === 0) {
  36094. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36095. this.addShape(triangle, 1);
  36096. triangle.dispose();
  36097. }
  36098. this._positions32 = new Float32Array(this._positions);
  36099. this._uvs32 = new Float32Array(this._uvs);
  36100. this._colors32 = new Float32Array(this._colors);
  36101. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36102. this._normals32 = new Float32Array(this._normals);
  36103. this._fixedNormal32 = new Float32Array(this._normals);
  36104. var vertexData = new BABYLON.VertexData();
  36105. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36106. vertexData.indices = this._indices;
  36107. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36108. if (this._uvs32) {
  36109. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36110. ;
  36111. }
  36112. if (this._colors32) {
  36113. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36114. }
  36115. var mesh = new BABYLON.Mesh(name, this._scene);
  36116. vertexData.applyToMesh(mesh, this._updatable);
  36117. this.mesh = mesh;
  36118. this.mesh.isPickable = this._pickable;
  36119. // free memory
  36120. this._positions = null;
  36121. this._normals = null;
  36122. this._uvs = null;
  36123. this._colors = null;
  36124. if (!this._updatable) {
  36125. this.particles.length = 0;
  36126. }
  36127. return mesh;
  36128. };
  36129. //reset copy
  36130. SolidParticleSystem.prototype._resetCopy = function () {
  36131. this._copy.position.x = 0;
  36132. this._copy.position.y = 0;
  36133. this._copy.position.z = 0;
  36134. this._copy.rotation.x = 0;
  36135. this._copy.rotation.y = 0;
  36136. this._copy.rotation.z = 0;
  36137. this._copy.quaternion = null;
  36138. this._copy.scale.x = 1;
  36139. this._copy.scale.y = 1;
  36140. this._copy.scale.z = 1;
  36141. this._copy.uvs.x = 0;
  36142. this._copy.uvs.y = 0;
  36143. this._copy.uvs.z = 1;
  36144. this._copy.uvs.w = 1;
  36145. this._copy.color = null;
  36146. };
  36147. // _meshBuilder : inserts the shape model in the global SPS mesh
  36148. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36149. var i;
  36150. var u = 0;
  36151. var c = 0;
  36152. this._resetCopy();
  36153. if (options && options.positionFunction) {
  36154. options.positionFunction(this._copy, idx, idxInShape);
  36155. }
  36156. if (this._copy.quaternion) {
  36157. this._quaternion.x = this._copy.quaternion.x;
  36158. this._quaternion.y = this._copy.quaternion.y;
  36159. this._quaternion.z = this._copy.quaternion.z;
  36160. this._quaternion.w = this._copy.quaternion.w;
  36161. }
  36162. else {
  36163. this._yaw = this._copy.rotation.y;
  36164. this._pitch = this._copy.rotation.x;
  36165. this._roll = this._copy.rotation.z;
  36166. this._quaternionRotationYPR();
  36167. }
  36168. this._quaternionToRotationMatrix();
  36169. for (i = 0; i < shape.length; i++) {
  36170. this._vertex.x = shape[i].x;
  36171. this._vertex.y = shape[i].y;
  36172. this._vertex.z = shape[i].z;
  36173. if (options && options.vertexFunction) {
  36174. options.vertexFunction(this._copy, this._vertex, i);
  36175. }
  36176. this._vertex.x *= this._copy.scale.x;
  36177. this._vertex.y *= this._copy.scale.y;
  36178. this._vertex.z *= this._copy.scale.z;
  36179. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36180. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36181. if (meshUV) {
  36182. 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);
  36183. u += 2;
  36184. }
  36185. if (this._copy.color) {
  36186. this._color = this._copy.color;
  36187. }
  36188. else if (meshCol && meshCol[c]) {
  36189. this._color.r = meshCol[c];
  36190. this._color.g = meshCol[c + 1];
  36191. this._color.b = meshCol[c + 2];
  36192. this._color.a = meshCol[c + 3];
  36193. }
  36194. else {
  36195. this._color.r = 1;
  36196. this._color.g = 1;
  36197. this._color.b = 1;
  36198. this._color.a = 1;
  36199. }
  36200. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36201. c += 4;
  36202. }
  36203. for (i = 0; i < meshInd.length; i++) {
  36204. indices.push(p + meshInd[i]);
  36205. }
  36206. if (this._pickable) {
  36207. var nbfaces = meshInd.length / 3;
  36208. for (i = 0; i < nbfaces; i++) {
  36209. this.pickedParticles.push({ idx: idx, faceId: i });
  36210. }
  36211. }
  36212. };
  36213. // returns a shape array from positions array
  36214. SolidParticleSystem.prototype._posToShape = function (positions) {
  36215. var shape = [];
  36216. for (var i = 0; i < positions.length; i += 3) {
  36217. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36218. }
  36219. return shape;
  36220. };
  36221. // returns a shapeUV array from a Vector4 uvs
  36222. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36223. var shapeUV = [];
  36224. if (uvs) {
  36225. for (var i = 0; i < uvs.length; i++)
  36226. shapeUV.push(uvs[i]);
  36227. }
  36228. return shapeUV;
  36229. };
  36230. // adds a new particle object in the particles array
  36231. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36232. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36233. };
  36234. // add solid particles from a shape model in the particles array
  36235. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36236. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36237. var meshInd = mesh.getIndices();
  36238. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36239. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36240. var shape = this._posToShape(meshPos);
  36241. var shapeUV = this._uvsToShapeUV(meshUV);
  36242. var posfunc = options ? options.positionFunction : null;
  36243. var vtxfunc = options ? options.vertexFunction : null;
  36244. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36245. // particles
  36246. var idx = this.nbParticles;
  36247. for (var i = 0; i < nb; i++) {
  36248. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36249. if (this._updatable) {
  36250. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36251. }
  36252. this._index += shape.length;
  36253. idx++;
  36254. }
  36255. this.nbParticles += nb;
  36256. this._shapeCounter++;
  36257. return this._shapeCounter;
  36258. };
  36259. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36260. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36261. this._resetCopy();
  36262. if (particle._model._positionFunction) {
  36263. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36264. }
  36265. if (this._copy.quaternion) {
  36266. this._quaternion.x = this._copy.quaternion.x;
  36267. this._quaternion.y = this._copy.quaternion.y;
  36268. this._quaternion.z = this._copy.quaternion.z;
  36269. this._quaternion.w = this._copy.quaternion.w;
  36270. }
  36271. else {
  36272. this._yaw = this._copy.rotation.y;
  36273. this._pitch = this._copy.rotation.x;
  36274. this._roll = this._copy.rotation.z;
  36275. this._quaternionRotationYPR();
  36276. }
  36277. this._quaternionToRotationMatrix();
  36278. this._shape = particle._model._shape;
  36279. for (var pt = 0; pt < this._shape.length; pt++) {
  36280. this._vertex.x = this._shape[pt].x;
  36281. this._vertex.y = this._shape[pt].y;
  36282. this._vertex.z = this._shape[pt].z;
  36283. if (particle._model._vertexFunction) {
  36284. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36285. }
  36286. this._vertex.x *= this._copy.scale.x;
  36287. this._vertex.y *= this._copy.scale.y;
  36288. this._vertex.z *= this._copy.scale.z;
  36289. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36290. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36291. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36292. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36293. }
  36294. particle.position.x = 0;
  36295. particle.position.y = 0;
  36296. particle.position.z = 0;
  36297. particle.rotation.x = 0;
  36298. particle.rotation.y = 0;
  36299. particle.rotation.z = 0;
  36300. particle.quaternion = null;
  36301. particle.scale.x = 1;
  36302. particle.scale.y = 1;
  36303. particle.scale.z = 1;
  36304. };
  36305. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36306. SolidParticleSystem.prototype.rebuildMesh = function () {
  36307. for (var p = 0; p < this.particles.length; p++) {
  36308. this._rebuildParticle(this.particles[p]);
  36309. }
  36310. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36311. };
  36312. // sets all the particles : updates the VBO
  36313. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36314. if (start === void 0) { start = 0; }
  36315. if (end === void 0) { end = this.nbParticles - 1; }
  36316. if (update === void 0) { update = true; }
  36317. if (!this._updatable) {
  36318. return;
  36319. }
  36320. // custom beforeUpdate
  36321. this.beforeUpdateParticles(start, end, update);
  36322. this._cam_axisX.x = 1;
  36323. this._cam_axisX.y = 0;
  36324. this._cam_axisX.z = 0;
  36325. this._cam_axisY.x = 0;
  36326. this._cam_axisY.y = 1;
  36327. this._cam_axisY.z = 0;
  36328. this._cam_axisZ.x = 0;
  36329. this._cam_axisZ.y = 0;
  36330. this._cam_axisZ.z = 1;
  36331. // if the particles will always face the camera
  36332. if (this.billboard) {
  36333. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36334. this._yaw = this.mesh.rotation.y;
  36335. this._pitch = this.mesh.rotation.x;
  36336. this._roll = this.mesh.rotation.z;
  36337. this._quaternionRotationYPR();
  36338. this._quaternionToRotationMatrix();
  36339. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._rotMatrix, this._fakeCamPos);
  36340. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36341. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36342. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36343. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36344. this._cam_axisY.normalize();
  36345. this._cam_axisX.normalize();
  36346. this._cam_axisZ.normalize();
  36347. }
  36348. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36349. var idx = 0;
  36350. var index = 0;
  36351. var colidx = 0;
  36352. var colorIndex = 0;
  36353. var uvidx = 0;
  36354. var uvIndex = 0;
  36355. // particle loop
  36356. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36357. for (var p = start; p <= end; p++) {
  36358. this._particle = this.particles[p];
  36359. this._shape = this._particle._model._shape;
  36360. this._shapeUV = this._particle._model._shapeUV;
  36361. // call to custom user function to update the particle properties
  36362. this.updateParticle(this._particle);
  36363. // particle rotation matrix
  36364. if (this.billboard) {
  36365. this._particle.rotation.x = 0.0;
  36366. this._particle.rotation.y = 0.0;
  36367. }
  36368. if (this._computeParticleRotation) {
  36369. if (this._particle.quaternion) {
  36370. this._quaternion.x = this._particle.quaternion.x;
  36371. this._quaternion.y = this._particle.quaternion.y;
  36372. this._quaternion.z = this._particle.quaternion.z;
  36373. this._quaternion.w = this._particle.quaternion.w;
  36374. }
  36375. else {
  36376. this._yaw = this._particle.rotation.y;
  36377. this._pitch = this._particle.rotation.x;
  36378. this._roll = this._particle.rotation.z;
  36379. this._quaternionRotationYPR();
  36380. }
  36381. this._quaternionToRotationMatrix();
  36382. }
  36383. for (var pt = 0; pt < this._shape.length; pt++) {
  36384. idx = index + pt * 3;
  36385. colidx = colorIndex + pt * 4;
  36386. uvidx = uvIndex + pt * 2;
  36387. this._vertex.x = this._shape[pt].x;
  36388. this._vertex.y = this._shape[pt].y;
  36389. this._vertex.z = this._shape[pt].z;
  36390. if (this._computeParticleVertex) {
  36391. this.updateParticleVertex(this._particle, this._vertex, pt);
  36392. }
  36393. // positions
  36394. this._vertex.x *= this._particle.scale.x;
  36395. this._vertex.y *= this._particle.scale.y;
  36396. this._vertex.z *= this._particle.scale.z;
  36397. 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];
  36398. 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;
  36399. 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;
  36400. 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;
  36401. 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;
  36402. 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;
  36403. 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;
  36404. // normals : if the particles can't be morphed then just rotate the normals
  36405. if (!this._computeParticleVertex && !this.billboard) {
  36406. this._normal.x = this._fixedNormal32[idx];
  36407. this._normal.y = this._fixedNormal32[idx + 1];
  36408. this._normal.z = this._fixedNormal32[idx + 2];
  36409. 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];
  36410. 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;
  36411. 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;
  36412. 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;
  36413. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36414. 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;
  36415. 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;
  36416. }
  36417. if (this._computeParticleColor) {
  36418. this._colors32[colidx] = this._particle.color.r;
  36419. this._colors32[colidx + 1] = this._particle.color.g;
  36420. this._colors32[colidx + 2] = this._particle.color.b;
  36421. this._colors32[colidx + 3] = this._particle.color.a;
  36422. }
  36423. if (this._computeParticleTexture) {
  36424. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36425. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36426. }
  36427. }
  36428. index = idx + 3;
  36429. colorIndex = colidx + 4;
  36430. uvIndex = uvidx + 2;
  36431. }
  36432. if (update) {
  36433. if (this._computeParticleColor) {
  36434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36435. }
  36436. if (this._computeParticleTexture) {
  36437. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36438. }
  36439. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36440. if (!this.mesh.areNormalsFrozen) {
  36441. if (this._computeParticleVertex || this.billboard) {
  36442. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36443. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36444. for (var i = 0; i < this._normals32.length; i++) {
  36445. this._fixedNormal32[i] = this._normals32[i];
  36446. }
  36447. }
  36448. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36449. }
  36450. }
  36451. this.afterUpdateParticles(start, end, update);
  36452. };
  36453. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36454. this._halfroll = this._roll * 0.5;
  36455. this._halfpitch = this._pitch * 0.5;
  36456. this._halfyaw = this._yaw * 0.5;
  36457. this._sinRoll = Math.sin(this._halfroll);
  36458. this._cosRoll = Math.cos(this._halfroll);
  36459. this._sinPitch = Math.sin(this._halfpitch);
  36460. this._cosPitch = Math.cos(this._halfpitch);
  36461. this._sinYaw = Math.sin(this._halfyaw);
  36462. this._cosYaw = Math.cos(this._halfyaw);
  36463. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36464. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36465. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36466. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36467. };
  36468. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36469. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36470. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36471. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36472. this._rotMatrix.m[3] = 0;
  36473. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36474. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36475. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36476. this._rotMatrix.m[7] = 0;
  36477. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36478. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36479. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36480. this._rotMatrix.m[11] = 0;
  36481. this._rotMatrix.m[12] = 0;
  36482. this._rotMatrix.m[13] = 0;
  36483. this._rotMatrix.m[14] = 0;
  36484. this._rotMatrix.m[15] = 1.0;
  36485. };
  36486. // dispose the SPS
  36487. SolidParticleSystem.prototype.dispose = function () {
  36488. this.mesh.dispose();
  36489. this.vars = null;
  36490. // drop references to internal big arrays for the GC
  36491. this._positions = null;
  36492. this._indices = null;
  36493. this._normals = null;
  36494. this._uvs = null;
  36495. this._colors = null;
  36496. this._positions32 = null;
  36497. this._normals32 = null;
  36498. this._fixedNormal32 = null;
  36499. this._uvs32 = null;
  36500. this._colors32 = null;
  36501. this.pickedParticles = null;
  36502. };
  36503. // Visibilty helpers
  36504. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36505. this.mesh.refreshBoundingInfo();
  36506. };
  36507. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36508. // getter and setter
  36509. get: function () {
  36510. return this._alwaysVisible;
  36511. },
  36512. set: function (val) {
  36513. this._alwaysVisible = val;
  36514. this.mesh.alwaysSelectAsActiveMesh = val;
  36515. },
  36516. enumerable: true,
  36517. configurable: true
  36518. });
  36519. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36520. // getters
  36521. get: function () {
  36522. return this._computeParticleRotation;
  36523. },
  36524. // Optimizer setters
  36525. set: function (val) {
  36526. this._computeParticleRotation = val;
  36527. },
  36528. enumerable: true,
  36529. configurable: true
  36530. });
  36531. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36532. get: function () {
  36533. return this._computeParticleColor;
  36534. },
  36535. set: function (val) {
  36536. this._computeParticleColor = val;
  36537. },
  36538. enumerable: true,
  36539. configurable: true
  36540. });
  36541. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36542. get: function () {
  36543. return this._computeParticleTexture;
  36544. },
  36545. set: function (val) {
  36546. this._computeParticleTexture = val;
  36547. },
  36548. enumerable: true,
  36549. configurable: true
  36550. });
  36551. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36552. get: function () {
  36553. return this._computeParticleVertex;
  36554. },
  36555. set: function (val) {
  36556. this._computeParticleVertex = val;
  36557. },
  36558. enumerable: true,
  36559. configurable: true
  36560. });
  36561. // =======================================================================
  36562. // Particle behavior logic
  36563. // these following methods may be overwritten by the user to fit his needs
  36564. // init : sets all particles first values and calls updateParticle to set them in space
  36565. // can be overwritten by the user
  36566. SolidParticleSystem.prototype.initParticles = function () {
  36567. };
  36568. // recycles a particle : can by overwritten by the user
  36569. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36570. return particle;
  36571. };
  36572. // updates a particle : can be overwritten by the user
  36573. // will be called on each particle by setParticles() :
  36574. // ex : just set a particle position or velocity and recycle conditions
  36575. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36576. return particle;
  36577. };
  36578. // updates a vertex of a particle : can be overwritten by the user
  36579. // will be called on each vertex particle by setParticles() :
  36580. // particle : the current particle
  36581. // vertex : the current index of the current particle
  36582. // pt : the index of the current vertex in the particle shape
  36583. // ex : just set a vertex particle position
  36584. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36585. return vertex;
  36586. };
  36587. // will be called before any other treatment by setParticles()
  36588. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36589. };
  36590. // will be called after all setParticles() treatments
  36591. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36592. };
  36593. return SolidParticleSystem;
  36594. })();
  36595. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36596. })(BABYLON || (BABYLON = {}));
  36597. 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\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\tbias = vReflectionInfos.y;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\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\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\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 bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","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\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = 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, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","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}"};
  36598. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,f=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,f=t.y*a+r.y*u+n.y*m+o.y*y,p=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,f,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=c.X,f=c.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,f)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,f)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.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=o.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,f=y+c;return 0!==f&&1!==f?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*f),t.z=Math.atan2(e-h,u+m)):0===f?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],f=o+a+c;f>0?(n=.5/Math.sqrt(f+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],f=this.m[12],p=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*p,v=m*l-y*p,g=u*x-c*f,d=u*l-y*f,T=u*p-m*f,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),A=1/(i*R+n*_+r*M+o*F),b=h*x-a*l,P=e*x-a*p,C=e*l-h*p,I=s*x-a*f,E=s*l-h*f,q=s*p-e*f,L=h*c-a*y,D=e*c-a*m,S=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*A,t.m[4]=_*A,t.m[8]=M*A,t.m[12]=F*A,t.m[1]=-(n*z-r*w+o*v)*A,t.m[5]=(i*z-r*g+o*d)*A,t.m[9]=-(i*w-n*g+o*T)*A,t.m[13]=(i*v-n*d+r*T)*A,t.m[2]=(n*b-r*P+o*C)*A,t.m[6]=-(i*b-r*I+o*E)*A,t.m[10]=(i*P-n*I+o*q)*A,t.m[14]=-(i*C-n*E+r*q)*A,t.m[3]=-(n*L-r*D+o*S)*A,t.m[7]=(i*L-r*Z+o*N)*A,t.m[11]=-(i*D-n*Z+o*W)*A,t.m[15]=(i*S-n*N+r*W)*A,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],f=this.m[10],p=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],A=t.m[8],b=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],q=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*A+e*I,i[n+1]=r*g+o*_+s*b+e*E,i[n+2]=r*d+o*M+s*P+e*q,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*A+m*I,i[n+5]=h*g+a*_+u*b+m*E,i[n+6]=h*d+a*M+u*P+m*q,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+f*A+p*I,i[n+9]=y*g+c*_+f*b+p*E,i[n+10]=y*d+c*M+f*P+p*q,i[n+11]=y*T+c*F+f*C+p*L,i[n+12]=l*v+x*R+z*A+w*I,i[n+13]=l*g+x*_+z*b+w*E,i[n+14]=l*d+x*M+z*P+w*q,i[n+15]=l*T+x*F+z*C+w*L,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,f,p,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=f,x.m[14]=p,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,f,p,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=f,z.m[13]=p,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){\nr.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,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,f=Math.sqrt(m*m+y*y+c*c);return r=0!==f?1/f:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var y=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=c;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,f=1/(3*s*m+2*e*a+h);a-=(c-t)*f,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var p=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?p.CW:p.CCW,this.angle=l.FromDegrees(this.orientation===p.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),y=m.angle.radians()/e;m.orientation===p.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,f=0;e>f;f++){var l=Math.cos(c)*m.radius+m.centerPoint.x,z=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(l,z),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var y=u.normalize(),c=n-o;return new r(h.x+y.x*c,h.y+y.y*c)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=g;var d=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var T=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=T}(BABYLON||(BABYLON={}));";
  36599. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36600. module.exports = BABYLON;
  36601. };