babylon.max.js 1.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574
  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.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3904. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3905. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3906. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3907. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3908. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3909. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3910. }
  3911. return {
  3912. minimum: minimum,
  3913. maximum: maximum
  3914. };
  3915. };
  3916. Tools.ExtractMinAndMax = function (positions, start, count) {
  3917. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3918. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3919. for (var index = start; index < start + count; index++) {
  3920. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3921. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3922. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3923. }
  3924. return {
  3925. minimum: minimum,
  3926. maximum: maximum
  3927. };
  3928. };
  3929. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3930. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3931. return undefined;
  3932. return Array.isArray(obj) ? obj : [obj];
  3933. };
  3934. // Misc.
  3935. Tools.GetPointerPrefix = function () {
  3936. var eventPrefix = "pointer";
  3937. // Check if hand.js is referenced or if the browser natively supports pointer events
  3938. if (!navigator.pointerEnabled) {
  3939. eventPrefix = "mouse";
  3940. }
  3941. return eventPrefix;
  3942. };
  3943. Tools.QueueNewFrame = function (func) {
  3944. if (window.requestAnimationFrame)
  3945. window.requestAnimationFrame(func);
  3946. else if (window.msRequestAnimationFrame)
  3947. window.msRequestAnimationFrame(func);
  3948. else if (window.webkitRequestAnimationFrame)
  3949. window.webkitRequestAnimationFrame(func);
  3950. else if (window.mozRequestAnimationFrame)
  3951. window.mozRequestAnimationFrame(func);
  3952. else if (window.oRequestAnimationFrame)
  3953. window.oRequestAnimationFrame(func);
  3954. else {
  3955. window.setTimeout(func, 16);
  3956. }
  3957. };
  3958. Tools.RequestFullscreen = function (element) {
  3959. if (element.requestFullscreen)
  3960. element.requestFullscreen();
  3961. else if (element.msRequestFullscreen)
  3962. element.msRequestFullscreen();
  3963. else if (element.webkitRequestFullscreen)
  3964. element.webkitRequestFullscreen();
  3965. else if (element.mozRequestFullScreen)
  3966. element.mozRequestFullScreen();
  3967. };
  3968. Tools.ExitFullscreen = function () {
  3969. if (document.exitFullscreen) {
  3970. document.exitFullscreen();
  3971. }
  3972. else if (document.mozCancelFullScreen) {
  3973. document.mozCancelFullScreen();
  3974. }
  3975. else if (document.webkitCancelFullScreen) {
  3976. document.webkitCancelFullScreen();
  3977. }
  3978. else if (document.msCancelFullScreen) {
  3979. document.msCancelFullScreen();
  3980. }
  3981. };
  3982. // External files
  3983. Tools.CleanUrl = function (url) {
  3984. url = url.replace(/#/mg, "%23");
  3985. return url;
  3986. };
  3987. Tools.LoadImage = function (url, onload, onerror, database) {
  3988. url = Tools.CleanUrl(url);
  3989. var img = new Image();
  3990. if (url.substr(0, 5) !== "data:")
  3991. img.crossOrigin = 'anonymous';
  3992. img.onload = function () {
  3993. onload(img);
  3994. };
  3995. img.onerror = function (err) {
  3996. Tools.Error("Error while trying to load texture: " + url);
  3997. 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";
  3998. onload(img);
  3999. };
  4000. var noIndexedDB = function () {
  4001. img.src = url;
  4002. };
  4003. var loadFromIndexedDB = function () {
  4004. database.loadImageFromDB(url, img);
  4005. };
  4006. //ANY database to do!
  4007. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4008. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4009. }
  4010. else {
  4011. if (url.indexOf("file:") === -1) {
  4012. noIndexedDB();
  4013. }
  4014. else {
  4015. try {
  4016. var textureName = url.substring(5);
  4017. var blobURL;
  4018. try {
  4019. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4020. }
  4021. catch (ex) {
  4022. // Chrome doesn't support oneTimeOnly parameter
  4023. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4024. }
  4025. img.src = blobURL;
  4026. }
  4027. catch (e) {
  4028. img.src = null;
  4029. }
  4030. }
  4031. }
  4032. return img;
  4033. };
  4034. //ANY
  4035. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4036. url = Tools.CleanUrl(url);
  4037. var noIndexedDB = function () {
  4038. var request = new XMLHttpRequest();
  4039. var loadUrl = Tools.BaseUrl + url;
  4040. request.open('GET', loadUrl, true);
  4041. if (useArrayBuffer) {
  4042. request.responseType = "arraybuffer";
  4043. }
  4044. request.onprogress = progressCallBack;
  4045. request.onreadystatechange = function () {
  4046. if (request.readyState === 4) {
  4047. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4048. callback(!useArrayBuffer ? request.responseText : request.response);
  4049. }
  4050. else {
  4051. if (onError) {
  4052. onError();
  4053. }
  4054. else {
  4055. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4056. }
  4057. }
  4058. }
  4059. };
  4060. request.send(null);
  4061. };
  4062. var loadFromIndexedDB = function () {
  4063. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4064. };
  4065. if (url.indexOf("file:") !== -1) {
  4066. var fileName = url.substring(5);
  4067. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4068. }
  4069. else {
  4070. // Caching all files
  4071. if (database && database.enableSceneOffline) {
  4072. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4073. }
  4074. else {
  4075. noIndexedDB();
  4076. }
  4077. }
  4078. };
  4079. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4080. var reader = new FileReader();
  4081. reader.onload = function (e) {
  4082. //target doesn't have result from ts 1.3
  4083. callback(e.target['result']);
  4084. };
  4085. reader.onprogress = progressCallback;
  4086. reader.readAsDataURL(fileToLoad);
  4087. };
  4088. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4089. var reader = new FileReader();
  4090. reader.onerror = function (e) {
  4091. Tools.Log("Error while reading file: " + fileToLoad.name);
  4092. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4093. };
  4094. reader.onload = function (e) {
  4095. //target doesn't have result from ts 1.3
  4096. callback(e.target['result']);
  4097. };
  4098. reader.onprogress = progressCallBack;
  4099. if (!useArrayBuffer) {
  4100. // Asynchronous read
  4101. reader.readAsText(fileToLoad);
  4102. }
  4103. else {
  4104. reader.readAsArrayBuffer(fileToLoad);
  4105. }
  4106. };
  4107. //returns a downloadable url to a file content.
  4108. Tools.FileAsURL = function (content) {
  4109. var fileBlob = new Blob([content]);
  4110. var url = window.URL || window.webkitURL;
  4111. var link = url.createObjectURL(fileBlob);
  4112. return link;
  4113. };
  4114. // Misc.
  4115. Tools.Clamp = function (value, min, max) {
  4116. if (min === void 0) { min = 0; }
  4117. if (max === void 0) { max = 1; }
  4118. return Math.min(max, Math.max(min, value));
  4119. };
  4120. // Returns -1 when value is a negative number and
  4121. // +1 when value is a positive number.
  4122. Tools.Sign = function (value) {
  4123. value = +value; // convert to a number
  4124. if (value === 0 || isNaN(value))
  4125. return value;
  4126. return value > 0 ? 1 : -1;
  4127. };
  4128. Tools.Format = function (value, decimals) {
  4129. if (decimals === void 0) { decimals = 2; }
  4130. return value.toFixed(decimals);
  4131. };
  4132. Tools.CheckExtends = function (v, min, max) {
  4133. if (v.x < min.x)
  4134. min.x = v.x;
  4135. if (v.y < min.y)
  4136. min.y = v.y;
  4137. if (v.z < min.z)
  4138. min.z = v.z;
  4139. if (v.x > max.x)
  4140. max.x = v.x;
  4141. if (v.y > max.y)
  4142. max.y = v.y;
  4143. if (v.z > max.z)
  4144. max.z = v.z;
  4145. };
  4146. Tools.WithinEpsilon = function (a, b, epsilon) {
  4147. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4148. var num = a - b;
  4149. return -epsilon <= num && num <= epsilon;
  4150. };
  4151. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4152. for (var prop in source) {
  4153. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4154. continue;
  4155. }
  4156. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4157. continue;
  4158. }
  4159. var sourceValue = source[prop];
  4160. var typeOfSourceValue = typeof sourceValue;
  4161. if (typeOfSourceValue === "function") {
  4162. continue;
  4163. }
  4164. if (typeOfSourceValue === "object") {
  4165. if (sourceValue instanceof Array) {
  4166. destination[prop] = [];
  4167. if (sourceValue.length > 0) {
  4168. if (typeof sourceValue[0] == "object") {
  4169. for (var index = 0; index < sourceValue.length; index++) {
  4170. var clonedValue = cloneValue(sourceValue[index], destination);
  4171. if (destination[prop].indexOf(clonedValue) === -1) {
  4172. destination[prop].push(clonedValue);
  4173. }
  4174. }
  4175. }
  4176. else {
  4177. destination[prop] = sourceValue.slice(0);
  4178. }
  4179. }
  4180. }
  4181. else {
  4182. destination[prop] = cloneValue(sourceValue, destination);
  4183. }
  4184. }
  4185. else {
  4186. destination[prop] = sourceValue;
  4187. }
  4188. }
  4189. };
  4190. Tools.IsEmpty = function (obj) {
  4191. for (var i in obj) {
  4192. return false;
  4193. }
  4194. return true;
  4195. };
  4196. Tools.RegisterTopRootEvents = function (events) {
  4197. for (var index = 0; index < events.length; index++) {
  4198. var event = events[index];
  4199. window.addEventListener(event.name, event.handler, false);
  4200. try {
  4201. if (window.parent) {
  4202. window.parent.addEventListener(event.name, event.handler, false);
  4203. }
  4204. }
  4205. catch (e) {
  4206. }
  4207. }
  4208. };
  4209. Tools.UnregisterTopRootEvents = function (events) {
  4210. for (var index = 0; index < events.length; index++) {
  4211. var event = events[index];
  4212. window.removeEventListener(event.name, event.handler);
  4213. try {
  4214. if (window.parent) {
  4215. window.parent.removeEventListener(event.name, event.handler);
  4216. }
  4217. }
  4218. catch (e) {
  4219. }
  4220. }
  4221. };
  4222. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4223. // Read the contents of the framebuffer
  4224. var numberOfChannelsByLine = width * 4;
  4225. var halfHeight = height / 2;
  4226. //Reading datas from WebGL
  4227. var data = engine.readPixels(0, 0, width, height);
  4228. //To flip image on Y axis.
  4229. for (var i = 0; i < halfHeight; i++) {
  4230. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4231. var currentCell = j + i * numberOfChannelsByLine;
  4232. var targetLine = height - i - 1;
  4233. var targetCell = j + targetLine * numberOfChannelsByLine;
  4234. var temp = data[currentCell];
  4235. data[currentCell] = data[targetCell];
  4236. data[targetCell] = temp;
  4237. }
  4238. }
  4239. // Create a 2D canvas to store the result
  4240. if (!screenshotCanvas) {
  4241. screenshotCanvas = document.createElement('canvas');
  4242. }
  4243. screenshotCanvas.width = width;
  4244. screenshotCanvas.height = height;
  4245. var context = screenshotCanvas.getContext('2d');
  4246. // Copy the pixels to a 2D canvas
  4247. var imageData = context.createImageData(width, height);
  4248. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4249. var castData = imageData.data;
  4250. castData.set(data);
  4251. context.putImageData(imageData, 0, 0);
  4252. var base64Image = screenshotCanvas.toDataURL();
  4253. if (successCallback) {
  4254. successCallback(base64Image);
  4255. }
  4256. else {
  4257. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4258. if (("download" in document.createElement("a"))) {
  4259. var a = window.document.createElement("a");
  4260. a.href = base64Image;
  4261. var date = new Date();
  4262. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4263. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4264. window.document.body.appendChild(a);
  4265. a.addEventListener("click", function () {
  4266. a.parentElement.removeChild(a);
  4267. });
  4268. a.click();
  4269. }
  4270. else {
  4271. var newWindow = window.open("");
  4272. var img = newWindow.document.createElement("img");
  4273. img.src = base64Image;
  4274. newWindow.document.body.appendChild(img);
  4275. }
  4276. }
  4277. };
  4278. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4279. var width;
  4280. var height;
  4281. //If a precision value is specified
  4282. if (size.precision) {
  4283. width = Math.round(engine.getRenderWidth() * size.precision);
  4284. height = Math.round(width / engine.getAspectRatio(camera));
  4285. size = { width: width, height: height };
  4286. }
  4287. else if (size.width && size.height) {
  4288. width = size.width;
  4289. height = size.height;
  4290. }
  4291. else if (size.width && !size.height) {
  4292. width = size.width;
  4293. height = Math.round(width / engine.getAspectRatio(camera));
  4294. size = { width: width, height: height };
  4295. }
  4296. else if (size.height && !size.width) {
  4297. height = size.height;
  4298. width = Math.round(height * engine.getAspectRatio(camera));
  4299. size = { width: width, height: height };
  4300. }
  4301. else if (!isNaN(size)) {
  4302. height = size;
  4303. width = size;
  4304. }
  4305. else {
  4306. Tools.Error("Invalid 'size' parameter !");
  4307. return;
  4308. }
  4309. var scene = camera.getScene();
  4310. var previousCamera = null;
  4311. if (scene.activeCamera !== camera) {
  4312. previousCamera = scene.activeCamera;
  4313. scene.activeCamera = camera;
  4314. }
  4315. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4316. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4317. texture.renderList = scene.meshes;
  4318. texture.onAfterRender = function () {
  4319. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4320. };
  4321. scene.incrementRenderId();
  4322. texture.render(true);
  4323. texture.dispose();
  4324. if (previousCamera) {
  4325. scene.activeCamera = previousCamera;
  4326. }
  4327. };
  4328. // XHR response validator for local file scenario
  4329. Tools.ValidateXHRData = function (xhr, dataType) {
  4330. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4331. if (dataType === void 0) { dataType = 7; }
  4332. try {
  4333. if (dataType & 1) {
  4334. if (xhr.responseText && xhr.responseText.length > 0) {
  4335. return true;
  4336. }
  4337. else if (dataType === 1) {
  4338. return false;
  4339. }
  4340. }
  4341. if (dataType & 2) {
  4342. // Check header width and height since there is no "TGA" magic number
  4343. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4344. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4345. return true;
  4346. }
  4347. else if (dataType === 2) {
  4348. return false;
  4349. }
  4350. }
  4351. if (dataType & 4) {
  4352. // Check for the "DDS" magic number
  4353. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4354. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4355. return true;
  4356. }
  4357. else {
  4358. return false;
  4359. }
  4360. }
  4361. }
  4362. catch (e) {
  4363. }
  4364. return false;
  4365. };
  4366. Object.defineProperty(Tools, "NoneLogLevel", {
  4367. get: function () {
  4368. return Tools._NoneLogLevel;
  4369. },
  4370. enumerable: true,
  4371. configurable: true
  4372. });
  4373. Object.defineProperty(Tools, "MessageLogLevel", {
  4374. get: function () {
  4375. return Tools._MessageLogLevel;
  4376. },
  4377. enumerable: true,
  4378. configurable: true
  4379. });
  4380. Object.defineProperty(Tools, "WarningLogLevel", {
  4381. get: function () {
  4382. return Tools._WarningLogLevel;
  4383. },
  4384. enumerable: true,
  4385. configurable: true
  4386. });
  4387. Object.defineProperty(Tools, "ErrorLogLevel", {
  4388. get: function () {
  4389. return Tools._ErrorLogLevel;
  4390. },
  4391. enumerable: true,
  4392. configurable: true
  4393. });
  4394. Object.defineProperty(Tools, "AllLogLevel", {
  4395. get: function () {
  4396. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4397. },
  4398. enumerable: true,
  4399. configurable: true
  4400. });
  4401. Tools._AddLogEntry = function (entry) {
  4402. Tools._LogCache = entry + Tools._LogCache;
  4403. if (Tools.OnNewCacheEntry) {
  4404. Tools.OnNewCacheEntry(entry);
  4405. }
  4406. };
  4407. Tools._FormatMessage = function (message) {
  4408. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4409. var date = new Date();
  4410. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4411. };
  4412. Tools._LogDisabled = function (message) {
  4413. // nothing to do
  4414. };
  4415. Tools._LogEnabled = function (message) {
  4416. var formattedMessage = Tools._FormatMessage(message);
  4417. console.log("BJS - " + formattedMessage);
  4418. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4419. Tools._AddLogEntry(entry);
  4420. };
  4421. Tools._WarnDisabled = function (message) {
  4422. // nothing to do
  4423. };
  4424. Tools._WarnEnabled = function (message) {
  4425. var formattedMessage = Tools._FormatMessage(message);
  4426. console.warn("BJS - " + formattedMessage);
  4427. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4428. Tools._AddLogEntry(entry);
  4429. };
  4430. Tools._ErrorDisabled = function (message) {
  4431. // nothing to do
  4432. };
  4433. Tools._ErrorEnabled = function (message) {
  4434. Tools.errorsCount++;
  4435. var formattedMessage = Tools._FormatMessage(message);
  4436. console.error("BJS - " + formattedMessage);
  4437. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4438. Tools._AddLogEntry(entry);
  4439. };
  4440. Object.defineProperty(Tools, "LogCache", {
  4441. get: function () {
  4442. return Tools._LogCache;
  4443. },
  4444. enumerable: true,
  4445. configurable: true
  4446. });
  4447. Tools.ClearLogCache = function () {
  4448. Tools._LogCache = "";
  4449. Tools.errorsCount = 0;
  4450. };
  4451. Object.defineProperty(Tools, "LogLevels", {
  4452. set: function (level) {
  4453. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4454. Tools.Log = Tools._LogEnabled;
  4455. }
  4456. else {
  4457. Tools.Log = Tools._LogDisabled;
  4458. }
  4459. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4460. Tools.Warn = Tools._WarnEnabled;
  4461. }
  4462. else {
  4463. Tools.Warn = Tools._WarnDisabled;
  4464. }
  4465. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4466. Tools.Error = Tools._ErrorEnabled;
  4467. }
  4468. else {
  4469. Tools.Error = Tools._ErrorDisabled;
  4470. }
  4471. },
  4472. enumerable: true,
  4473. configurable: true
  4474. });
  4475. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4476. get: function () {
  4477. return Tools._PerformanceNoneLogLevel;
  4478. },
  4479. enumerable: true,
  4480. configurable: true
  4481. });
  4482. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4483. get: function () {
  4484. return Tools._PerformanceUserMarkLogLevel;
  4485. },
  4486. enumerable: true,
  4487. configurable: true
  4488. });
  4489. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4490. get: function () {
  4491. return Tools._PerformanceConsoleLogLevel;
  4492. },
  4493. enumerable: true,
  4494. configurable: true
  4495. });
  4496. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4497. set: function (level) {
  4498. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4499. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4500. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4501. return;
  4502. }
  4503. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4504. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4505. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4506. return;
  4507. }
  4508. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4509. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4510. },
  4511. enumerable: true,
  4512. configurable: true
  4513. });
  4514. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4515. };
  4516. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4517. };
  4518. Tools._StartUserMark = function (counterName, condition) {
  4519. if (condition === void 0) { condition = true; }
  4520. if (!condition || !Tools._performance.mark) {
  4521. return;
  4522. }
  4523. Tools._performance.mark(counterName + "-Begin");
  4524. };
  4525. Tools._EndUserMark = function (counterName, condition) {
  4526. if (condition === void 0) { condition = true; }
  4527. if (!condition || !Tools._performance.mark) {
  4528. return;
  4529. }
  4530. Tools._performance.mark(counterName + "-End");
  4531. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4532. };
  4533. Tools._StartPerformanceConsole = function (counterName, condition) {
  4534. if (condition === void 0) { condition = true; }
  4535. if (!condition) {
  4536. return;
  4537. }
  4538. Tools._StartUserMark(counterName, condition);
  4539. if (console.time) {
  4540. console.time(counterName);
  4541. }
  4542. };
  4543. Tools._EndPerformanceConsole = function (counterName, condition) {
  4544. if (condition === void 0) { condition = true; }
  4545. if (!condition) {
  4546. return;
  4547. }
  4548. Tools._EndUserMark(counterName, condition);
  4549. if (console.time) {
  4550. console.timeEnd(counterName);
  4551. }
  4552. };
  4553. Object.defineProperty(Tools, "Now", {
  4554. get: function () {
  4555. if (window.performance && window.performance.now) {
  4556. return window.performance.now();
  4557. }
  4558. return new Date().getTime();
  4559. },
  4560. enumerable: true,
  4561. configurable: true
  4562. });
  4563. Tools.BaseUrl = "";
  4564. // Logs
  4565. Tools._NoneLogLevel = 0;
  4566. Tools._MessageLogLevel = 1;
  4567. Tools._WarningLogLevel = 2;
  4568. Tools._ErrorLogLevel = 4;
  4569. Tools._LogCache = "";
  4570. Tools.errorsCount = 0;
  4571. Tools.Log = Tools._LogEnabled;
  4572. Tools.Warn = Tools._WarnEnabled;
  4573. Tools.Error = Tools._ErrorEnabled;
  4574. // Performances
  4575. Tools._PerformanceNoneLogLevel = 0;
  4576. Tools._PerformanceUserMarkLogLevel = 1;
  4577. Tools._PerformanceConsoleLogLevel = 2;
  4578. Tools._performance = window.performance;
  4579. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4580. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4581. return Tools;
  4582. })();
  4583. BABYLON.Tools = Tools;
  4584. /**
  4585. * An implementation of a loop for asynchronous functions.
  4586. */
  4587. var AsyncLoop = (function () {
  4588. /**
  4589. * Constroctor.
  4590. * @param iterations the number of iterations.
  4591. * @param _fn the function to run each iteration
  4592. * @param _successCallback the callback that will be called upon succesful execution
  4593. * @param offset starting offset.
  4594. */
  4595. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4596. if (offset === void 0) { offset = 0; }
  4597. this.iterations = iterations;
  4598. this._fn = _fn;
  4599. this._successCallback = _successCallback;
  4600. this.index = offset - 1;
  4601. this._done = false;
  4602. }
  4603. /**
  4604. * Execute the next iteration. Must be called after the last iteration was finished.
  4605. */
  4606. AsyncLoop.prototype.executeNext = function () {
  4607. if (!this._done) {
  4608. if (this.index + 1 < this.iterations) {
  4609. ++this.index;
  4610. this._fn(this);
  4611. }
  4612. else {
  4613. this.breakLoop();
  4614. }
  4615. }
  4616. };
  4617. /**
  4618. * Break the loop and run the success callback.
  4619. */
  4620. AsyncLoop.prototype.breakLoop = function () {
  4621. this._done = true;
  4622. this._successCallback();
  4623. };
  4624. /**
  4625. * Helper function
  4626. */
  4627. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4628. if (offset === void 0) { offset = 0; }
  4629. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4630. loop.executeNext();
  4631. return loop;
  4632. };
  4633. /**
  4634. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4635. * @param iterations total number of iterations
  4636. * @param syncedIterations number of synchronous iterations in each async iteration.
  4637. * @param fn the function to call each iteration.
  4638. * @param callback a success call back that will be called when iterating stops.
  4639. * @param breakFunction a break condition (optional)
  4640. * @param timeout timeout settings for the setTimeout function. default - 0.
  4641. * @constructor
  4642. */
  4643. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4644. if (timeout === void 0) { timeout = 0; }
  4645. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4646. if (breakFunction && breakFunction())
  4647. loop.breakLoop();
  4648. else {
  4649. setTimeout(function () {
  4650. for (var i = 0; i < syncedIterations; ++i) {
  4651. var iteration = (loop.index * syncedIterations) + i;
  4652. if (iteration >= iterations)
  4653. break;
  4654. fn(iteration);
  4655. if (breakFunction && breakFunction()) {
  4656. loop.breakLoop();
  4657. break;
  4658. }
  4659. }
  4660. loop.executeNext();
  4661. }, timeout);
  4662. }
  4663. }, callback);
  4664. };
  4665. return AsyncLoop;
  4666. })();
  4667. BABYLON.AsyncLoop = AsyncLoop;
  4668. })(BABYLON || (BABYLON = {}));
  4669. var BABYLON;
  4670. (function (BABYLON) {
  4671. var _DepthCullingState = (function () {
  4672. function _DepthCullingState() {
  4673. this._isDepthTestDirty = false;
  4674. this._isDepthMaskDirty = false;
  4675. this._isDepthFuncDirty = false;
  4676. this._isCullFaceDirty = false;
  4677. this._isCullDirty = false;
  4678. this._isZOffsetDirty = false;
  4679. }
  4680. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4681. get: function () {
  4682. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4683. },
  4684. enumerable: true,
  4685. configurable: true
  4686. });
  4687. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4688. get: function () {
  4689. return this._zOffset;
  4690. },
  4691. set: function (value) {
  4692. if (this._zOffset === value) {
  4693. return;
  4694. }
  4695. this._zOffset = value;
  4696. this._isZOffsetDirty = true;
  4697. },
  4698. enumerable: true,
  4699. configurable: true
  4700. });
  4701. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4702. get: function () {
  4703. return this._cullFace;
  4704. },
  4705. set: function (value) {
  4706. if (this._cullFace === value) {
  4707. return;
  4708. }
  4709. this._cullFace = value;
  4710. this._isCullFaceDirty = true;
  4711. },
  4712. enumerable: true,
  4713. configurable: true
  4714. });
  4715. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4716. get: function () {
  4717. return this._cull;
  4718. },
  4719. set: function (value) {
  4720. if (this._cull === value) {
  4721. return;
  4722. }
  4723. this._cull = value;
  4724. this._isCullDirty = true;
  4725. },
  4726. enumerable: true,
  4727. configurable: true
  4728. });
  4729. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4730. get: function () {
  4731. return this._depthFunc;
  4732. },
  4733. set: function (value) {
  4734. if (this._depthFunc === value) {
  4735. return;
  4736. }
  4737. this._depthFunc = value;
  4738. this._isDepthFuncDirty = true;
  4739. },
  4740. enumerable: true,
  4741. configurable: true
  4742. });
  4743. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4744. get: function () {
  4745. return this._depthMask;
  4746. },
  4747. set: function (value) {
  4748. if (this._depthMask === value) {
  4749. return;
  4750. }
  4751. this._depthMask = value;
  4752. this._isDepthMaskDirty = true;
  4753. },
  4754. enumerable: true,
  4755. configurable: true
  4756. });
  4757. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4758. get: function () {
  4759. return this._depthTest;
  4760. },
  4761. set: function (value) {
  4762. if (this._depthTest === value) {
  4763. return;
  4764. }
  4765. this._depthTest = value;
  4766. this._isDepthTestDirty = true;
  4767. },
  4768. enumerable: true,
  4769. configurable: true
  4770. });
  4771. _DepthCullingState.prototype.reset = function () {
  4772. this._depthMask = true;
  4773. this._depthTest = true;
  4774. this._depthFunc = null;
  4775. this._cull = null;
  4776. this._cullFace = null;
  4777. this._zOffset = 0;
  4778. this._isDepthTestDirty = true;
  4779. this._isDepthMaskDirty = true;
  4780. this._isDepthFuncDirty = false;
  4781. this._isCullFaceDirty = false;
  4782. this._isCullDirty = false;
  4783. this._isZOffsetDirty = false;
  4784. };
  4785. _DepthCullingState.prototype.apply = function (gl) {
  4786. if (!this.isDirty) {
  4787. return;
  4788. }
  4789. // Cull
  4790. if (this._isCullDirty) {
  4791. if (this.cull) {
  4792. gl.enable(gl.CULL_FACE);
  4793. }
  4794. else {
  4795. gl.disable(gl.CULL_FACE);
  4796. }
  4797. this._isCullDirty = false;
  4798. }
  4799. // Cull face
  4800. if (this._isCullFaceDirty) {
  4801. gl.cullFace(this.cullFace);
  4802. this._isCullFaceDirty = false;
  4803. }
  4804. // Depth mask
  4805. if (this._isDepthMaskDirty) {
  4806. gl.depthMask(this.depthMask);
  4807. this._isDepthMaskDirty = false;
  4808. }
  4809. // Depth test
  4810. if (this._isDepthTestDirty) {
  4811. if (this.depthTest) {
  4812. gl.enable(gl.DEPTH_TEST);
  4813. }
  4814. else {
  4815. gl.disable(gl.DEPTH_TEST);
  4816. }
  4817. this._isDepthTestDirty = false;
  4818. }
  4819. // Depth func
  4820. if (this._isDepthFuncDirty) {
  4821. gl.depthFunc(this.depthFunc);
  4822. this._isDepthFuncDirty = false;
  4823. }
  4824. // zOffset
  4825. if (this._isZOffsetDirty) {
  4826. if (this.zOffset) {
  4827. gl.enable(gl.POLYGON_OFFSET_FILL);
  4828. gl.polygonOffset(this.zOffset, 0);
  4829. }
  4830. else {
  4831. gl.disable(gl.POLYGON_OFFSET_FILL);
  4832. }
  4833. this._isZOffsetDirty = false;
  4834. }
  4835. };
  4836. return _DepthCullingState;
  4837. })();
  4838. BABYLON._DepthCullingState = _DepthCullingState;
  4839. var _AlphaState = (function () {
  4840. function _AlphaState() {
  4841. this._isAlphaBlendDirty = false;
  4842. this._isBlendFunctionParametersDirty = false;
  4843. this._alphaBlend = false;
  4844. this._blendFunctionParameters = new Array(4);
  4845. }
  4846. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4847. get: function () {
  4848. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4854. get: function () {
  4855. return this._alphaBlend;
  4856. },
  4857. set: function (value) {
  4858. if (this._alphaBlend === value) {
  4859. return;
  4860. }
  4861. this._alphaBlend = value;
  4862. this._isAlphaBlendDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4868. if (this._blendFunctionParameters[0] === value0 &&
  4869. this._blendFunctionParameters[1] === value1 &&
  4870. this._blendFunctionParameters[2] === value2 &&
  4871. this._blendFunctionParameters[3] === value3) {
  4872. return;
  4873. }
  4874. this._blendFunctionParameters[0] = value0;
  4875. this._blendFunctionParameters[1] = value1;
  4876. this._blendFunctionParameters[2] = value2;
  4877. this._blendFunctionParameters[3] = value3;
  4878. this._isBlendFunctionParametersDirty = true;
  4879. };
  4880. _AlphaState.prototype.reset = function () {
  4881. this._alphaBlend = false;
  4882. this._blendFunctionParameters[0] = null;
  4883. this._blendFunctionParameters[1] = null;
  4884. this._blendFunctionParameters[2] = null;
  4885. this._blendFunctionParameters[3] = null;
  4886. this._isAlphaBlendDirty = true;
  4887. this._isBlendFunctionParametersDirty = false;
  4888. };
  4889. _AlphaState.prototype.apply = function (gl) {
  4890. if (!this.isDirty) {
  4891. return;
  4892. }
  4893. // Alpha blend
  4894. if (this._isAlphaBlendDirty) {
  4895. if (this._alphaBlend) {
  4896. gl.enable(gl.BLEND);
  4897. }
  4898. else {
  4899. gl.disable(gl.BLEND);
  4900. }
  4901. this._isAlphaBlendDirty = false;
  4902. }
  4903. // Alpha function
  4904. if (this._isBlendFunctionParametersDirty) {
  4905. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4906. this._isBlendFunctionParametersDirty = false;
  4907. }
  4908. };
  4909. return _AlphaState;
  4910. })();
  4911. BABYLON._AlphaState = _AlphaState;
  4912. var compileShader = function (gl, source, type, defines) {
  4913. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4914. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4915. gl.compileShader(shader);
  4916. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4917. throw new Error(gl.getShaderInfoLog(shader));
  4918. }
  4919. return shader;
  4920. };
  4921. var getWebGLTextureType = function (gl, type) {
  4922. var textureType = gl.UNSIGNED_BYTE;
  4923. if (type === Engine.TEXTURETYPE_FLOAT)
  4924. textureType = gl.FLOAT;
  4925. return textureType;
  4926. };
  4927. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4928. var magFilter = gl.NEAREST;
  4929. var minFilter = gl.NEAREST;
  4930. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4931. magFilter = gl.LINEAR;
  4932. if (generateMipMaps) {
  4933. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  4934. }
  4935. else {
  4936. minFilter = gl.LINEAR;
  4937. }
  4938. }
  4939. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4940. magFilter = gl.LINEAR;
  4941. if (generateMipMaps) {
  4942. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4943. }
  4944. else {
  4945. minFilter = gl.LINEAR;
  4946. }
  4947. }
  4948. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4949. magFilter = gl.NEAREST;
  4950. if (generateMipMaps) {
  4951. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  4952. }
  4953. else {
  4954. minFilter = gl.NEAREST;
  4955. }
  4956. }
  4957. return {
  4958. min: minFilter,
  4959. mag: magFilter
  4960. };
  4961. };
  4962. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  4963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4964. var engine = scene.getEngine();
  4965. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  4966. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  4967. gl.bindTexture(gl.TEXTURE_2D, texture);
  4968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4969. texture._baseWidth = width;
  4970. texture._baseHeight = height;
  4971. texture._width = potWidth;
  4972. texture._height = potHeight;
  4973. texture.isReady = true;
  4974. processFunction(potWidth, potHeight);
  4975. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  4976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4977. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4978. if (!noMipmap && !isCompressed) {
  4979. gl.generateMipmap(gl.TEXTURE_2D);
  4980. }
  4981. gl.bindTexture(gl.TEXTURE_2D, null);
  4982. engine.resetTextureCache();
  4983. scene._removePendingData(texture);
  4984. };
  4985. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  4986. var onload = function () {
  4987. loadedImages[index] = img;
  4988. loadedImages._internalCount++;
  4989. scene._removePendingData(img);
  4990. if (loadedImages._internalCount === 6) {
  4991. onfinish(loadedImages);
  4992. }
  4993. };
  4994. var onerror = function () {
  4995. scene._removePendingData(img);
  4996. };
  4997. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4998. scene._addPendingData(img);
  4999. };
  5000. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5001. var loadedImages = [];
  5002. loadedImages._internalCount = 0;
  5003. for (var index = 0; index < 6; index++) {
  5004. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5005. }
  5006. };
  5007. var EngineCapabilities = (function () {
  5008. function EngineCapabilities() {
  5009. }
  5010. return EngineCapabilities;
  5011. })();
  5012. BABYLON.EngineCapabilities = EngineCapabilities;
  5013. /**
  5014. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5015. */
  5016. var Engine = (function () {
  5017. /**
  5018. * @constructor
  5019. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5020. * @param {boolean} [antialias] - enable antialias
  5021. * @param options - further options to be sent to the getContext function
  5022. */
  5023. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5024. var _this = this;
  5025. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5026. // Public members
  5027. this.isFullscreen = false;
  5028. this.isPointerLock = false;
  5029. this.cullBackFaces = true;
  5030. this.renderEvenInBackground = true;
  5031. // To enable/disable IDB support and avoid XHR on .manifest
  5032. this.enableOfflineSupport = true;
  5033. this.scenes = new Array();
  5034. this._windowIsBackground = false;
  5035. this._drawCalls = 0;
  5036. this._renderingQueueLaunched = false;
  5037. this._activeRenderLoops = [];
  5038. // FPS
  5039. this.fpsRange = 60;
  5040. this.previousFramesDuration = [];
  5041. this.fps = 60;
  5042. this.deltaTime = 0;
  5043. // States
  5044. this._depthCullingState = new _DepthCullingState();
  5045. this._alphaState = new _AlphaState();
  5046. this._alphaMode = Engine.ALPHA_DISABLE;
  5047. // Cache
  5048. this._loadedTexturesCache = new Array();
  5049. this._maxTextureChannels = 16;
  5050. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5051. this._compiledEffects = {};
  5052. this._uintIndicesCurrentlySet = false;
  5053. this._renderingCanvas = canvas;
  5054. options = options || {};
  5055. options.antialias = antialias;
  5056. if (options.preserveDrawingBuffer === undefined) {
  5057. options.preserveDrawingBuffer = false;
  5058. }
  5059. // GL
  5060. try {
  5061. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5062. }
  5063. catch (e) {
  5064. throw new Error("WebGL not supported");
  5065. }
  5066. if (!this._gl) {
  5067. throw new Error("WebGL not supported");
  5068. }
  5069. this._onBlur = function () {
  5070. _this._windowIsBackground = true;
  5071. };
  5072. this._onFocus = function () {
  5073. _this._windowIsBackground = false;
  5074. };
  5075. window.addEventListener("blur", this._onBlur);
  5076. window.addEventListener("focus", this._onFocus);
  5077. // Viewport
  5078. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5079. this.resize();
  5080. // Caps
  5081. this._caps = new EngineCapabilities();
  5082. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5083. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5084. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5085. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5086. // Infos
  5087. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5088. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5089. if (rendererInfo != null) {
  5090. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5091. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5092. }
  5093. if (!this._glVendor) {
  5094. this._glVendor = "Unknown vendor";
  5095. }
  5096. if (!this._glRenderer) {
  5097. this._glRenderer = "Unknown renderer";
  5098. }
  5099. // Extensions
  5100. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5101. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5102. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5103. 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');
  5104. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5105. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5106. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5107. this._caps.highPrecisionShaderSupported = true;
  5108. if (this._gl.getShaderPrecisionFormat) {
  5109. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5110. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5111. }
  5112. // Depth buffer
  5113. this.setDepthBuffer(true);
  5114. this.setDepthFunctionToLessOrEqual();
  5115. this.setDepthWrite(true);
  5116. // Fullscreen
  5117. this._onFullscreenChange = function () {
  5118. if (document.fullscreen !== undefined) {
  5119. _this.isFullscreen = document.fullscreen;
  5120. }
  5121. else if (document.mozFullScreen !== undefined) {
  5122. _this.isFullscreen = document.mozFullScreen;
  5123. }
  5124. else if (document.webkitIsFullScreen !== undefined) {
  5125. _this.isFullscreen = document.webkitIsFullScreen;
  5126. }
  5127. else if (document.msIsFullScreen !== undefined) {
  5128. _this.isFullscreen = document.msIsFullScreen;
  5129. }
  5130. // Pointer lock
  5131. if (_this.isFullscreen && _this._pointerLockRequested) {
  5132. canvas.requestPointerLock = canvas.requestPointerLock ||
  5133. canvas.msRequestPointerLock ||
  5134. canvas.mozRequestPointerLock ||
  5135. canvas.webkitRequestPointerLock;
  5136. if (canvas.requestPointerLock) {
  5137. canvas.requestPointerLock();
  5138. }
  5139. }
  5140. };
  5141. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5142. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5143. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5144. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5145. // Pointer lock
  5146. this._onPointerLockChange = function () {
  5147. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5148. document.webkitPointerLockElement === canvas ||
  5149. document.msPointerLockElement === canvas ||
  5150. document.pointerLockElement === canvas);
  5151. };
  5152. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5153. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5154. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5155. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5156. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5157. Engine.audioEngine = new BABYLON.AudioEngine();
  5158. }
  5159. //default loading screen
  5160. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5161. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5162. }
  5163. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5164. get: function () {
  5165. return Engine._ALPHA_DISABLE;
  5166. },
  5167. enumerable: true,
  5168. configurable: true
  5169. });
  5170. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5171. get: function () {
  5172. return Engine._ALPHA_ONEONE;
  5173. },
  5174. enumerable: true,
  5175. configurable: true
  5176. });
  5177. Object.defineProperty(Engine, "ALPHA_ADD", {
  5178. get: function () {
  5179. return Engine._ALPHA_ADD;
  5180. },
  5181. enumerable: true,
  5182. configurable: true
  5183. });
  5184. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5185. get: function () {
  5186. return Engine._ALPHA_COMBINE;
  5187. },
  5188. enumerable: true,
  5189. configurable: true
  5190. });
  5191. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5192. get: function () {
  5193. return Engine._ALPHA_SUBTRACT;
  5194. },
  5195. enumerable: true,
  5196. configurable: true
  5197. });
  5198. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5199. get: function () {
  5200. return Engine._ALPHA_MULTIPLY;
  5201. },
  5202. enumerable: true,
  5203. configurable: true
  5204. });
  5205. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5206. get: function () {
  5207. return Engine._ALPHA_MAXIMIZED;
  5208. },
  5209. enumerable: true,
  5210. configurable: true
  5211. });
  5212. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5213. get: function () {
  5214. return Engine._DELAYLOADSTATE_NONE;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5220. get: function () {
  5221. return Engine._DELAYLOADSTATE_LOADED;
  5222. },
  5223. enumerable: true,
  5224. configurable: true
  5225. });
  5226. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5227. get: function () {
  5228. return Engine._DELAYLOADSTATE_LOADING;
  5229. },
  5230. enumerable: true,
  5231. configurable: true
  5232. });
  5233. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5234. get: function () {
  5235. return Engine._DELAYLOADSTATE_NOTLOADED;
  5236. },
  5237. enumerable: true,
  5238. configurable: true
  5239. });
  5240. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5241. get: function () {
  5242. return Engine._TEXTUREFORMAT_ALPHA;
  5243. },
  5244. enumerable: true,
  5245. configurable: true
  5246. });
  5247. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5248. get: function () {
  5249. return Engine._TEXTUREFORMAT_LUMINANCE;
  5250. },
  5251. enumerable: true,
  5252. configurable: true
  5253. });
  5254. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5255. get: function () {
  5256. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5257. },
  5258. enumerable: true,
  5259. configurable: true
  5260. });
  5261. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5262. get: function () {
  5263. return Engine._TEXTUREFORMAT_RGB;
  5264. },
  5265. enumerable: true,
  5266. configurable: true
  5267. });
  5268. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5269. get: function () {
  5270. return Engine._TEXTUREFORMAT_RGBA;
  5271. },
  5272. enumerable: true,
  5273. configurable: true
  5274. });
  5275. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5276. get: function () {
  5277. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5278. },
  5279. enumerable: true,
  5280. configurable: true
  5281. });
  5282. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5283. get: function () {
  5284. return Engine._TEXTURETYPE_FLOAT;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. Object.defineProperty(Engine, "Version", {
  5290. get: function () {
  5291. return "2.3.0-alpha";
  5292. },
  5293. enumerable: true,
  5294. configurable: true
  5295. });
  5296. Engine.prototype._prepareWorkingCanvas = function () {
  5297. if (this._workingCanvas) {
  5298. return;
  5299. }
  5300. this._workingCanvas = document.createElement("canvas");
  5301. this._workingContext = this._workingCanvas.getContext("2d");
  5302. };
  5303. Engine.prototype.resetTextureCache = function () {
  5304. for (var index = 0; index < this._maxTextureChannels; index++) {
  5305. this._activeTexturesCache[index] = null;
  5306. }
  5307. };
  5308. Engine.prototype.getGlInfo = function () {
  5309. return {
  5310. vendor: this._glVendor,
  5311. renderer: this._glRenderer,
  5312. version: this._glVersion
  5313. };
  5314. };
  5315. Engine.prototype.getAspectRatio = function (camera) {
  5316. var viewport = camera.viewport;
  5317. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5318. };
  5319. Engine.prototype.getRenderWidth = function () {
  5320. if (this._currentRenderTarget) {
  5321. return this._currentRenderTarget._width;
  5322. }
  5323. return this._renderingCanvas.width;
  5324. };
  5325. Engine.prototype.getRenderHeight = function () {
  5326. if (this._currentRenderTarget) {
  5327. return this._currentRenderTarget._height;
  5328. }
  5329. return this._renderingCanvas.height;
  5330. };
  5331. Engine.prototype.getRenderingCanvas = function () {
  5332. return this._renderingCanvas;
  5333. };
  5334. Engine.prototype.getRenderingCanvasClientRect = function () {
  5335. return this._renderingCanvas.getBoundingClientRect();
  5336. };
  5337. Engine.prototype.setHardwareScalingLevel = function (level) {
  5338. this._hardwareScalingLevel = level;
  5339. this.resize();
  5340. };
  5341. Engine.prototype.getHardwareScalingLevel = function () {
  5342. return this._hardwareScalingLevel;
  5343. };
  5344. Engine.prototype.getLoadedTexturesCache = function () {
  5345. return this._loadedTexturesCache;
  5346. };
  5347. Engine.prototype.getCaps = function () {
  5348. return this._caps;
  5349. };
  5350. Object.defineProperty(Engine.prototype, "drawCalls", {
  5351. get: function () {
  5352. return this._drawCalls;
  5353. },
  5354. enumerable: true,
  5355. configurable: true
  5356. });
  5357. // Methods
  5358. Engine.prototype.resetDrawCalls = function () {
  5359. this._drawCalls = 0;
  5360. };
  5361. Engine.prototype.setDepthFunctionToGreater = function () {
  5362. this._depthCullingState.depthFunc = this._gl.GREATER;
  5363. };
  5364. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5365. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5366. };
  5367. Engine.prototype.setDepthFunctionToLess = function () {
  5368. this._depthCullingState.depthFunc = this._gl.LESS;
  5369. };
  5370. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5371. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5372. };
  5373. /**
  5374. * stop executing a render loop function and remove it from the execution array
  5375. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5376. */
  5377. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5378. if (!renderFunction) {
  5379. this._activeRenderLoops = [];
  5380. return;
  5381. }
  5382. var index = this._activeRenderLoops.indexOf(renderFunction);
  5383. if (index >= 0) {
  5384. this._activeRenderLoops.splice(index, 1);
  5385. }
  5386. };
  5387. Engine.prototype._renderLoop = function () {
  5388. var shouldRender = true;
  5389. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5390. shouldRender = false;
  5391. }
  5392. if (shouldRender) {
  5393. // Start new frame
  5394. this.beginFrame();
  5395. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5396. var renderFunction = this._activeRenderLoops[index];
  5397. renderFunction();
  5398. }
  5399. // Present
  5400. this.endFrame();
  5401. }
  5402. if (this._activeRenderLoops.length > 0) {
  5403. // Register new frame
  5404. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5405. }
  5406. else {
  5407. this._renderingQueueLaunched = false;
  5408. }
  5409. };
  5410. /**
  5411. * Register and execute a render loop. The engine can have more than one render function.
  5412. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5413. * @example
  5414. * engine.runRenderLoop(function () {
  5415. * scene.render()
  5416. * })
  5417. */
  5418. Engine.prototype.runRenderLoop = function (renderFunction) {
  5419. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5420. return;
  5421. }
  5422. this._activeRenderLoops.push(renderFunction);
  5423. if (!this._renderingQueueLaunched) {
  5424. this._renderingQueueLaunched = true;
  5425. this._bindedRenderFunction = this._renderLoop.bind(this);
  5426. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5427. }
  5428. };
  5429. /**
  5430. * Toggle full screen mode.
  5431. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5432. */
  5433. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5434. if (this.isFullscreen) {
  5435. BABYLON.Tools.ExitFullscreen();
  5436. }
  5437. else {
  5438. this._pointerLockRequested = requestPointerLock;
  5439. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5440. }
  5441. };
  5442. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5443. this.applyStates();
  5444. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5445. if (this._depthCullingState.depthMask) {
  5446. this._gl.clearDepth(1.0);
  5447. }
  5448. var mode = 0;
  5449. if (backBuffer)
  5450. mode |= this._gl.COLOR_BUFFER_BIT;
  5451. if (depthStencil && this._depthCullingState.depthMask)
  5452. mode |= this._gl.DEPTH_BUFFER_BIT;
  5453. this._gl.clear(mode);
  5454. };
  5455. /**
  5456. * Set the WebGL's viewport
  5457. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5458. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5459. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5460. */
  5461. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5462. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5463. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5464. var x = viewport.x || 0;
  5465. var y = viewport.y || 0;
  5466. this._cachedViewport = viewport;
  5467. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5468. };
  5469. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5470. this._cachedViewport = null;
  5471. this._gl.viewport(x, y, width, height);
  5472. };
  5473. Engine.prototype.beginFrame = function () {
  5474. this._measureFps();
  5475. };
  5476. Engine.prototype.endFrame = function () {
  5477. //this.flushFramebuffer();
  5478. };
  5479. /**
  5480. * resize the view according to the canvas' size.
  5481. * @example
  5482. * window.addEventListener("resize", function () {
  5483. * engine.resize();
  5484. * });
  5485. */
  5486. Engine.prototype.resize = function () {
  5487. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5488. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5489. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5490. for (var index = 0; index < this.scenes.length; index++) {
  5491. var scene = this.scenes[index];
  5492. if (scene.debugLayer.isVisible()) {
  5493. scene.debugLayer._syncPositions();
  5494. }
  5495. }
  5496. };
  5497. /**
  5498. * force a specific size of the canvas
  5499. * @param {number} width - the new canvas' width
  5500. * @param {number} height - the new canvas' height
  5501. */
  5502. Engine.prototype.setSize = function (width, height) {
  5503. this._renderingCanvas.width = width;
  5504. this._renderingCanvas.height = height;
  5505. for (var index = 0; index < this.scenes.length; index++) {
  5506. var scene = this.scenes[index];
  5507. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5508. var cam = scene.cameras[camIndex];
  5509. cam._currentRenderId = 0;
  5510. }
  5511. }
  5512. };
  5513. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5514. this._currentRenderTarget = texture;
  5515. var gl = this._gl;
  5516. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5517. if (texture.isCube) {
  5518. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5519. }
  5520. else {
  5521. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5522. }
  5523. this._gl.viewport(0, 0, texture._width, texture._height);
  5524. this.wipeCaches();
  5525. };
  5526. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5527. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5528. this._currentRenderTarget = null;
  5529. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5530. var gl = this._gl;
  5531. gl.bindTexture(gl.TEXTURE_2D, texture);
  5532. gl.generateMipmap(gl.TEXTURE_2D);
  5533. gl.bindTexture(gl.TEXTURE_2D, null);
  5534. }
  5535. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5536. };
  5537. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5538. if (texture.generateMipMaps) {
  5539. var gl = this._gl;
  5540. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5541. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5542. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5543. }
  5544. };
  5545. Engine.prototype.flushFramebuffer = function () {
  5546. this._gl.flush();
  5547. };
  5548. Engine.prototype.restoreDefaultFramebuffer = function () {
  5549. this._currentRenderTarget = null;
  5550. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5551. this.setViewport(this._cachedViewport);
  5552. this.wipeCaches();
  5553. };
  5554. // VBOs
  5555. Engine.prototype._resetVertexBufferBinding = function () {
  5556. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5557. this._cachedVertexBuffers = null;
  5558. };
  5559. Engine.prototype.createVertexBuffer = function (vertices) {
  5560. var vbo = this._gl.createBuffer();
  5561. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5562. if (vertices instanceof Float32Array) {
  5563. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5564. }
  5565. else {
  5566. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5567. }
  5568. this._resetVertexBufferBinding();
  5569. vbo.references = 1;
  5570. return vbo;
  5571. };
  5572. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5573. var vbo = this._gl.createBuffer();
  5574. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5575. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5576. this._resetVertexBufferBinding();
  5577. vbo.references = 1;
  5578. return vbo;
  5579. };
  5580. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5581. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5582. if (offset === undefined) {
  5583. offset = 0;
  5584. }
  5585. if (vertices instanceof Float32Array) {
  5586. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5587. }
  5588. else {
  5589. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5590. }
  5591. this._resetVertexBufferBinding();
  5592. };
  5593. Engine.prototype._resetIndexBufferBinding = function () {
  5594. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5595. this._cachedIndexBuffer = null;
  5596. };
  5597. Engine.prototype.createIndexBuffer = function (indices) {
  5598. var vbo = this._gl.createBuffer();
  5599. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5600. // Check for 32 bits indices
  5601. var arrayBuffer;
  5602. var need32Bits = false;
  5603. if (this._caps.uintIndices) {
  5604. for (var index = 0; index < indices.length; index++) {
  5605. if (indices[index] > 65535) {
  5606. need32Bits = true;
  5607. break;
  5608. }
  5609. }
  5610. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5611. }
  5612. else {
  5613. arrayBuffer = new Uint16Array(indices);
  5614. }
  5615. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5616. this._resetIndexBufferBinding();
  5617. vbo.references = 1;
  5618. vbo.is32Bits = need32Bits;
  5619. return vbo;
  5620. };
  5621. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5622. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5623. this._cachedVertexBuffers = vertexBuffer;
  5624. this._cachedEffectForVertexBuffers = effect;
  5625. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5626. var offset = 0;
  5627. for (var index = 0; index < vertexDeclaration.length; index++) {
  5628. var order = effect.getAttributeLocation(index);
  5629. if (order >= 0) {
  5630. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5631. }
  5632. offset += vertexDeclaration[index] * 4;
  5633. }
  5634. }
  5635. if (this._cachedIndexBuffer !== indexBuffer) {
  5636. this._cachedIndexBuffer = indexBuffer;
  5637. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5638. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5639. }
  5640. };
  5641. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5642. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5643. this._cachedVertexBuffers = vertexBuffers;
  5644. this._cachedEffectForVertexBuffers = effect;
  5645. var attributes = effect.getAttributesNames();
  5646. for (var index = 0; index < attributes.length; index++) {
  5647. var order = effect.getAttributeLocation(index);
  5648. if (order >= 0) {
  5649. var vertexBuffer = vertexBuffers[attributes[index]];
  5650. if (!vertexBuffer) {
  5651. continue;
  5652. }
  5653. var stride = vertexBuffer.getStrideSize();
  5654. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5655. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5656. }
  5657. }
  5658. }
  5659. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5660. this._cachedIndexBuffer = indexBuffer;
  5661. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5662. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5663. }
  5664. };
  5665. Engine.prototype._releaseBuffer = function (buffer) {
  5666. buffer.references--;
  5667. if (buffer.references === 0) {
  5668. this._gl.deleteBuffer(buffer);
  5669. return true;
  5670. }
  5671. return false;
  5672. };
  5673. Engine.prototype.createInstancesBuffer = function (capacity) {
  5674. var buffer = this._gl.createBuffer();
  5675. buffer.capacity = capacity;
  5676. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5677. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5678. return buffer;
  5679. };
  5680. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5681. this._gl.deleteBuffer(buffer);
  5682. };
  5683. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5684. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5685. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5686. for (var index = 0; index < 4; index++) {
  5687. var offsetLocation = offsetLocations[index];
  5688. this._gl.enableVertexAttribArray(offsetLocation);
  5689. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5690. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5691. }
  5692. };
  5693. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5694. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5695. for (var index = 0; index < 4; index++) {
  5696. var offsetLocation = offsetLocations[index];
  5697. this._gl.disableVertexAttribArray(offsetLocation);
  5698. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5699. }
  5700. };
  5701. Engine.prototype.applyStates = function () {
  5702. this._depthCullingState.apply(this._gl);
  5703. this._alphaState.apply(this._gl);
  5704. };
  5705. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5706. // Apply states
  5707. this.applyStates();
  5708. this._drawCalls++;
  5709. // Render
  5710. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5711. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5712. if (instancesCount) {
  5713. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5714. return;
  5715. }
  5716. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5717. };
  5718. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5719. // Apply states
  5720. this.applyStates();
  5721. this._drawCalls++;
  5722. if (instancesCount) {
  5723. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5724. return;
  5725. }
  5726. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5727. };
  5728. // Shaders
  5729. Engine.prototype._releaseEffect = function (effect) {
  5730. if (this._compiledEffects[effect._key]) {
  5731. delete this._compiledEffects[effect._key];
  5732. if (effect.getProgram()) {
  5733. this._gl.deleteProgram(effect.getProgram());
  5734. }
  5735. }
  5736. };
  5737. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5738. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5739. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5740. var name = vertex + "+" + fragment + "@" + defines;
  5741. if (this._compiledEffects[name]) {
  5742. return this._compiledEffects[name];
  5743. }
  5744. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5745. effect._key = name;
  5746. this._compiledEffects[name] = effect;
  5747. return effect;
  5748. };
  5749. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5750. if (uniformsNames === void 0) { uniformsNames = []; }
  5751. if (samplers === void 0) { samplers = []; }
  5752. if (defines === void 0) { defines = ""; }
  5753. return this.createEffect({
  5754. vertex: "particles",
  5755. fragmentElement: fragmentName
  5756. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5757. };
  5758. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5759. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5760. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5761. var shaderProgram = this._gl.createProgram();
  5762. this._gl.attachShader(shaderProgram, vertexShader);
  5763. this._gl.attachShader(shaderProgram, fragmentShader);
  5764. this._gl.linkProgram(shaderProgram);
  5765. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5766. if (!linked) {
  5767. var error = this._gl.getProgramInfoLog(shaderProgram);
  5768. if (error) {
  5769. throw new Error(error);
  5770. }
  5771. }
  5772. this._gl.deleteShader(vertexShader);
  5773. this._gl.deleteShader(fragmentShader);
  5774. return shaderProgram;
  5775. };
  5776. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5777. var results = [];
  5778. for (var index = 0; index < uniformsNames.length; index++) {
  5779. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5780. }
  5781. return results;
  5782. };
  5783. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5784. var results = [];
  5785. for (var index = 0; index < attributesNames.length; index++) {
  5786. try {
  5787. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5788. }
  5789. catch (e) {
  5790. results.push(-1);
  5791. }
  5792. }
  5793. return results;
  5794. };
  5795. Engine.prototype.enableEffect = function (effect) {
  5796. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5797. if (effect && effect.onBind) {
  5798. effect.onBind(effect);
  5799. }
  5800. return;
  5801. }
  5802. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5803. // Use program
  5804. this._gl.useProgram(effect.getProgram());
  5805. for (var i in this._vertexAttribArrays) {
  5806. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5807. continue;
  5808. }
  5809. this._vertexAttribArrays[i] = false;
  5810. this._gl.disableVertexAttribArray(i);
  5811. }
  5812. var attributesCount = effect.getAttributesCount();
  5813. for (var index = 0; index < attributesCount; index++) {
  5814. // Attributes
  5815. var order = effect.getAttributeLocation(index);
  5816. if (order >= 0) {
  5817. this._vertexAttribArrays[order] = true;
  5818. this._gl.enableVertexAttribArray(order);
  5819. }
  5820. }
  5821. this._currentEffect = effect;
  5822. if (effect.onBind) {
  5823. effect.onBind(effect);
  5824. }
  5825. };
  5826. Engine.prototype.setArray = function (uniform, array) {
  5827. if (!uniform)
  5828. return;
  5829. this._gl.uniform1fv(uniform, array);
  5830. };
  5831. Engine.prototype.setArray2 = function (uniform, array) {
  5832. if (!uniform || array.length % 2 !== 0)
  5833. return;
  5834. this._gl.uniform2fv(uniform, array);
  5835. };
  5836. Engine.prototype.setArray3 = function (uniform, array) {
  5837. if (!uniform || array.length % 3 !== 0)
  5838. return;
  5839. this._gl.uniform3fv(uniform, array);
  5840. };
  5841. Engine.prototype.setArray4 = function (uniform, array) {
  5842. if (!uniform || array.length % 4 !== 0)
  5843. return;
  5844. this._gl.uniform4fv(uniform, array);
  5845. };
  5846. Engine.prototype.setMatrices = function (uniform, matrices) {
  5847. if (!uniform)
  5848. return;
  5849. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5850. };
  5851. Engine.prototype.setMatrix = function (uniform, matrix) {
  5852. if (!uniform)
  5853. return;
  5854. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5855. };
  5856. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5857. if (!uniform)
  5858. return;
  5859. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5860. };
  5861. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5862. if (!uniform)
  5863. return;
  5864. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5865. };
  5866. Engine.prototype.setFloat = function (uniform, value) {
  5867. if (!uniform)
  5868. return;
  5869. this._gl.uniform1f(uniform, value);
  5870. };
  5871. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5872. if (!uniform)
  5873. return;
  5874. this._gl.uniform2f(uniform, x, y);
  5875. };
  5876. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5877. if (!uniform)
  5878. return;
  5879. this._gl.uniform3f(uniform, x, y, z);
  5880. };
  5881. Engine.prototype.setBool = function (uniform, bool) {
  5882. if (!uniform)
  5883. return;
  5884. this._gl.uniform1i(uniform, bool);
  5885. };
  5886. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5887. if (!uniform)
  5888. return;
  5889. this._gl.uniform4f(uniform, x, y, z, w);
  5890. };
  5891. Engine.prototype.setColor3 = function (uniform, color3) {
  5892. if (!uniform)
  5893. return;
  5894. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5895. };
  5896. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5897. if (!uniform)
  5898. return;
  5899. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5900. };
  5901. // States
  5902. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5903. if (zOffset === void 0) { zOffset = 0; }
  5904. if (reverseSide === void 0) { reverseSide = false; }
  5905. // Culling
  5906. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5907. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5908. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5909. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5910. if (culling) {
  5911. this._depthCullingState.cullFace = cullFace;
  5912. this._depthCullingState.cull = true;
  5913. }
  5914. else {
  5915. this._depthCullingState.cull = false;
  5916. }
  5917. }
  5918. // Z offset
  5919. this._depthCullingState.zOffset = zOffset;
  5920. };
  5921. Engine.prototype.setDepthBuffer = function (enable) {
  5922. this._depthCullingState.depthTest = enable;
  5923. };
  5924. Engine.prototype.getDepthWrite = function () {
  5925. return this._depthCullingState.depthMask;
  5926. };
  5927. Engine.prototype.setDepthWrite = function (enable) {
  5928. this._depthCullingState.depthMask = enable;
  5929. };
  5930. Engine.prototype.setColorWrite = function (enable) {
  5931. this._gl.colorMask(enable, enable, enable, enable);
  5932. };
  5933. Engine.prototype.setAlphaMode = function (mode) {
  5934. if (this._alphaMode === mode) {
  5935. return;
  5936. }
  5937. switch (mode) {
  5938. case Engine.ALPHA_DISABLE:
  5939. this.setDepthWrite(true);
  5940. this._alphaState.alphaBlend = false;
  5941. break;
  5942. case Engine.ALPHA_COMBINE:
  5943. this.setDepthWrite(false);
  5944. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  5945. this._alphaState.alphaBlend = true;
  5946. break;
  5947. case Engine.ALPHA_ONEONE:
  5948. this.setDepthWrite(false);
  5949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5950. this._alphaState.alphaBlend = true;
  5951. break;
  5952. case Engine.ALPHA_ADD:
  5953. this.setDepthWrite(false);
  5954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5955. this._alphaState.alphaBlend = true;
  5956. break;
  5957. case Engine.ALPHA_SUBTRACT:
  5958. this.setDepthWrite(false);
  5959. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  5960. this._alphaState.alphaBlend = true;
  5961. break;
  5962. case Engine.ALPHA_MULTIPLY:
  5963. this.setDepthWrite(false);
  5964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  5965. this._alphaState.alphaBlend = true;
  5966. break;
  5967. case Engine.ALPHA_MAXIMIZED:
  5968. this.setDepthWrite(false);
  5969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  5970. this._alphaState.alphaBlend = true;
  5971. break;
  5972. }
  5973. this._alphaMode = mode;
  5974. };
  5975. Engine.prototype.getAlphaMode = function () {
  5976. return this._alphaMode;
  5977. };
  5978. Engine.prototype.setAlphaTesting = function (enable) {
  5979. this._alphaTest = enable;
  5980. };
  5981. Engine.prototype.getAlphaTesting = function () {
  5982. return this._alphaTest;
  5983. };
  5984. // Textures
  5985. Engine.prototype.wipeCaches = function () {
  5986. this.resetTextureCache();
  5987. this._currentEffect = null;
  5988. this._depthCullingState.reset();
  5989. this._alphaState.reset();
  5990. this._cachedVertexBuffers = null;
  5991. this._cachedIndexBuffer = null;
  5992. this._cachedEffectForVertexBuffers = null;
  5993. };
  5994. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  5995. var gl = this._gl;
  5996. gl.bindTexture(gl.TEXTURE_2D, texture);
  5997. var magFilter = gl.NEAREST;
  5998. var minFilter = gl.NEAREST;
  5999. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6000. magFilter = gl.LINEAR;
  6001. minFilter = gl.LINEAR;
  6002. }
  6003. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6004. magFilter = gl.LINEAR;
  6005. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6006. }
  6007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6009. gl.bindTexture(gl.TEXTURE_2D, null);
  6010. texture.samplingMode = samplingMode;
  6011. };
  6012. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6013. var _this = this;
  6014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6015. if (onLoad === void 0) { onLoad = null; }
  6016. if (onError === void 0) { onError = null; }
  6017. if (buffer === void 0) { buffer = null; }
  6018. var texture = this._gl.createTexture();
  6019. var extension;
  6020. var fromData = false;
  6021. if (url.substr(0, 5) === "data:") {
  6022. fromData = true;
  6023. }
  6024. if (!fromData)
  6025. extension = url.substr(url.length - 4, 4).toLowerCase();
  6026. else {
  6027. var oldUrl = url;
  6028. fromData = oldUrl.split(':');
  6029. url = oldUrl;
  6030. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6031. }
  6032. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6033. var isTGA = (extension === ".tga");
  6034. scene._addPendingData(texture);
  6035. texture.url = url;
  6036. texture.noMipmap = noMipmap;
  6037. texture.references = 1;
  6038. texture.samplingMode = samplingMode;
  6039. this._loadedTexturesCache.push(texture);
  6040. var onerror = function () {
  6041. scene._removePendingData(texture);
  6042. if (onError) {
  6043. onError();
  6044. }
  6045. };
  6046. var callback;
  6047. if (isTGA) {
  6048. callback = function (arrayBuffer) {
  6049. var data = new Uint8Array(arrayBuffer);
  6050. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6051. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6052. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6053. if (onLoad) {
  6054. onLoad();
  6055. }
  6056. }, samplingMode);
  6057. };
  6058. if (!(fromData instanceof Array))
  6059. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6060. callback(arrayBuffer);
  6061. }, onerror, scene.database, true);
  6062. else
  6063. callback(buffer);
  6064. }
  6065. else if (isDDS) {
  6066. callback = function (data) {
  6067. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6068. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6069. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6070. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6071. if (onLoad) {
  6072. onLoad();
  6073. }
  6074. }, samplingMode);
  6075. };
  6076. if (!(fromData instanceof Array))
  6077. BABYLON.Tools.LoadFile(url, function (data) {
  6078. callback(data);
  6079. }, onerror, scene.database, true);
  6080. else
  6081. callback(buffer);
  6082. }
  6083. else {
  6084. var onload = function (img) {
  6085. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6086. var isPot = (img.width === potWidth && img.height === potHeight);
  6087. if (!isPot) {
  6088. _this._prepareWorkingCanvas();
  6089. _this._workingCanvas.width = potWidth;
  6090. _this._workingCanvas.height = potHeight;
  6091. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6092. _this._workingContext.imageSmoothingEnabled = false;
  6093. _this._workingContext.mozImageSmoothingEnabled = false;
  6094. _this._workingContext.oImageSmoothingEnabled = false;
  6095. _this._workingContext.webkitImageSmoothingEnabled = false;
  6096. _this._workingContext.msImageSmoothingEnabled = false;
  6097. }
  6098. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6099. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6100. _this._workingContext.imageSmoothingEnabled = true;
  6101. _this._workingContext.mozImageSmoothingEnabled = true;
  6102. _this._workingContext.oImageSmoothingEnabled = true;
  6103. _this._workingContext.webkitImageSmoothingEnabled = true;
  6104. _this._workingContext.msImageSmoothingEnabled = true;
  6105. }
  6106. }
  6107. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6108. if (onLoad) {
  6109. onLoad();
  6110. }
  6111. }, samplingMode);
  6112. };
  6113. if (!(fromData instanceof Array))
  6114. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6115. else
  6116. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6117. }
  6118. return texture;
  6119. };
  6120. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6121. if (compression === void 0) { compression = null; }
  6122. var internalFormat = this._gl.RGBA;
  6123. switch (format) {
  6124. case Engine.TEXTUREFORMAT_ALPHA:
  6125. internalFormat = this._gl.ALPHA;
  6126. break;
  6127. case Engine.TEXTUREFORMAT_LUMINANCE:
  6128. internalFormat = this._gl.LUMINANCE;
  6129. break;
  6130. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6131. internalFormat = this._gl.LUMINANCE_ALPHA;
  6132. break;
  6133. case Engine.TEXTUREFORMAT_RGB:
  6134. internalFormat = this._gl.RGB;
  6135. break;
  6136. case Engine.TEXTUREFORMAT_RGBA:
  6137. internalFormat = this._gl.RGBA;
  6138. break;
  6139. }
  6140. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6141. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6142. if (compression) {
  6143. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6144. }
  6145. else {
  6146. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6147. }
  6148. if (texture.generateMipMaps) {
  6149. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6150. }
  6151. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6152. this.resetTextureCache();
  6153. texture.isReady = true;
  6154. };
  6155. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6156. if (compression === void 0) { compression = null; }
  6157. var texture = this._gl.createTexture();
  6158. texture._baseWidth = width;
  6159. texture._baseHeight = height;
  6160. texture._width = width;
  6161. texture._height = height;
  6162. texture.references = 1;
  6163. this.updateRawTexture(texture, data, format, invertY, compression);
  6164. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6165. // Filters
  6166. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6167. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6168. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6169. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6170. texture.samplingMode = samplingMode;
  6171. this._loadedTexturesCache.push(texture);
  6172. return texture;
  6173. };
  6174. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6175. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6176. var texture = this._gl.createTexture();
  6177. texture._baseWidth = width;
  6178. texture._baseHeight = height;
  6179. if (forceExponantOfTwo) {
  6180. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6181. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6182. }
  6183. this.resetTextureCache();
  6184. texture._width = width;
  6185. texture._height = height;
  6186. texture.isReady = false;
  6187. texture.generateMipMaps = generateMipMaps;
  6188. texture.references = 1;
  6189. texture.samplingMode = samplingMode;
  6190. this.updateTextureSamplingMode(samplingMode, texture);
  6191. this._loadedTexturesCache.push(texture);
  6192. return texture;
  6193. };
  6194. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6195. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6196. if (texture.isCube) {
  6197. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6198. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6199. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6200. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6201. }
  6202. else {
  6203. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6205. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6206. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6207. }
  6208. };
  6209. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6210. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6211. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6212. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6213. if (texture.generateMipMaps) {
  6214. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6215. }
  6216. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6217. this.resetTextureCache();
  6218. texture.isReady = true;
  6219. };
  6220. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6221. if (texture._isDisabled) {
  6222. return;
  6223. }
  6224. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6225. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6226. try {
  6227. // Testing video texture support
  6228. if (this._videoTextureSupported === undefined) {
  6229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6230. if (this._gl.getError() !== 0) {
  6231. this._videoTextureSupported = false;
  6232. }
  6233. else {
  6234. this._videoTextureSupported = true;
  6235. }
  6236. }
  6237. // Copy video through the current working canvas if video texture is not supported
  6238. if (!this._videoTextureSupported) {
  6239. if (!texture._workingCanvas) {
  6240. texture._workingCanvas = document.createElement("canvas");
  6241. texture._workingContext = texture._workingCanvas.getContext("2d");
  6242. texture._workingCanvas.width = texture._width;
  6243. texture._workingCanvas.height = texture._height;
  6244. }
  6245. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6246. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6247. }
  6248. else {
  6249. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6250. }
  6251. if (texture.generateMipMaps) {
  6252. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6253. }
  6254. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6255. this.resetTextureCache();
  6256. texture.isReady = true;
  6257. }
  6258. catch (ex) {
  6259. // Something unexpected
  6260. // Let's disable the texture
  6261. texture._isDisabled = true;
  6262. }
  6263. };
  6264. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6265. // old version had a "generateMipMaps" arg instead of options.
  6266. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6267. // in the same way, generateDepthBuffer is defaulted to true
  6268. var generateMipMaps = false;
  6269. var generateDepthBuffer = true;
  6270. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6271. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6272. if (options !== undefined) {
  6273. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6274. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6275. type = options.type === undefined ? type : options.type;
  6276. if (options.samplingMode !== undefined) {
  6277. samplingMode = options.samplingMode;
  6278. }
  6279. if (type === Engine.TEXTURETYPE_FLOAT) {
  6280. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6281. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6282. }
  6283. }
  6284. var gl = this._gl;
  6285. var texture = gl.createTexture();
  6286. gl.bindTexture(gl.TEXTURE_2D, texture);
  6287. var width = size.width || size;
  6288. var height = size.height || size;
  6289. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6290. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6291. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6292. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6293. }
  6294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6298. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6299. var depthBuffer;
  6300. // Create the depth buffer
  6301. if (generateDepthBuffer) {
  6302. depthBuffer = gl.createRenderbuffer();
  6303. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6304. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6305. }
  6306. // Create the framebuffer
  6307. var framebuffer = gl.createFramebuffer();
  6308. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6309. if (generateDepthBuffer) {
  6310. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6311. }
  6312. if (generateMipMaps) {
  6313. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6314. }
  6315. // Unbind
  6316. gl.bindTexture(gl.TEXTURE_2D, null);
  6317. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6318. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6319. texture._framebuffer = framebuffer;
  6320. if (generateDepthBuffer) {
  6321. texture._depthBuffer = depthBuffer;
  6322. }
  6323. texture._width = width;
  6324. texture._height = height;
  6325. texture.isReady = true;
  6326. texture.generateMipMaps = generateMipMaps;
  6327. texture.references = 1;
  6328. texture.samplingMode = samplingMode;
  6329. this.resetTextureCache();
  6330. this._loadedTexturesCache.push(texture);
  6331. return texture;
  6332. };
  6333. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6334. var gl = this._gl;
  6335. var texture = gl.createTexture();
  6336. var generateMipMaps = true;
  6337. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6338. if (options !== undefined) {
  6339. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6340. if (options.samplingMode !== undefined) {
  6341. samplingMode = options.samplingMode;
  6342. }
  6343. }
  6344. texture.isCube = true;
  6345. texture.references = 1;
  6346. texture.generateMipMaps = generateMipMaps;
  6347. texture.references = 1;
  6348. texture.samplingMode = samplingMode;
  6349. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6350. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6351. for (var face = 0; face < 6; face++) {
  6352. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6353. }
  6354. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6358. // Create the depth buffer
  6359. var depthBuffer = gl.createRenderbuffer();
  6360. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6361. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6362. // Create the framebuffer
  6363. var framebuffer = gl.createFramebuffer();
  6364. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6365. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6366. // Unbind
  6367. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6368. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6369. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6370. texture._framebuffer = framebuffer;
  6371. texture._depthBuffer = depthBuffer;
  6372. this.resetTextureCache();
  6373. texture._width = size;
  6374. texture._height = size;
  6375. texture.isReady = true;
  6376. return texture;
  6377. };
  6378. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6379. var _this = this;
  6380. var gl = this._gl;
  6381. var texture = gl.createTexture();
  6382. texture.isCube = true;
  6383. texture.url = rootUrl;
  6384. texture.references = 1;
  6385. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6386. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6387. if (isDDS) {
  6388. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6389. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6390. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6391. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6392. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6393. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6394. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6395. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6396. }
  6397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  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. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6402. _this.resetTextureCache();
  6403. texture._width = info.width;
  6404. texture._height = info.height;
  6405. texture.isReady = true;
  6406. }, null, null, true);
  6407. }
  6408. else {
  6409. cascadeLoad(rootUrl, scene, function (imgs) {
  6410. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6411. var height = width;
  6412. _this._prepareWorkingCanvas();
  6413. _this._workingCanvas.width = width;
  6414. _this._workingCanvas.height = height;
  6415. var faces = [
  6416. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6417. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6418. ];
  6419. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6420. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6421. for (var index = 0; index < faces.length; index++) {
  6422. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6423. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6424. }
  6425. if (!noMipmap) {
  6426. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6427. }
  6428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6429. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6430. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6432. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6433. _this.resetTextureCache();
  6434. texture._width = width;
  6435. texture._height = height;
  6436. texture.isReady = true;
  6437. }, extensions);
  6438. }
  6439. return texture;
  6440. };
  6441. Engine.prototype._releaseTexture = function (texture) {
  6442. var gl = this._gl;
  6443. if (texture._framebuffer) {
  6444. gl.deleteFramebuffer(texture._framebuffer);
  6445. }
  6446. if (texture._depthBuffer) {
  6447. gl.deleteRenderbuffer(texture._depthBuffer);
  6448. }
  6449. gl.deleteTexture(texture);
  6450. // Unbind channels
  6451. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6452. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6453. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6454. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6455. this._activeTexturesCache[channel] = null;
  6456. }
  6457. var index = this._loadedTexturesCache.indexOf(texture);
  6458. if (index !== -1) {
  6459. this._loadedTexturesCache.splice(index, 1);
  6460. }
  6461. };
  6462. Engine.prototype.bindSamplers = function (effect) {
  6463. this._gl.useProgram(effect.getProgram());
  6464. var samplers = effect.getSamplers();
  6465. for (var index = 0; index < samplers.length; index++) {
  6466. var uniform = effect.getUniform(samplers[index]);
  6467. this._gl.uniform1i(uniform, index);
  6468. }
  6469. this._currentEffect = null;
  6470. };
  6471. Engine.prototype._bindTexture = function (channel, texture) {
  6472. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6473. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6474. this._activeTexturesCache[channel] = null;
  6475. };
  6476. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6477. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6478. };
  6479. Engine.prototype.setTexture = function (channel, texture) {
  6480. if (channel < 0) {
  6481. return;
  6482. }
  6483. // Not ready?
  6484. if (!texture || !texture.isReady()) {
  6485. if (this._activeTexturesCache[channel] != null) {
  6486. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6487. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6488. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6489. this._activeTexturesCache[channel] = null;
  6490. }
  6491. return;
  6492. }
  6493. // Video
  6494. if (texture instanceof BABYLON.VideoTexture) {
  6495. if (texture.update()) {
  6496. this._activeTexturesCache[channel] = null;
  6497. }
  6498. }
  6499. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6500. texture.delayLoad();
  6501. return;
  6502. }
  6503. if (this._activeTexturesCache[channel] === texture) {
  6504. return;
  6505. }
  6506. this._activeTexturesCache[channel] = texture;
  6507. var internalTexture = texture.getInternalTexture();
  6508. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6509. if (internalTexture.isCube) {
  6510. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6511. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6512. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6513. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6514. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6515. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6516. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6517. }
  6518. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6519. }
  6520. else {
  6521. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6522. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6523. internalTexture._cachedWrapU = texture.wrapU;
  6524. switch (texture.wrapU) {
  6525. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6526. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6527. break;
  6528. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6530. break;
  6531. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6533. break;
  6534. }
  6535. }
  6536. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6537. internalTexture._cachedWrapV = texture.wrapV;
  6538. switch (texture.wrapV) {
  6539. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6540. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6541. break;
  6542. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6544. break;
  6545. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6547. break;
  6548. }
  6549. }
  6550. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6551. }
  6552. };
  6553. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6554. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6555. var value = texture.anisotropicFilteringLevel;
  6556. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6557. value = 1;
  6558. }
  6559. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6560. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6561. texture._cachedAnisotropicFilteringLevel = value;
  6562. }
  6563. };
  6564. Engine.prototype.readPixels = function (x, y, width, height) {
  6565. var data = new Uint8Array(height * width * 4);
  6566. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6567. return data;
  6568. };
  6569. Engine.prototype.releaseInternalTexture = function (texture) {
  6570. if (!texture) {
  6571. return;
  6572. }
  6573. texture.references--;
  6574. // Final reference ?
  6575. if (texture.references === 0) {
  6576. var texturesCache = this.getLoadedTexturesCache();
  6577. var index = texturesCache.indexOf(texture);
  6578. if (index > -1) {
  6579. texturesCache.splice(index, 1);
  6580. }
  6581. this._releaseTexture(texture);
  6582. }
  6583. };
  6584. // Dispose
  6585. Engine.prototype.dispose = function () {
  6586. this.hideLoadingUI();
  6587. this.stopRenderLoop();
  6588. // Release scenes
  6589. while (this.scenes.length) {
  6590. this.scenes[0].dispose();
  6591. }
  6592. // Release audio engine
  6593. Engine.audioEngine.dispose();
  6594. // Release effects
  6595. for (var name in this._compiledEffects) {
  6596. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6597. }
  6598. // Unbind
  6599. for (var i in this._vertexAttribArrays) {
  6600. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6601. continue;
  6602. }
  6603. this._gl.disableVertexAttribArray(i);
  6604. }
  6605. this._gl = null;
  6606. // Events
  6607. window.removeEventListener("blur", this._onBlur);
  6608. window.removeEventListener("focus", this._onFocus);
  6609. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6610. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6611. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6612. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6613. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6614. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6615. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6616. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6617. };
  6618. // Loading screen
  6619. Engine.prototype.displayLoadingUI = function () {
  6620. this._loadingScreen.displayLoadingUI();
  6621. };
  6622. Engine.prototype.hideLoadingUI = function () {
  6623. this._loadingScreen.hideLoadingUI();
  6624. };
  6625. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6626. get: function () {
  6627. return this._loadingScreen;
  6628. },
  6629. set: function (loadingScreen) {
  6630. this._loadingScreen = loadingScreen;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6636. set: function (text) {
  6637. this._loadingScreen.loadingUIText = text;
  6638. },
  6639. enumerable: true,
  6640. configurable: true
  6641. });
  6642. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6643. set: function (color) {
  6644. this._loadingScreen.loadingUIBackgroundColor = color;
  6645. },
  6646. enumerable: true,
  6647. configurable: true
  6648. });
  6649. // FPS
  6650. Engine.prototype.getFps = function () {
  6651. return this.fps;
  6652. };
  6653. Engine.prototype.getDeltaTime = function () {
  6654. return this.deltaTime;
  6655. };
  6656. Engine.prototype._measureFps = function () {
  6657. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6658. var length = this.previousFramesDuration.length;
  6659. if (length >= 2) {
  6660. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6661. }
  6662. if (length >= this.fpsRange) {
  6663. if (length > this.fpsRange) {
  6664. this.previousFramesDuration.splice(0, 1);
  6665. length = this.previousFramesDuration.length;
  6666. }
  6667. var sum = 0;
  6668. for (var id = 0; id < length - 1; id++) {
  6669. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6670. }
  6671. this.fps = 1000.0 / (sum / (length - 1));
  6672. }
  6673. };
  6674. // Statics
  6675. Engine.isSupported = function () {
  6676. try {
  6677. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6678. if (navigator.isCocoonJS) {
  6679. return true;
  6680. }
  6681. var tempcanvas = document.createElement("canvas");
  6682. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6683. return gl != null && !!window.WebGLRenderingContext;
  6684. }
  6685. catch (e) {
  6686. return false;
  6687. }
  6688. };
  6689. // Const statics
  6690. Engine._ALPHA_DISABLE = 0;
  6691. Engine._ALPHA_ADD = 1;
  6692. Engine._ALPHA_COMBINE = 2;
  6693. Engine._ALPHA_SUBTRACT = 3;
  6694. Engine._ALPHA_MULTIPLY = 4;
  6695. Engine._ALPHA_MAXIMIZED = 5;
  6696. Engine._ALPHA_ONEONE = 6;
  6697. Engine._DELAYLOADSTATE_NONE = 0;
  6698. Engine._DELAYLOADSTATE_LOADED = 1;
  6699. Engine._DELAYLOADSTATE_LOADING = 2;
  6700. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6701. Engine._TEXTUREFORMAT_ALPHA = 0;
  6702. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6703. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6704. Engine._TEXTUREFORMAT_RGB = 4;
  6705. Engine._TEXTUREFORMAT_RGBA = 5;
  6706. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6707. Engine._TEXTURETYPE_FLOAT = 1;
  6708. // Updatable statics so stick with vars here
  6709. Engine.Epsilon = 0.001;
  6710. Engine.CollisionsEpsilon = 0.001;
  6711. Engine.CodeRepository = "src/";
  6712. Engine.ShadersRepository = "src/Shaders/";
  6713. return Engine;
  6714. })();
  6715. BABYLON.Engine = Engine;
  6716. })(BABYLON || (BABYLON = {}));
  6717. var BABYLON;
  6718. (function (BABYLON) {
  6719. /**
  6720. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6721. */
  6722. var Node = (function () {
  6723. /**
  6724. * @constructor
  6725. * @param {string} name - the name and id to be given to this node
  6726. * @param {BABYLON.Scene} the scene this node will be added to
  6727. */
  6728. function Node(name, scene) {
  6729. this.state = "";
  6730. this.animations = new Array();
  6731. this._childrenFlag = -1;
  6732. this._isEnabled = true;
  6733. this._isReady = true;
  6734. this._currentRenderId = -1;
  6735. this._parentRenderId = -1;
  6736. this.name = name;
  6737. this.id = name;
  6738. this._scene = scene;
  6739. this._initCache();
  6740. }
  6741. Node.prototype.getScene = function () {
  6742. return this._scene;
  6743. };
  6744. Node.prototype.getEngine = function () {
  6745. return this._scene.getEngine();
  6746. };
  6747. // override it in derived class
  6748. Node.prototype.getWorldMatrix = function () {
  6749. return BABYLON.Matrix.Identity();
  6750. };
  6751. // override it in derived class if you add new variables to the cache
  6752. // and call the parent class method
  6753. Node.prototype._initCache = function () {
  6754. this._cache = {};
  6755. this._cache.parent = undefined;
  6756. };
  6757. Node.prototype.updateCache = function (force) {
  6758. if (!force && this.isSynchronized())
  6759. return;
  6760. this._cache.parent = this.parent;
  6761. this._updateCache();
  6762. };
  6763. // override it in derived class if you add new variables to the cache
  6764. // and call the parent class method if !ignoreParentClass
  6765. Node.prototype._updateCache = function (ignoreParentClass) {
  6766. };
  6767. // override it in derived class if you add new variables to the cache
  6768. Node.prototype._isSynchronized = function () {
  6769. return true;
  6770. };
  6771. Node.prototype._markSyncedWithParent = function () {
  6772. this._parentRenderId = this.parent._currentRenderId;
  6773. };
  6774. Node.prototype.isSynchronizedWithParent = function () {
  6775. if (!this.parent) {
  6776. return true;
  6777. }
  6778. if (this._parentRenderId !== this.parent._currentRenderId) {
  6779. return false;
  6780. }
  6781. return this.parent.isSynchronized();
  6782. };
  6783. Node.prototype.isSynchronized = function (updateCache) {
  6784. var check = this.hasNewParent();
  6785. check = check || !this.isSynchronizedWithParent();
  6786. check = check || !this._isSynchronized();
  6787. if (updateCache)
  6788. this.updateCache(true);
  6789. return !check;
  6790. };
  6791. Node.prototype.hasNewParent = function (update) {
  6792. if (this._cache.parent === this.parent)
  6793. return false;
  6794. if (update)
  6795. this._cache.parent = this.parent;
  6796. return true;
  6797. };
  6798. /**
  6799. * Is this node ready to be used/rendered
  6800. * @return {boolean} is it ready
  6801. */
  6802. Node.prototype.isReady = function () {
  6803. return this._isReady;
  6804. };
  6805. /**
  6806. * Is this node enabled.
  6807. * If the node has a parent and is enabled, the parent will be inspected as well.
  6808. * @return {boolean} whether this node (and its parent) is enabled.
  6809. * @see setEnabled
  6810. */
  6811. Node.prototype.isEnabled = function () {
  6812. if (!this._isEnabled) {
  6813. return false;
  6814. }
  6815. if (this.parent) {
  6816. return this.parent.isEnabled();
  6817. }
  6818. return true;
  6819. };
  6820. /**
  6821. * Set the enabled state of this node.
  6822. * @param {boolean} value - the new enabled state
  6823. * @see isEnabled
  6824. */
  6825. Node.prototype.setEnabled = function (value) {
  6826. this._isEnabled = value;
  6827. };
  6828. /**
  6829. * Is this node a descendant of the given node.
  6830. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6831. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6832. * @see parent
  6833. */
  6834. Node.prototype.isDescendantOf = function (ancestor) {
  6835. if (this.parent) {
  6836. if (this.parent === ancestor) {
  6837. return true;
  6838. }
  6839. return this.parent.isDescendantOf(ancestor);
  6840. }
  6841. return false;
  6842. };
  6843. Node.prototype._getDescendants = function (list, results) {
  6844. for (var index = 0; index < list.length; index++) {
  6845. var item = list[index];
  6846. if (item.isDescendantOf(this)) {
  6847. results.push(item);
  6848. }
  6849. }
  6850. };
  6851. /**
  6852. * Will return all nodes that have this node as parent.
  6853. * @return {BABYLON.Node[]} all children nodes of all types.
  6854. */
  6855. Node.prototype.getDescendants = function () {
  6856. var results = [];
  6857. this._getDescendants(this._scene.meshes, results);
  6858. this._getDescendants(this._scene.lights, results);
  6859. this._getDescendants(this._scene.cameras, results);
  6860. return results;
  6861. };
  6862. Node.prototype._setReady = function (state) {
  6863. if (state === this._isReady) {
  6864. return;
  6865. }
  6866. if (!state) {
  6867. this._isReady = false;
  6868. return;
  6869. }
  6870. this._isReady = true;
  6871. if (this.onReady) {
  6872. this.onReady(this);
  6873. }
  6874. };
  6875. Node.prototype.getAnimationByName = function (name) {
  6876. for (var i = 0; i < this.animations.length; i++) {
  6877. var animation = this.animations[i];
  6878. if (animation.name === name) {
  6879. return animation;
  6880. }
  6881. }
  6882. return null;
  6883. };
  6884. return Node;
  6885. })();
  6886. BABYLON.Node = Node;
  6887. })(BABYLON || (BABYLON = {}));
  6888. var BABYLON;
  6889. (function (BABYLON) {
  6890. var FilesInput = (function () {
  6891. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6892. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6893. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6894. this._engine = p_engine;
  6895. this._canvas = p_canvas;
  6896. this._currentScene = p_scene;
  6897. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6898. this._progressCallback = p_progressCallback;
  6899. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6900. this._textureLoadingCallback = p_textureLoadingCallback;
  6901. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6902. }
  6903. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6904. var _this = this;
  6905. if (p_elementToMonitor) {
  6906. this._elementToMonitor = p_elementToMonitor;
  6907. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6908. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6909. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6910. }
  6911. };
  6912. FilesInput.prototype.renderFunction = function () {
  6913. if (this._additionnalRenderLoopLogicCallback) {
  6914. this._additionnalRenderLoopLogicCallback();
  6915. }
  6916. if (this._currentScene) {
  6917. if (this._textureLoadingCallback) {
  6918. var remaining = this._currentScene.getWaitingItemsCount();
  6919. if (remaining > 0) {
  6920. this._textureLoadingCallback(remaining);
  6921. }
  6922. }
  6923. this._currentScene.render();
  6924. }
  6925. };
  6926. FilesInput.prototype.drag = function (e) {
  6927. e.stopPropagation();
  6928. e.preventDefault();
  6929. };
  6930. FilesInput.prototype.drop = function (eventDrop) {
  6931. eventDrop.stopPropagation();
  6932. eventDrop.preventDefault();
  6933. this.loadFiles(eventDrop);
  6934. };
  6935. FilesInput.prototype.loadFiles = function (event) {
  6936. if (this._startingProcessingFilesCallback)
  6937. this._startingProcessingFilesCallback();
  6938. // Handling data transfer via drag'n'drop
  6939. if (event && event.dataTransfer && event.dataTransfer.files) {
  6940. this._filesToLoad = event.dataTransfer.files;
  6941. }
  6942. // Handling files from input files
  6943. if (event && event.target && event.target.files) {
  6944. this._filesToLoad = event.target.files;
  6945. }
  6946. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6947. for (var i = 0; i < this._filesToLoad.length; i++) {
  6948. switch (this._filesToLoad[i].type) {
  6949. case "image/jpeg":
  6950. case "image/png":
  6951. case "image/bmp":
  6952. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6953. break;
  6954. case "image/targa":
  6955. case "image/vnd.ms-dds":
  6956. case "audio/wav":
  6957. case "audio/x-wav":
  6958. case "audio/mp3":
  6959. case "audio/mpeg":
  6960. case "audio/mpeg3":
  6961. case "audio/x-mpeg-3":
  6962. case "audio/ogg":
  6963. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6964. break;
  6965. default:
  6966. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  6967. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  6968. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  6969. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  6970. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  6971. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  6972. this._sceneFileToLoad = this._filesToLoad[i];
  6973. }
  6974. break;
  6975. }
  6976. }
  6977. this.reload();
  6978. }
  6979. };
  6980. FilesInput.prototype.reload = function () {
  6981. var _this = this;
  6982. var that = this;
  6983. // If a ".babylon" file has been provided
  6984. if (this._sceneFileToLoad) {
  6985. if (this._currentScene) {
  6986. if (BABYLON.Tools.errorsCount > 0) {
  6987. BABYLON.Tools.ClearLogCache();
  6988. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  6989. }
  6990. this._engine.stopRenderLoop();
  6991. this._currentScene.dispose();
  6992. }
  6993. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  6994. that._currentScene = newScene;
  6995. // Wait for textures and shaders to be ready
  6996. that._currentScene.executeWhenReady(function () {
  6997. // Attach camera to canvas inputs
  6998. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  6999. that._currentScene.createDefaultCameraOrLight();
  7000. }
  7001. that._currentScene.activeCamera.attachControl(that._canvas);
  7002. if (that._sceneLoadedCallback) {
  7003. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7004. }
  7005. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7006. });
  7007. }, function (progress) {
  7008. if (_this._progressCallback) {
  7009. _this._progressCallback(progress);
  7010. }
  7011. });
  7012. }
  7013. else {
  7014. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7015. }
  7016. };
  7017. FilesInput.FilesTextures = new Array();
  7018. FilesInput.FilesToLoad = new Array();
  7019. return FilesInput;
  7020. })();
  7021. BABYLON.FilesInput = FilesInput;
  7022. })(BABYLON || (BABYLON = {}));
  7023. var BABYLON;
  7024. (function (BABYLON) {
  7025. var IntersectionInfo = (function () {
  7026. function IntersectionInfo(bu, bv, distance) {
  7027. this.bu = bu;
  7028. this.bv = bv;
  7029. this.distance = distance;
  7030. this.faceId = 0;
  7031. this.subMeshId = 0;
  7032. }
  7033. return IntersectionInfo;
  7034. })();
  7035. BABYLON.IntersectionInfo = IntersectionInfo;
  7036. var PickingInfo = (function () {
  7037. function PickingInfo() {
  7038. this.hit = false;
  7039. this.distance = 0;
  7040. this.pickedPoint = null;
  7041. this.pickedMesh = null;
  7042. this.bu = 0;
  7043. this.bv = 0;
  7044. this.faceId = -1;
  7045. this.subMeshId = 0;
  7046. this.pickedSprite = null;
  7047. }
  7048. // Methods
  7049. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7050. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7051. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7052. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7053. return null;
  7054. }
  7055. var indices = this.pickedMesh.getIndices();
  7056. var result;
  7057. if (useVerticesNormals) {
  7058. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7059. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7060. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7061. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7062. normal0 = normal0.scale(this.bu);
  7063. normal1 = normal1.scale(this.bv);
  7064. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7065. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7066. }
  7067. else {
  7068. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7069. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7070. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7071. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7072. var p1p2 = vertex1.subtract(vertex2);
  7073. var p3p2 = vertex3.subtract(vertex2);
  7074. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7075. }
  7076. if (useWorldCoordinates) {
  7077. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7078. }
  7079. return BABYLON.Vector3.Normalize(result);
  7080. };
  7081. PickingInfo.prototype.getTextureCoordinates = function () {
  7082. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7083. return null;
  7084. }
  7085. var indices = this.pickedMesh.getIndices();
  7086. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7087. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7088. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7089. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7090. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7091. uv1 = uv1.scale(this.bu);
  7092. uv2 = uv2.scale(this.bv);
  7093. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7094. };
  7095. return PickingInfo;
  7096. })();
  7097. BABYLON.PickingInfo = PickingInfo;
  7098. })(BABYLON || (BABYLON = {}));
  7099. var BABYLON;
  7100. (function (BABYLON) {
  7101. var BoundingSphere = (function () {
  7102. function BoundingSphere(minimum, maximum) {
  7103. this.minimum = minimum;
  7104. this.maximum = maximum;
  7105. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7106. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7107. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7108. this.radius = distance * 0.5;
  7109. this.centerWorld = BABYLON.Vector3.Zero();
  7110. this._update(BABYLON.Matrix.Identity());
  7111. }
  7112. // Methods
  7113. BoundingSphere.prototype._update = function (world) {
  7114. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7115. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7116. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7117. };
  7118. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7119. for (var i = 0; i < 6; i++) {
  7120. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7121. return false;
  7122. }
  7123. return true;
  7124. };
  7125. BoundingSphere.prototype.intersectsPoint = function (point) {
  7126. var x = this.centerWorld.x - point.x;
  7127. var y = this.centerWorld.y - point.y;
  7128. var z = this.centerWorld.z - point.z;
  7129. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7130. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7131. return false;
  7132. return true;
  7133. };
  7134. // Statics
  7135. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7136. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7137. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7138. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7139. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7140. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7141. return false;
  7142. return true;
  7143. };
  7144. return BoundingSphere;
  7145. })();
  7146. BABYLON.BoundingSphere = BoundingSphere;
  7147. })(BABYLON || (BABYLON = {}));
  7148. var BABYLON;
  7149. (function (BABYLON) {
  7150. var BoundingBox = (function () {
  7151. function BoundingBox(minimum, maximum) {
  7152. this.minimum = minimum;
  7153. this.maximum = maximum;
  7154. this.vectors = new Array();
  7155. this.vectorsWorld = new Array();
  7156. // Bounding vectors
  7157. this.vectors.push(this.minimum.clone());
  7158. this.vectors.push(this.maximum.clone());
  7159. this.vectors.push(this.minimum.clone());
  7160. this.vectors[2].x = this.maximum.x;
  7161. this.vectors.push(this.minimum.clone());
  7162. this.vectors[3].y = this.maximum.y;
  7163. this.vectors.push(this.minimum.clone());
  7164. this.vectors[4].z = this.maximum.z;
  7165. this.vectors.push(this.maximum.clone());
  7166. this.vectors[5].z = this.minimum.z;
  7167. this.vectors.push(this.maximum.clone());
  7168. this.vectors[6].x = this.minimum.x;
  7169. this.vectors.push(this.maximum.clone());
  7170. this.vectors[7].y = this.minimum.y;
  7171. // OBB
  7172. this.center = this.maximum.add(this.minimum).scale(0.5);
  7173. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7174. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7175. // World
  7176. for (var index = 0; index < this.vectors.length; index++) {
  7177. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7178. }
  7179. this.minimumWorld = BABYLON.Vector3.Zero();
  7180. this.maximumWorld = BABYLON.Vector3.Zero();
  7181. this._update(BABYLON.Matrix.Identity());
  7182. }
  7183. // Methods
  7184. BoundingBox.prototype.getWorldMatrix = function () {
  7185. return this._worldMatrix;
  7186. };
  7187. BoundingBox.prototype._update = function (world) {
  7188. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7189. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7190. for (var index = 0; index < this.vectors.length; index++) {
  7191. var v = this.vectorsWorld[index];
  7192. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7193. if (v.x < this.minimumWorld.x)
  7194. this.minimumWorld.x = v.x;
  7195. if (v.y < this.minimumWorld.y)
  7196. this.minimumWorld.y = v.y;
  7197. if (v.z < this.minimumWorld.z)
  7198. this.minimumWorld.z = v.z;
  7199. if (v.x > this.maximumWorld.x)
  7200. this.maximumWorld.x = v.x;
  7201. if (v.y > this.maximumWorld.y)
  7202. this.maximumWorld.y = v.y;
  7203. if (v.z > this.maximumWorld.z)
  7204. this.maximumWorld.z = v.z;
  7205. }
  7206. // OBB
  7207. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7208. this.center.scaleInPlace(0.5);
  7209. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7210. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7211. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7212. this._worldMatrix = world;
  7213. };
  7214. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7215. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7216. };
  7217. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7218. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7219. };
  7220. BoundingBox.prototype.intersectsPoint = function (point) {
  7221. var delta = -BABYLON.Engine.Epsilon;
  7222. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7223. return false;
  7224. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7225. return false;
  7226. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7227. return false;
  7228. return true;
  7229. };
  7230. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7231. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7232. };
  7233. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7234. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7235. return false;
  7236. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7237. return false;
  7238. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7239. return false;
  7240. return true;
  7241. };
  7242. // Statics
  7243. BoundingBox.Intersects = function (box0, box1) {
  7244. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7245. return false;
  7246. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7247. return false;
  7248. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7249. return false;
  7250. return true;
  7251. };
  7252. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7253. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7254. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7255. return (num <= (sphereRadius * sphereRadius));
  7256. };
  7257. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7258. for (var p = 0; p < 6; p++) {
  7259. for (var i = 0; i < 8; i++) {
  7260. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7261. return false;
  7262. }
  7263. }
  7264. }
  7265. return true;
  7266. };
  7267. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7268. for (var p = 0; p < 6; p++) {
  7269. var inCount = 8;
  7270. for (var i = 0; i < 8; i++) {
  7271. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7272. --inCount;
  7273. }
  7274. else {
  7275. break;
  7276. }
  7277. }
  7278. if (inCount === 0)
  7279. return false;
  7280. }
  7281. return true;
  7282. };
  7283. return BoundingBox;
  7284. })();
  7285. BABYLON.BoundingBox = BoundingBox;
  7286. })(BABYLON || (BABYLON = {}));
  7287. var BABYLON;
  7288. (function (BABYLON) {
  7289. var computeBoxExtents = function (axis, box) {
  7290. var p = BABYLON.Vector3.Dot(box.center, axis);
  7291. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7292. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7293. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7294. var r = r0 + r1 + r2;
  7295. return {
  7296. min: p - r,
  7297. max: p + r
  7298. };
  7299. };
  7300. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7301. var axisOverlap = function (axis, box0, box1) {
  7302. var result0 = computeBoxExtents(axis, box0);
  7303. var result1 = computeBoxExtents(axis, box1);
  7304. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7305. };
  7306. var BoundingInfo = (function () {
  7307. function BoundingInfo(minimum, maximum) {
  7308. this.minimum = minimum;
  7309. this.maximum = maximum;
  7310. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7311. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7312. }
  7313. // Methods
  7314. BoundingInfo.prototype._update = function (world) {
  7315. this.boundingBox._update(world);
  7316. this.boundingSphere._update(world);
  7317. };
  7318. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7319. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7320. return false;
  7321. return this.boundingBox.isInFrustum(frustumPlanes);
  7322. };
  7323. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7324. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7325. };
  7326. BoundingInfo.prototype._checkCollision = function (collider) {
  7327. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7328. };
  7329. BoundingInfo.prototype.intersectsPoint = function (point) {
  7330. if (!this.boundingSphere.centerWorld) {
  7331. return false;
  7332. }
  7333. if (!this.boundingSphere.intersectsPoint(point)) {
  7334. return false;
  7335. }
  7336. if (!this.boundingBox.intersectsPoint(point)) {
  7337. return false;
  7338. }
  7339. return true;
  7340. };
  7341. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7342. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7343. return false;
  7344. }
  7345. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7346. return false;
  7347. }
  7348. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7349. return false;
  7350. }
  7351. if (!precise) {
  7352. return true;
  7353. }
  7354. var box0 = this.boundingBox;
  7355. var box1 = boundingInfo.boundingBox;
  7356. if (!axisOverlap(box0.directions[0], box0, box1))
  7357. return false;
  7358. if (!axisOverlap(box0.directions[1], box0, box1))
  7359. return false;
  7360. if (!axisOverlap(box0.directions[2], box0, box1))
  7361. return false;
  7362. if (!axisOverlap(box1.directions[0], box0, box1))
  7363. return false;
  7364. if (!axisOverlap(box1.directions[1], box0, box1))
  7365. return false;
  7366. if (!axisOverlap(box1.directions[2], box0, box1))
  7367. return false;
  7368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7369. return false;
  7370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7371. return false;
  7372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7373. return false;
  7374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7375. return false;
  7376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7377. return false;
  7378. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7379. return false;
  7380. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7381. return false;
  7382. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7383. return false;
  7384. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7385. return false;
  7386. return true;
  7387. };
  7388. return BoundingInfo;
  7389. })();
  7390. BABYLON.BoundingInfo = BoundingInfo;
  7391. })(BABYLON || (BABYLON = {}));
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var AbstractMesh = (function (_super) {
  7395. __extends(AbstractMesh, _super);
  7396. function AbstractMesh(name, scene) {
  7397. var _this = this;
  7398. _super.call(this, name, scene);
  7399. // Properties
  7400. this.definedFacingForward = true; // orientation for POV movement & rotation
  7401. this.position = new BABYLON.Vector3(0, 0, 0);
  7402. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7403. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7404. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7405. this.visibility = 1.0;
  7406. this.alphaIndex = Number.MAX_VALUE;
  7407. this.infiniteDistance = false;
  7408. this.isVisible = true;
  7409. this.isPickable = true;
  7410. this.showBoundingBox = false;
  7411. this.showSubMeshesBoundingBox = false;
  7412. this.onDispose = null;
  7413. this.isBlocker = false;
  7414. this.renderingGroupId = 0;
  7415. this.receiveShadows = false;
  7416. this.renderOutline = false;
  7417. this.outlineColor = BABYLON.Color3.Red();
  7418. this.outlineWidth = 0.02;
  7419. this.renderOverlay = false;
  7420. this.overlayColor = BABYLON.Color3.Red();
  7421. this.overlayAlpha = 0.5;
  7422. this.hasVertexAlpha = false;
  7423. this.useVertexColors = true;
  7424. this.applyFog = true;
  7425. this.computeBonesUsingShaders = true;
  7426. this.scalingDeterminant = 1;
  7427. this.numBoneInfluencers = 4;
  7428. this.useOctreeForRenderingSelection = true;
  7429. this.useOctreeForPicking = true;
  7430. this.useOctreeForCollisions = true;
  7431. this.layerMask = 0x0FFFFFFF;
  7432. this.alwaysSelectAsActiveMesh = false;
  7433. // Physics
  7434. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7435. // Collisions
  7436. this._checkCollisions = false;
  7437. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7438. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7439. this._collider = new BABYLON.Collider();
  7440. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7441. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7442. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7443. // Edges
  7444. this.edgesWidth = 1;
  7445. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7446. // Cache
  7447. this._localScaling = BABYLON.Matrix.Zero();
  7448. this._localRotation = BABYLON.Matrix.Zero();
  7449. this._localTranslation = BABYLON.Matrix.Zero();
  7450. this._localBillboard = BABYLON.Matrix.Zero();
  7451. this._localPivotScaling = BABYLON.Matrix.Zero();
  7452. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7453. this._localWorld = BABYLON.Matrix.Zero();
  7454. this._worldMatrix = BABYLON.Matrix.Zero();
  7455. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7456. this._absolutePosition = BABYLON.Vector3.Zero();
  7457. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7458. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7459. this._isDirty = false;
  7460. this._pivotMatrix = BABYLON.Matrix.Identity();
  7461. this._isDisposed = false;
  7462. this._renderId = 0;
  7463. this._intersectionsInProgress = new Array();
  7464. this._onAfterWorldMatrixUpdate = new Array();
  7465. this._isWorldMatrixFrozen = false;
  7466. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7467. if (collidedMesh === void 0) { collidedMesh = null; }
  7468. //TODO move this to the collision coordinator!
  7469. if (_this.getScene().workerCollisions)
  7470. newPosition.multiplyInPlace(_this._collider.radius);
  7471. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7472. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7473. _this.position.addInPlace(_this._diffPositionForCollisions);
  7474. }
  7475. if (_this.onCollide && collidedMesh) {
  7476. _this.onCollide(collidedMesh);
  7477. }
  7478. };
  7479. scene.addMesh(this);
  7480. }
  7481. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7482. get: function () {
  7483. return AbstractMesh._BILLBOARDMODE_NONE;
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7489. get: function () {
  7490. return AbstractMesh._BILLBOARDMODE_X;
  7491. },
  7492. enumerable: true,
  7493. configurable: true
  7494. });
  7495. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7496. get: function () {
  7497. return AbstractMesh._BILLBOARDMODE_Y;
  7498. },
  7499. enumerable: true,
  7500. configurable: true
  7501. });
  7502. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7503. get: function () {
  7504. return AbstractMesh._BILLBOARDMODE_Z;
  7505. },
  7506. enumerable: true,
  7507. configurable: true
  7508. });
  7509. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7510. get: function () {
  7511. return AbstractMesh._BILLBOARDMODE_ALL;
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. // Methods
  7517. AbstractMesh.prototype.disableEdgesRendering = function () {
  7518. if (this._edgesRenderer !== undefined) {
  7519. this._edgesRenderer.dispose();
  7520. this._edgesRenderer = undefined;
  7521. }
  7522. };
  7523. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7524. if (epsilon === void 0) { epsilon = 0.95; }
  7525. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7526. this.disableEdgesRendering();
  7527. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7528. };
  7529. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7530. get: function () {
  7531. return false;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. AbstractMesh.prototype.getLOD = function (camera) {
  7537. return this;
  7538. };
  7539. AbstractMesh.prototype.getTotalVertices = function () {
  7540. return 0;
  7541. };
  7542. AbstractMesh.prototype.getIndices = function () {
  7543. return null;
  7544. };
  7545. AbstractMesh.prototype.getVerticesData = function (kind) {
  7546. return null;
  7547. };
  7548. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7549. return false;
  7550. };
  7551. AbstractMesh.prototype.getBoundingInfo = function () {
  7552. if (this._masterMesh) {
  7553. return this._masterMesh.getBoundingInfo();
  7554. }
  7555. if (!this._boundingInfo) {
  7556. this._updateBoundingInfo();
  7557. }
  7558. return this._boundingInfo;
  7559. };
  7560. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7561. get: function () {
  7562. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. AbstractMesh.prototype._preActivate = function () {
  7568. };
  7569. AbstractMesh.prototype._activate = function (renderId) {
  7570. this._renderId = renderId;
  7571. };
  7572. AbstractMesh.prototype.getWorldMatrix = function () {
  7573. if (this._masterMesh) {
  7574. return this._masterMesh.getWorldMatrix();
  7575. }
  7576. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7577. this.computeWorldMatrix();
  7578. }
  7579. return this._worldMatrix;
  7580. };
  7581. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7582. get: function () {
  7583. return this._worldMatrix;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7589. get: function () {
  7590. return this._absolutePosition;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7596. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7597. this.computeWorldMatrix(true);
  7598. this._isWorldMatrixFrozen = true;
  7599. };
  7600. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7601. this._isWorldMatrixFrozen = false;
  7602. this.computeWorldMatrix(true);
  7603. };
  7604. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7605. get: function () {
  7606. return this._isWorldMatrixFrozen;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7612. axis.normalize();
  7613. if (!this.rotationQuaternion) {
  7614. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7615. this.rotation = BABYLON.Vector3.Zero();
  7616. }
  7617. var rotationQuaternion;
  7618. if (!space || space === BABYLON.Space.LOCAL) {
  7619. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7620. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7621. }
  7622. else {
  7623. if (this.parent) {
  7624. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7625. invertParentWorldMatrix.invert();
  7626. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7627. }
  7628. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7629. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7630. }
  7631. };
  7632. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7633. var displacementVector = axis.scale(distance);
  7634. if (!space || space === BABYLON.Space.LOCAL) {
  7635. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7636. this.setPositionWithLocalVector(tempV3);
  7637. }
  7638. else {
  7639. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7640. }
  7641. };
  7642. AbstractMesh.prototype.getAbsolutePosition = function () {
  7643. this.computeWorldMatrix();
  7644. return this._absolutePosition;
  7645. };
  7646. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7647. if (!absolutePosition) {
  7648. return;
  7649. }
  7650. var absolutePositionX;
  7651. var absolutePositionY;
  7652. var absolutePositionZ;
  7653. if (absolutePosition.x === undefined) {
  7654. if (arguments.length < 3) {
  7655. return;
  7656. }
  7657. absolutePositionX = arguments[0];
  7658. absolutePositionY = arguments[1];
  7659. absolutePositionZ = arguments[2];
  7660. }
  7661. else {
  7662. absolutePositionX = absolutePosition.x;
  7663. absolutePositionY = absolutePosition.y;
  7664. absolutePositionZ = absolutePosition.z;
  7665. }
  7666. if (this.parent) {
  7667. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7668. invertParentWorldMatrix.invert();
  7669. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7670. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7671. }
  7672. else {
  7673. this.position.x = absolutePositionX;
  7674. this.position.y = absolutePositionY;
  7675. this.position.z = absolutePositionZ;
  7676. }
  7677. };
  7678. // ================================== Point of View Movement =================================
  7679. /**
  7680. * Perform relative position change from the point of view of behind the front of the mesh.
  7681. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7682. * Supports definition of mesh facing forward or backward.
  7683. * @param {number} amountRight
  7684. * @param {number} amountUp
  7685. * @param {number} amountForward
  7686. */
  7687. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7688. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7689. };
  7690. /**
  7691. * Calculate relative position change from the point of view of behind the front of the mesh.
  7692. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7693. * Supports definition of mesh facing forward or backward.
  7694. * @param {number} amountRight
  7695. * @param {number} amountUp
  7696. * @param {number} amountForward
  7697. */
  7698. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7699. var rotMatrix = new BABYLON.Matrix();
  7700. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7701. rotQuaternion.toRotationMatrix(rotMatrix);
  7702. var translationDelta = BABYLON.Vector3.Zero();
  7703. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7704. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7705. return translationDelta;
  7706. };
  7707. // ================================== Point of View Rotation =================================
  7708. /**
  7709. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7710. * Supports definition of mesh facing forward or backward.
  7711. * @param {number} flipBack
  7712. * @param {number} twirlClockwise
  7713. * @param {number} tiltRight
  7714. */
  7715. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7716. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7717. };
  7718. /**
  7719. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7720. * Supports definition of mesh facing forward or backward.
  7721. * @param {number} flipBack
  7722. * @param {number} twirlClockwise
  7723. * @param {number} tiltRight
  7724. */
  7725. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7726. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7727. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7728. };
  7729. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7730. this._pivotMatrix = matrix;
  7731. this._cache.pivotMatrixUpdated = true;
  7732. };
  7733. AbstractMesh.prototype.getPivotMatrix = function () {
  7734. return this._pivotMatrix;
  7735. };
  7736. AbstractMesh.prototype._isSynchronized = function () {
  7737. if (this._isDirty) {
  7738. return false;
  7739. }
  7740. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7741. return false;
  7742. if (this._cache.pivotMatrixUpdated) {
  7743. return false;
  7744. }
  7745. if (this.infiniteDistance) {
  7746. return false;
  7747. }
  7748. if (!this._cache.position.equals(this.position))
  7749. return false;
  7750. if (this.rotationQuaternion) {
  7751. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7752. return false;
  7753. }
  7754. else {
  7755. if (!this._cache.rotation.equals(this.rotation))
  7756. return false;
  7757. }
  7758. if (!this._cache.scaling.equals(this.scaling))
  7759. return false;
  7760. return true;
  7761. };
  7762. AbstractMesh.prototype._initCache = function () {
  7763. _super.prototype._initCache.call(this);
  7764. this._cache.localMatrixUpdated = false;
  7765. this._cache.position = BABYLON.Vector3.Zero();
  7766. this._cache.scaling = BABYLON.Vector3.Zero();
  7767. this._cache.rotation = BABYLON.Vector3.Zero();
  7768. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7769. };
  7770. AbstractMesh.prototype.markAsDirty = function (property) {
  7771. if (property === "rotation") {
  7772. this.rotationQuaternion = null;
  7773. }
  7774. this._currentRenderId = Number.MAX_VALUE;
  7775. this._isDirty = true;
  7776. };
  7777. AbstractMesh.prototype._updateBoundingInfo = function () {
  7778. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7779. this._boundingInfo._update(this.worldMatrixFromCache);
  7780. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7781. };
  7782. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7783. if (!this.subMeshes) {
  7784. return;
  7785. }
  7786. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7787. var subMesh = this.subMeshes[subIndex];
  7788. subMesh.updateBoundingInfo(matrix);
  7789. }
  7790. };
  7791. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7792. if (this._isWorldMatrixFrozen) {
  7793. return this._worldMatrix;
  7794. }
  7795. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7796. return this._worldMatrix;
  7797. }
  7798. this._cache.position.copyFrom(this.position);
  7799. this._cache.scaling.copyFrom(this.scaling);
  7800. this._cache.pivotMatrixUpdated = false;
  7801. this._currentRenderId = this.getScene().getRenderId();
  7802. this._isDirty = false;
  7803. // Scaling
  7804. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7805. // Rotation
  7806. if (this.rotationQuaternion) {
  7807. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7808. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7809. }
  7810. else {
  7811. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7812. this._cache.rotation.copyFrom(this.rotation);
  7813. }
  7814. // Translation
  7815. if (this.infiniteDistance && !this.parent) {
  7816. var camera = this.getScene().activeCamera;
  7817. if (camera) {
  7818. var cameraWorldMatrix = camera.getWorldMatrix();
  7819. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7820. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7821. }
  7822. }
  7823. else {
  7824. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7825. }
  7826. // Composing transformations
  7827. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7828. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7829. // Billboarding
  7830. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7831. var localPosition = this.position.clone();
  7832. var zero = this.getScene().activeCamera.globalPosition.clone();
  7833. if (this.parent && this.parent.position) {
  7834. localPosition.addInPlace(this.parent.position);
  7835. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7836. }
  7837. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7838. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7839. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7840. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7841. zero.y = localPosition.y + 0.001;
  7842. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7843. zero.z = localPosition.z + 0.001;
  7844. }
  7845. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7846. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7847. this._localBillboard.invert();
  7848. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7849. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7850. }
  7851. // Local world
  7852. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7853. // Parent
  7854. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7855. this._markSyncedWithParent();
  7856. if (this._meshToBoneReferal) {
  7857. if (!this._localMeshReferalTransform) {
  7858. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7859. }
  7860. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7861. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7862. }
  7863. else {
  7864. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7865. }
  7866. }
  7867. else {
  7868. this._worldMatrix.copyFrom(this._localWorld);
  7869. }
  7870. // Bounding info
  7871. this._updateBoundingInfo();
  7872. // Absolute position
  7873. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7874. // Callbacks
  7875. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7876. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7877. }
  7878. return this._worldMatrix;
  7879. };
  7880. /**
  7881. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7882. * @param func: callback function to add
  7883. */
  7884. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7885. this._onAfterWorldMatrixUpdate.push(func);
  7886. };
  7887. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7888. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7889. if (index > -1) {
  7890. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7891. }
  7892. };
  7893. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7894. this.computeWorldMatrix();
  7895. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7896. };
  7897. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7898. this.computeWorldMatrix();
  7899. var invLocalWorldMatrix = this._localWorld.clone();
  7900. invLocalWorldMatrix.invert();
  7901. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7902. };
  7903. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7904. this.computeWorldMatrix(true);
  7905. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7906. };
  7907. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7908. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7909. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7910. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7911. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7912. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7913. /// <returns>Mesh oriented towards targetMesh</returns>
  7914. yawCor = yawCor || 0; // default to zero if undefined
  7915. pitchCor = pitchCor || 0;
  7916. rollCor = rollCor || 0;
  7917. var dv = targetPoint.subtract(this.position);
  7918. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7919. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7920. var pitch = Math.atan2(dv.y, len);
  7921. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7922. };
  7923. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  7924. this._meshToBoneReferal = affectedMesh;
  7925. this.parent = bone;
  7926. if (bone.getWorldMatrix().determinant() < 0) {
  7927. this.scalingDeterminant *= -1;
  7928. }
  7929. };
  7930. AbstractMesh.prototype.detachFromBone = function () {
  7931. if (this.parent.getWorldMatrix().determinant() < 0) {
  7932. this.scalingDeterminant *= -1;
  7933. }
  7934. this._meshToBoneReferal = null;
  7935. this.parent = null;
  7936. };
  7937. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7938. return this._boundingInfo.isInFrustum(frustumPlanes);
  7939. };
  7940. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7941. if (!camera) {
  7942. camera = this.getScene().activeCamera;
  7943. }
  7944. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7945. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7946. return false;
  7947. }
  7948. return true;
  7949. };
  7950. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7951. if (!this._boundingInfo || !mesh._boundingInfo) {
  7952. return false;
  7953. }
  7954. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7955. };
  7956. AbstractMesh.prototype.intersectsPoint = function (point) {
  7957. if (!this._boundingInfo) {
  7958. return false;
  7959. }
  7960. return this._boundingInfo.intersectsPoint(point);
  7961. };
  7962. // Physics
  7963. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7964. var physicsEngine = this.getScene().getPhysicsEngine();
  7965. if (!physicsEngine) {
  7966. return null;
  7967. }
  7968. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7969. if (impostor.impostor) {
  7970. // Old API
  7971. options = impostor;
  7972. impostor = impostor.impostor;
  7973. }
  7974. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7975. physicsEngine._unregisterMesh(this);
  7976. return null;
  7977. }
  7978. if (!options) {
  7979. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7980. }
  7981. else {
  7982. if (!options.mass && options.mass !== 0)
  7983. options.mass = 0;
  7984. if (!options.friction && options.friction !== 0)
  7985. options.friction = 0.2;
  7986. if (!options.restitution && options.restitution !== 0)
  7987. options.restitution = 0.2;
  7988. }
  7989. this._physicImpostor = impostor;
  7990. this._physicsMass = options.mass;
  7991. this._physicsFriction = options.friction;
  7992. this._physicRestitution = options.restitution;
  7993. return physicsEngine._registerMesh(this, impostor, options);
  7994. };
  7995. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7996. if (!this._physicImpostor) {
  7997. return BABYLON.PhysicsEngine.NoImpostor;
  7998. }
  7999. return this._physicImpostor;
  8000. };
  8001. AbstractMesh.prototype.getPhysicsMass = function () {
  8002. if (!this._physicsMass) {
  8003. return 0;
  8004. }
  8005. return this._physicsMass;
  8006. };
  8007. AbstractMesh.prototype.getPhysicsFriction = function () {
  8008. if (!this._physicsFriction) {
  8009. return 0;
  8010. }
  8011. return this._physicsFriction;
  8012. };
  8013. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8014. if (!this._physicRestitution) {
  8015. return 0;
  8016. }
  8017. return this._physicRestitution;
  8018. };
  8019. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8020. if (!camera) {
  8021. camera = this.getScene().activeCamera;
  8022. }
  8023. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8024. };
  8025. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8026. if (!camera) {
  8027. camera = this.getScene().activeCamera;
  8028. }
  8029. return this.absolutePosition.subtract(camera.position).length();
  8030. };
  8031. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8032. if (!this._physicImpostor) {
  8033. return;
  8034. }
  8035. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8036. };
  8037. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8038. if (!this._physicImpostor) {
  8039. return;
  8040. }
  8041. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8042. };
  8043. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8044. if (!this._physicImpostor) {
  8045. return;
  8046. }
  8047. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8048. };
  8049. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8050. // Collisions
  8051. get: function () {
  8052. return this._checkCollisions;
  8053. },
  8054. set: function (collisionEnabled) {
  8055. this._checkCollisions = collisionEnabled;
  8056. if (this.getScene().workerCollisions) {
  8057. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8058. }
  8059. },
  8060. enumerable: true,
  8061. configurable: true
  8062. });
  8063. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8064. var globalPosition = this.getAbsolutePosition();
  8065. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8066. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8067. this._collider.radius = this.ellipsoid;
  8068. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8069. };
  8070. // Submeshes octree
  8071. /**
  8072. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8073. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8074. */
  8075. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8076. if (maxCapacity === void 0) { maxCapacity = 64; }
  8077. if (maxDepth === void 0) { maxDepth = 2; }
  8078. if (!this._submeshesOctree) {
  8079. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8080. }
  8081. this.computeWorldMatrix(true);
  8082. // Update octree
  8083. var bbox = this.getBoundingInfo().boundingBox;
  8084. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8085. return this._submeshesOctree;
  8086. };
  8087. // Collisions
  8088. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8089. this._generatePointsArray();
  8090. // Transformation
  8091. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8092. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8093. subMesh._lastColliderWorldVertices = [];
  8094. subMesh._trianglePlanes = [];
  8095. var start = subMesh.verticesStart;
  8096. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8097. for (var i = start; i < end; i++) {
  8098. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8099. }
  8100. }
  8101. // Collide
  8102. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8103. if (collider.collisionFound) {
  8104. collider.collidedMesh = this;
  8105. }
  8106. };
  8107. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8108. var subMeshes;
  8109. var len;
  8110. // Octrees
  8111. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8112. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8113. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8114. len = intersections.length;
  8115. subMeshes = intersections.data;
  8116. }
  8117. else {
  8118. subMeshes = this.subMeshes;
  8119. len = subMeshes.length;
  8120. }
  8121. for (var index = 0; index < len; index++) {
  8122. var subMesh = subMeshes[index];
  8123. // Bounding test
  8124. if (len > 1 && !subMesh._checkCollision(collider))
  8125. continue;
  8126. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8127. }
  8128. };
  8129. AbstractMesh.prototype._checkCollision = function (collider) {
  8130. // Bounding box test
  8131. if (!this._boundingInfo._checkCollision(collider))
  8132. return;
  8133. // Transformation matrix
  8134. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8135. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8136. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8137. };
  8138. // Picking
  8139. AbstractMesh.prototype._generatePointsArray = function () {
  8140. return false;
  8141. };
  8142. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8143. var pickingInfo = new BABYLON.PickingInfo();
  8144. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8145. return pickingInfo;
  8146. }
  8147. if (!this._generatePointsArray()) {
  8148. return pickingInfo;
  8149. }
  8150. var intersectInfo = null;
  8151. // Octrees
  8152. var subMeshes;
  8153. var len;
  8154. if (this._submeshesOctree && this.useOctreeForPicking) {
  8155. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8156. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8157. len = intersections.length;
  8158. subMeshes = intersections.data;
  8159. }
  8160. else {
  8161. subMeshes = this.subMeshes;
  8162. len = subMeshes.length;
  8163. }
  8164. for (var index = 0; index < len; index++) {
  8165. var subMesh = subMeshes[index];
  8166. // Bounding test
  8167. if (len > 1 && !subMesh.canIntersects(ray))
  8168. continue;
  8169. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8170. if (currentIntersectInfo) {
  8171. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8172. intersectInfo = currentIntersectInfo;
  8173. intersectInfo.subMeshId = index;
  8174. if (fastCheck) {
  8175. break;
  8176. }
  8177. }
  8178. }
  8179. }
  8180. if (intersectInfo) {
  8181. // Get picked point
  8182. var world = this.getWorldMatrix();
  8183. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8184. var direction = ray.direction.clone();
  8185. direction = direction.scale(intersectInfo.distance);
  8186. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8187. var pickedPoint = worldOrigin.add(worldDirection);
  8188. // Return result
  8189. pickingInfo.hit = true;
  8190. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8191. pickingInfo.pickedPoint = pickedPoint;
  8192. pickingInfo.pickedMesh = this;
  8193. pickingInfo.bu = intersectInfo.bu;
  8194. pickingInfo.bv = intersectInfo.bv;
  8195. pickingInfo.faceId = intersectInfo.faceId;
  8196. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8197. return pickingInfo;
  8198. }
  8199. return pickingInfo;
  8200. };
  8201. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8202. return null;
  8203. };
  8204. AbstractMesh.prototype.releaseSubMeshes = function () {
  8205. if (this.subMeshes) {
  8206. while (this.subMeshes.length) {
  8207. this.subMeshes[0].dispose();
  8208. }
  8209. }
  8210. else {
  8211. this.subMeshes = new Array();
  8212. }
  8213. };
  8214. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8215. var index;
  8216. // Animations
  8217. this.getScene().stopAnimation(this);
  8218. // Physics
  8219. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8220. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8221. }
  8222. // Intersections in progress
  8223. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8224. var other = this._intersectionsInProgress[index];
  8225. var pos = other._intersectionsInProgress.indexOf(this);
  8226. other._intersectionsInProgress.splice(pos, 1);
  8227. }
  8228. this._intersectionsInProgress = [];
  8229. // Edges
  8230. if (this._edgesRenderer) {
  8231. this._edgesRenderer.dispose();
  8232. this._edgesRenderer = null;
  8233. }
  8234. // SubMeshes
  8235. this.releaseSubMeshes();
  8236. // Remove from scene
  8237. this.getScene().removeMesh(this);
  8238. if (!doNotRecurse) {
  8239. // Particles
  8240. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8241. if (this.getScene().particleSystems[index].emitter === this) {
  8242. this.getScene().particleSystems[index].dispose();
  8243. index--;
  8244. }
  8245. }
  8246. // Children
  8247. var objects = this.getScene().meshes.slice(0);
  8248. for (index = 0; index < objects.length; index++) {
  8249. if (objects[index].parent === this) {
  8250. objects[index].dispose();
  8251. }
  8252. }
  8253. }
  8254. else {
  8255. for (index = 0; index < this.getScene().meshes.length; index++) {
  8256. var obj = this.getScene().meshes[index];
  8257. if (obj.parent === this) {
  8258. obj.parent = null;
  8259. obj.computeWorldMatrix(true);
  8260. }
  8261. }
  8262. }
  8263. this._onAfterWorldMatrixUpdate = [];
  8264. this._isDisposed = true;
  8265. // Callback
  8266. if (this.onDispose) {
  8267. this.onDispose();
  8268. }
  8269. };
  8270. // Statics
  8271. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8272. AbstractMesh._BILLBOARDMODE_X = 1;
  8273. AbstractMesh._BILLBOARDMODE_Y = 2;
  8274. AbstractMesh._BILLBOARDMODE_Z = 4;
  8275. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8276. return AbstractMesh;
  8277. })(BABYLON.Node);
  8278. BABYLON.AbstractMesh = AbstractMesh;
  8279. })(BABYLON || (BABYLON = {}));
  8280. var BABYLON;
  8281. (function (BABYLON) {
  8282. var Light = (function (_super) {
  8283. __extends(Light, _super);
  8284. function Light(name, scene) {
  8285. _super.call(this, name, scene);
  8286. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8287. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8288. this.intensity = 1.0;
  8289. this.range = Number.MAX_VALUE;
  8290. this.includeOnlyWithLayerMask = 0;
  8291. this.includedOnlyMeshes = new Array();
  8292. this.excludedMeshes = new Array();
  8293. this.excludeWithLayerMask = 0;
  8294. this._excludedMeshesIds = new Array();
  8295. this._includedOnlyMeshesIds = new Array();
  8296. scene.addLight(this);
  8297. }
  8298. Light.prototype.getShadowGenerator = function () {
  8299. return this._shadowGenerator;
  8300. };
  8301. Light.prototype.getAbsolutePosition = function () {
  8302. return BABYLON.Vector3.Zero();
  8303. };
  8304. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8305. };
  8306. Light.prototype._getWorldMatrix = function () {
  8307. return BABYLON.Matrix.Identity();
  8308. };
  8309. Light.prototype.canAffectMesh = function (mesh) {
  8310. if (!mesh) {
  8311. return true;
  8312. }
  8313. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8314. return false;
  8315. }
  8316. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8317. return false;
  8318. }
  8319. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8320. return false;
  8321. }
  8322. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8323. return false;
  8324. }
  8325. return true;
  8326. };
  8327. Light.prototype.getWorldMatrix = function () {
  8328. this._currentRenderId = this.getScene().getRenderId();
  8329. var worldMatrix = this._getWorldMatrix();
  8330. if (this.parent && this.parent.getWorldMatrix) {
  8331. if (!this._parentedWorldMatrix) {
  8332. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8333. }
  8334. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8335. this._markSyncedWithParent();
  8336. return this._parentedWorldMatrix;
  8337. }
  8338. return worldMatrix;
  8339. };
  8340. Light.prototype.dispose = function () {
  8341. if (this._shadowGenerator) {
  8342. this._shadowGenerator.dispose();
  8343. this._shadowGenerator = null;
  8344. }
  8345. // Animations
  8346. this.getScene().stopAnimation(this);
  8347. // Remove from scene
  8348. this.getScene().removeLight(this);
  8349. };
  8350. return Light;
  8351. })(BABYLON.Node);
  8352. BABYLON.Light = Light;
  8353. })(BABYLON || (BABYLON = {}));
  8354. var BABYLON;
  8355. (function (BABYLON) {
  8356. var PointLight = (function (_super) {
  8357. __extends(PointLight, _super);
  8358. function PointLight(name, position, scene) {
  8359. _super.call(this, name, scene);
  8360. this.position = position;
  8361. }
  8362. PointLight.prototype.getAbsolutePosition = function () {
  8363. return this.transformedPosition ? this.transformedPosition : this.position;
  8364. };
  8365. PointLight.prototype.computeTransformedPosition = function () {
  8366. if (this.parent && this.parent.getWorldMatrix) {
  8367. if (!this.transformedPosition) {
  8368. this.transformedPosition = BABYLON.Vector3.Zero();
  8369. }
  8370. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8371. return true;
  8372. }
  8373. return false;
  8374. };
  8375. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8376. if (this.parent && this.parent.getWorldMatrix) {
  8377. this.computeTransformedPosition();
  8378. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8379. return;
  8380. }
  8381. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8382. };
  8383. PointLight.prototype.needCube = function () {
  8384. return true;
  8385. };
  8386. PointLight.prototype.supportsVSM = function () {
  8387. return false;
  8388. };
  8389. PointLight.prototype.needRefreshPerFrame = function () {
  8390. return false;
  8391. };
  8392. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8393. switch (faceIndex) {
  8394. case 0:
  8395. return new BABYLON.Vector3(1, 0, 0);
  8396. case 1:
  8397. return new BABYLON.Vector3(-1, 0, 0);
  8398. case 2:
  8399. return new BABYLON.Vector3(0, -1, 0);
  8400. case 3:
  8401. return new BABYLON.Vector3(0, 1, 0);
  8402. case 4:
  8403. return new BABYLON.Vector3(0, 0, 1);
  8404. case 5:
  8405. return new BABYLON.Vector3(0, 0, -1);
  8406. }
  8407. return BABYLON.Vector3.Zero();
  8408. };
  8409. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8410. var activeCamera = this.getScene().activeCamera;
  8411. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8412. };
  8413. PointLight.prototype._getWorldMatrix = function () {
  8414. if (!this._worldMatrix) {
  8415. this._worldMatrix = BABYLON.Matrix.Identity();
  8416. }
  8417. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8418. return this._worldMatrix;
  8419. };
  8420. return PointLight;
  8421. })(BABYLON.Light);
  8422. BABYLON.PointLight = PointLight;
  8423. })(BABYLON || (BABYLON = {}));
  8424. var BABYLON;
  8425. (function (BABYLON) {
  8426. var SpotLight = (function (_super) {
  8427. __extends(SpotLight, _super);
  8428. function SpotLight(name, position, direction, angle, exponent, scene) {
  8429. _super.call(this, name, scene);
  8430. this.position = position;
  8431. this.direction = direction;
  8432. this.angle = angle;
  8433. this.exponent = exponent;
  8434. }
  8435. SpotLight.prototype.getAbsolutePosition = function () {
  8436. return this.transformedPosition ? this.transformedPosition : this.position;
  8437. };
  8438. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8439. var activeCamera = this.getScene().activeCamera;
  8440. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8441. };
  8442. SpotLight.prototype.needCube = function () {
  8443. return false;
  8444. };
  8445. SpotLight.prototype.supportsVSM = function () {
  8446. return true;
  8447. };
  8448. SpotLight.prototype.needRefreshPerFrame = function () {
  8449. return false;
  8450. };
  8451. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8452. return this.direction;
  8453. };
  8454. SpotLight.prototype.setDirectionToTarget = function (target) {
  8455. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8456. return this.direction;
  8457. };
  8458. SpotLight.prototype.computeTransformedPosition = function () {
  8459. if (this.parent && this.parent.getWorldMatrix) {
  8460. if (!this.transformedPosition) {
  8461. this.transformedPosition = BABYLON.Vector3.Zero();
  8462. }
  8463. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8464. return true;
  8465. }
  8466. return false;
  8467. };
  8468. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8469. var normalizeDirection;
  8470. if (this.parent && this.parent.getWorldMatrix) {
  8471. if (!this._transformedDirection) {
  8472. this._transformedDirection = BABYLON.Vector3.Zero();
  8473. }
  8474. this.computeTransformedPosition();
  8475. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8476. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8477. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8478. }
  8479. else {
  8480. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8481. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8482. }
  8483. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8484. };
  8485. SpotLight.prototype._getWorldMatrix = function () {
  8486. if (!this._worldMatrix) {
  8487. this._worldMatrix = BABYLON.Matrix.Identity();
  8488. }
  8489. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8490. return this._worldMatrix;
  8491. };
  8492. return SpotLight;
  8493. })(BABYLON.Light);
  8494. BABYLON.SpotLight = SpotLight;
  8495. })(BABYLON || (BABYLON = {}));
  8496. var BABYLON;
  8497. (function (BABYLON) {
  8498. var HemisphericLight = (function (_super) {
  8499. __extends(HemisphericLight, _super);
  8500. function HemisphericLight(name, direction, scene) {
  8501. _super.call(this, name, scene);
  8502. this.direction = direction;
  8503. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8504. }
  8505. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8506. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8507. return this.direction;
  8508. };
  8509. HemisphericLight.prototype.getShadowGenerator = function () {
  8510. return null;
  8511. };
  8512. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8513. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8514. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8515. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8516. };
  8517. HemisphericLight.prototype._getWorldMatrix = function () {
  8518. if (!this._worldMatrix) {
  8519. this._worldMatrix = BABYLON.Matrix.Identity();
  8520. }
  8521. return this._worldMatrix;
  8522. };
  8523. return HemisphericLight;
  8524. })(BABYLON.Light);
  8525. BABYLON.HemisphericLight = HemisphericLight;
  8526. })(BABYLON || (BABYLON = {}));
  8527. var BABYLON;
  8528. (function (BABYLON) {
  8529. var DirectionalLight = (function (_super) {
  8530. __extends(DirectionalLight, _super);
  8531. function DirectionalLight(name, direction, scene) {
  8532. _super.call(this, name, scene);
  8533. this.direction = direction;
  8534. this.shadowOrthoScale = 0.5;
  8535. this.autoUpdateExtends = true;
  8536. // Cache
  8537. this._orthoLeft = Number.MAX_VALUE;
  8538. this._orthoRight = Number.MIN_VALUE;
  8539. this._orthoTop = Number.MIN_VALUE;
  8540. this._orthoBottom = Number.MAX_VALUE;
  8541. this.position = direction.scale(-1);
  8542. }
  8543. DirectionalLight.prototype.getAbsolutePosition = function () {
  8544. return this.transformedPosition ? this.transformedPosition : this.position;
  8545. };
  8546. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8547. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8548. return this.direction;
  8549. };
  8550. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8551. var activeCamera = this.getScene().activeCamera;
  8552. // Check extends
  8553. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8554. var tempVector3 = BABYLON.Vector3.Zero();
  8555. this._orthoLeft = Number.MAX_VALUE;
  8556. this._orthoRight = Number.MIN_VALUE;
  8557. this._orthoTop = Number.MIN_VALUE;
  8558. this._orthoBottom = Number.MAX_VALUE;
  8559. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8560. var mesh = renderList[meshIndex];
  8561. if (!mesh) {
  8562. continue;
  8563. }
  8564. var boundingInfo = mesh.getBoundingInfo();
  8565. if (!boundingInfo) {
  8566. continue;
  8567. }
  8568. var boundingBox = boundingInfo.boundingBox;
  8569. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8570. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8571. if (tempVector3.x < this._orthoLeft)
  8572. this._orthoLeft = tempVector3.x;
  8573. if (tempVector3.y < this._orthoBottom)
  8574. this._orthoBottom = tempVector3.y;
  8575. if (tempVector3.x > this._orthoRight)
  8576. this._orthoRight = tempVector3.x;
  8577. if (tempVector3.y > this._orthoTop)
  8578. this._orthoTop = tempVector3.y;
  8579. }
  8580. }
  8581. }
  8582. var xOffset = this._orthoRight - this._orthoLeft;
  8583. var yOffset = this._orthoTop - this._orthoBottom;
  8584. 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);
  8585. };
  8586. DirectionalLight.prototype.supportsVSM = function () {
  8587. return true;
  8588. };
  8589. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8590. return true;
  8591. };
  8592. DirectionalLight.prototype.needCube = function () {
  8593. return false;
  8594. };
  8595. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8596. return this.direction;
  8597. };
  8598. DirectionalLight.prototype.computeTransformedPosition = function () {
  8599. if (this.parent && this.parent.getWorldMatrix) {
  8600. if (!this.transformedPosition) {
  8601. this.transformedPosition = BABYLON.Vector3.Zero();
  8602. }
  8603. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8604. return true;
  8605. }
  8606. return false;
  8607. };
  8608. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8609. if (this.parent && this.parent.getWorldMatrix) {
  8610. if (!this._transformedDirection) {
  8611. this._transformedDirection = BABYLON.Vector3.Zero();
  8612. }
  8613. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8614. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8615. return;
  8616. }
  8617. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8618. };
  8619. DirectionalLight.prototype._getWorldMatrix = function () {
  8620. if (!this._worldMatrix) {
  8621. this._worldMatrix = BABYLON.Matrix.Identity();
  8622. }
  8623. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8624. return this._worldMatrix;
  8625. };
  8626. return DirectionalLight;
  8627. })(BABYLON.Light);
  8628. BABYLON.DirectionalLight = DirectionalLight;
  8629. })(BABYLON || (BABYLON = {}));
  8630. var BABYLON;
  8631. (function (BABYLON) {
  8632. var ShadowGenerator = (function () {
  8633. function ShadowGenerator(mapSize, light) {
  8634. var _this = this;
  8635. // Members
  8636. this._filter = ShadowGenerator.FILTER_NONE;
  8637. this.blurScale = 2;
  8638. this._blurBoxOffset = 0;
  8639. this._bias = 0.00005;
  8640. this._lightDirection = BABYLON.Vector3.Zero();
  8641. this._darkness = 0;
  8642. this._transparencyShadow = false;
  8643. this._viewMatrix = BABYLON.Matrix.Zero();
  8644. this._projectionMatrix = BABYLON.Matrix.Zero();
  8645. this._transformMatrix = BABYLON.Matrix.Zero();
  8646. this._worldViewProjection = BABYLON.Matrix.Zero();
  8647. this._currentFaceIndex = 0;
  8648. this._currentFaceIndexCache = 0;
  8649. this._light = light;
  8650. this._scene = light.getScene();
  8651. this._mapSize = mapSize;
  8652. light._shadowGenerator = this;
  8653. // Render target
  8654. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8655. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8656. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8657. this._shadowMap.anisotropicFilteringLevel = 1;
  8658. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8659. this._shadowMap.renderParticles = false;
  8660. this._shadowMap.onBeforeRender = function (faceIndex) {
  8661. _this._currentFaceIndex = faceIndex;
  8662. };
  8663. this._shadowMap.onAfterUnbind = function () {
  8664. if (!_this.useBlurVarianceShadowMap) {
  8665. return;
  8666. }
  8667. if (!_this._shadowMap2) {
  8668. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8669. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8670. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8671. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8672. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8673. _this._downSamplePostprocess.onApply = function (effect) {
  8674. effect.setTexture("textureSampler", _this._shadowMap);
  8675. };
  8676. _this.blurBoxOffset = 1;
  8677. }
  8678. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8679. };
  8680. // Custom render function
  8681. var renderSubMesh = function (subMesh) {
  8682. var mesh = subMesh.getRenderingMesh();
  8683. var scene = _this._scene;
  8684. var engine = scene.getEngine();
  8685. // Culling
  8686. engine.setState(subMesh.getMaterial().backFaceCulling);
  8687. // Managing instances
  8688. var batch = mesh._getInstancesRenderList(subMesh._id);
  8689. if (batch.mustReturn) {
  8690. return;
  8691. }
  8692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8693. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8694. engine.enableEffect(_this._effect);
  8695. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8696. var material = subMesh.getMaterial();
  8697. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8698. // Alpha test
  8699. if (material && material.needAlphaTesting()) {
  8700. var alphaTexture = material.getAlphaTestTexture();
  8701. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8702. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8703. }
  8704. // Bones
  8705. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8706. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8707. }
  8708. // Draw
  8709. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8710. }
  8711. else {
  8712. // Need to reset refresh rate of the shadowMap
  8713. _this._shadowMap.resetRefreshCounter();
  8714. }
  8715. };
  8716. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8717. var index;
  8718. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8719. renderSubMesh(opaqueSubMeshes.data[index]);
  8720. }
  8721. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8722. renderSubMesh(alphaTestSubMeshes.data[index]);
  8723. }
  8724. if (_this._transparencyShadow) {
  8725. for (index = 0; index < transparentSubMeshes.length; index++) {
  8726. renderSubMesh(transparentSubMeshes.data[index]);
  8727. }
  8728. }
  8729. };
  8730. this._shadowMap.onClear = function (engine) {
  8731. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8732. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8733. }
  8734. else {
  8735. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8736. }
  8737. };
  8738. }
  8739. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8740. // Static
  8741. get: function () {
  8742. return ShadowGenerator._FILTER_NONE;
  8743. },
  8744. enumerable: true,
  8745. configurable: true
  8746. });
  8747. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8748. get: function () {
  8749. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8750. },
  8751. enumerable: true,
  8752. configurable: true
  8753. });
  8754. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8755. get: function () {
  8756. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8757. },
  8758. enumerable: true,
  8759. configurable: true
  8760. });
  8761. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8762. get: function () {
  8763. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8769. get: function () {
  8770. return this._bias;
  8771. },
  8772. set: function (bias) {
  8773. this._bias = bias;
  8774. },
  8775. enumerable: true,
  8776. configurable: true
  8777. });
  8778. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8779. get: function () {
  8780. return this._blurBoxOffset;
  8781. },
  8782. set: function (value) {
  8783. var _this = this;
  8784. if (this._blurBoxOffset === value) {
  8785. return;
  8786. }
  8787. this._blurBoxOffset = value;
  8788. if (this._boxBlurPostprocess) {
  8789. this._boxBlurPostprocess.dispose();
  8790. }
  8791. 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);
  8792. this._boxBlurPostprocess.onApply = function (effect) {
  8793. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8794. };
  8795. },
  8796. enumerable: true,
  8797. configurable: true
  8798. });
  8799. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8800. get: function () {
  8801. return this._filter;
  8802. },
  8803. set: function (value) {
  8804. if (this._filter === value) {
  8805. return;
  8806. }
  8807. this._filter = value;
  8808. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8809. this._shadowMap.anisotropicFilteringLevel = 16;
  8810. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8811. }
  8812. else {
  8813. this._shadowMap.anisotropicFilteringLevel = 1;
  8814. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8815. }
  8816. },
  8817. enumerable: true,
  8818. configurable: true
  8819. });
  8820. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8821. get: function () {
  8822. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8823. },
  8824. set: function (value) {
  8825. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8826. },
  8827. enumerable: true,
  8828. configurable: true
  8829. });
  8830. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8831. get: function () {
  8832. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8833. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8834. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8835. },
  8836. set: function (value) {
  8837. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8838. },
  8839. enumerable: true,
  8840. configurable: true
  8841. });
  8842. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8843. get: function () {
  8844. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8845. },
  8846. set: function (value) {
  8847. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8848. },
  8849. enumerable: true,
  8850. configurable: true
  8851. });
  8852. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8853. var defines = [];
  8854. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8855. defines.push("#define VSM");
  8856. }
  8857. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8858. var mesh = subMesh.getMesh();
  8859. var material = subMesh.getMaterial();
  8860. // Alpha test
  8861. if (material && material.needAlphaTesting()) {
  8862. defines.push("#define ALPHATEST");
  8863. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8864. attribs.push(BABYLON.VertexBuffer.UVKind);
  8865. defines.push("#define UV1");
  8866. }
  8867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8868. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8869. defines.push("#define UV2");
  8870. }
  8871. }
  8872. // Bones
  8873. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8874. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8875. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8876. defines.push("#define BONES");
  8877. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8878. }
  8879. // Instances
  8880. if (useInstances) {
  8881. defines.push("#define INSTANCES");
  8882. attribs.push("world0");
  8883. attribs.push("world1");
  8884. attribs.push("world2");
  8885. attribs.push("world3");
  8886. }
  8887. // Get correct effect
  8888. var join = defines.join("\n");
  8889. if (this._cachedDefines !== join) {
  8890. this._cachedDefines = join;
  8891. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8892. }
  8893. return this._effect.isReady();
  8894. };
  8895. ShadowGenerator.prototype.getShadowMap = function () {
  8896. return this._shadowMap;
  8897. };
  8898. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8899. if (this._shadowMap2) {
  8900. return this._shadowMap2;
  8901. }
  8902. return this._shadowMap;
  8903. };
  8904. ShadowGenerator.prototype.getLight = function () {
  8905. return this._light;
  8906. };
  8907. // Methods
  8908. ShadowGenerator.prototype.getTransformMatrix = function () {
  8909. var scene = this._scene;
  8910. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  8911. return this._transformMatrix;
  8912. }
  8913. this._currentRenderID = scene.getRenderId();
  8914. this._currentFaceIndexCache = this._currentFaceIndex;
  8915. var lightPosition = this._light.position;
  8916. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  8917. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  8918. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  8919. }
  8920. if (this._light.computeTransformedPosition()) {
  8921. lightPosition = this._light.transformedPosition;
  8922. }
  8923. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  8924. this._cachedPosition = lightPosition.clone();
  8925. this._cachedDirection = this._lightDirection.clone();
  8926. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8927. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8928. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8929. }
  8930. return this._transformMatrix;
  8931. };
  8932. ShadowGenerator.prototype.getDarkness = function () {
  8933. return this._darkness;
  8934. };
  8935. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8936. if (darkness >= 1.0)
  8937. this._darkness = 1.0;
  8938. else if (darkness <= 0.0)
  8939. this._darkness = 0.0;
  8940. else
  8941. this._darkness = darkness;
  8942. };
  8943. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8944. this._transparencyShadow = hasShadow;
  8945. };
  8946. ShadowGenerator.prototype._packHalf = function (depth) {
  8947. var scale = depth * 255.0;
  8948. var fract = scale - Math.floor(scale);
  8949. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8950. };
  8951. ShadowGenerator.prototype.dispose = function () {
  8952. this._shadowMap.dispose();
  8953. if (this._shadowMap2) {
  8954. this._shadowMap2.dispose();
  8955. }
  8956. if (this._downSamplePostprocess) {
  8957. this._downSamplePostprocess.dispose();
  8958. }
  8959. if (this._boxBlurPostprocess) {
  8960. this._boxBlurPostprocess.dispose();
  8961. }
  8962. };
  8963. ShadowGenerator._FILTER_NONE = 0;
  8964. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8965. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8966. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8967. return ShadowGenerator;
  8968. })();
  8969. BABYLON.ShadowGenerator = ShadowGenerator;
  8970. })(BABYLON || (BABYLON = {}));
  8971. var BABYLON;
  8972. (function (BABYLON) {
  8973. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8974. if (boxMin.x > sphereCenter.x + sphereRadius)
  8975. return false;
  8976. if (sphereCenter.x - sphereRadius > boxMax.x)
  8977. return false;
  8978. if (boxMin.y > sphereCenter.y + sphereRadius)
  8979. return false;
  8980. if (sphereCenter.y - sphereRadius > boxMax.y)
  8981. return false;
  8982. if (boxMin.z > sphereCenter.z + sphereRadius)
  8983. return false;
  8984. if (sphereCenter.z - sphereRadius > boxMax.z)
  8985. return false;
  8986. return true;
  8987. };
  8988. var getLowestRoot = function (a, b, c, maxR) {
  8989. var determinant = b * b - 4.0 * a * c;
  8990. var result = { root: 0, found: false };
  8991. if (determinant < 0)
  8992. return result;
  8993. var sqrtD = Math.sqrt(determinant);
  8994. var r1 = (-b - sqrtD) / (2.0 * a);
  8995. var r2 = (-b + sqrtD) / (2.0 * a);
  8996. if (r1 > r2) {
  8997. var temp = r2;
  8998. r2 = r1;
  8999. r1 = temp;
  9000. }
  9001. if (r1 > 0 && r1 < maxR) {
  9002. result.root = r1;
  9003. result.found = true;
  9004. return result;
  9005. }
  9006. if (r2 > 0 && r2 < maxR) {
  9007. result.root = r2;
  9008. result.found = true;
  9009. return result;
  9010. }
  9011. return result;
  9012. };
  9013. var Collider = (function () {
  9014. function Collider() {
  9015. this.radius = new BABYLON.Vector3(1, 1, 1);
  9016. this.retry = 0;
  9017. this.basePointWorld = BABYLON.Vector3.Zero();
  9018. this.velocityWorld = BABYLON.Vector3.Zero();
  9019. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9020. this._collisionPoint = BABYLON.Vector3.Zero();
  9021. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9022. this._tempVector = BABYLON.Vector3.Zero();
  9023. this._tempVector2 = BABYLON.Vector3.Zero();
  9024. this._tempVector3 = BABYLON.Vector3.Zero();
  9025. this._tempVector4 = BABYLON.Vector3.Zero();
  9026. this._edge = BABYLON.Vector3.Zero();
  9027. this._baseToVertex = BABYLON.Vector3.Zero();
  9028. this._destinationPoint = BABYLON.Vector3.Zero();
  9029. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9030. this._displacementVector = BABYLON.Vector3.Zero();
  9031. }
  9032. // Methods
  9033. Collider.prototype._initialize = function (source, dir, e) {
  9034. this.velocity = dir;
  9035. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9036. this.basePoint = source;
  9037. source.multiplyToRef(this.radius, this.basePointWorld);
  9038. dir.multiplyToRef(this.radius, this.velocityWorld);
  9039. this.velocityWorldLength = this.velocityWorld.length();
  9040. this.epsilon = e;
  9041. this.collisionFound = false;
  9042. };
  9043. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9044. pa.subtractToRef(point, this._tempVector);
  9045. pb.subtractToRef(point, this._tempVector2);
  9046. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9047. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9048. if (d < 0)
  9049. return false;
  9050. pc.subtractToRef(point, this._tempVector3);
  9051. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9052. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9053. if (d < 0)
  9054. return false;
  9055. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9056. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9057. return d >= 0;
  9058. };
  9059. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9060. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9061. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9062. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9063. return false;
  9064. }
  9065. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9066. return false;
  9067. return true;
  9068. };
  9069. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9070. var t0;
  9071. var embeddedInPlane = false;
  9072. //defensive programming, actually not needed.
  9073. if (!trianglePlaneArray) {
  9074. trianglePlaneArray = [];
  9075. }
  9076. if (!trianglePlaneArray[faceIndex]) {
  9077. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9078. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9079. }
  9080. var trianglePlane = trianglePlaneArray[faceIndex];
  9081. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9082. return;
  9083. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9084. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9085. if (normalDotVelocity == 0) {
  9086. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9087. return;
  9088. embeddedInPlane = true;
  9089. t0 = 0;
  9090. }
  9091. else {
  9092. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9093. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9094. if (t0 > t1) {
  9095. var temp = t1;
  9096. t1 = t0;
  9097. t0 = temp;
  9098. }
  9099. if (t0 > 1.0 || t1 < 0.0)
  9100. return;
  9101. if (t0 < 0)
  9102. t0 = 0;
  9103. if (t0 > 1.0)
  9104. t0 = 1.0;
  9105. }
  9106. this._collisionPoint.copyFromFloats(0, 0, 0);
  9107. var found = false;
  9108. var t = 1.0;
  9109. if (!embeddedInPlane) {
  9110. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9111. this.velocity.scaleToRef(t0, this._tempVector);
  9112. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9113. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9114. found = true;
  9115. t = t0;
  9116. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9117. }
  9118. }
  9119. if (!found) {
  9120. var velocitySquaredLength = this.velocity.lengthSquared();
  9121. var a = velocitySquaredLength;
  9122. this.basePoint.subtractToRef(p1, this._tempVector);
  9123. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9124. var c = this._tempVector.lengthSquared() - 1.0;
  9125. var lowestRoot = getLowestRoot(a, b, c, t);
  9126. if (lowestRoot.found) {
  9127. t = lowestRoot.root;
  9128. found = true;
  9129. this._collisionPoint.copyFrom(p1);
  9130. }
  9131. this.basePoint.subtractToRef(p2, this._tempVector);
  9132. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9133. c = this._tempVector.lengthSquared() - 1.0;
  9134. lowestRoot = getLowestRoot(a, b, c, t);
  9135. if (lowestRoot.found) {
  9136. t = lowestRoot.root;
  9137. found = true;
  9138. this._collisionPoint.copyFrom(p2);
  9139. }
  9140. this.basePoint.subtractToRef(p3, this._tempVector);
  9141. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9142. c = this._tempVector.lengthSquared() - 1.0;
  9143. lowestRoot = getLowestRoot(a, b, c, t);
  9144. if (lowestRoot.found) {
  9145. t = lowestRoot.root;
  9146. found = true;
  9147. this._collisionPoint.copyFrom(p3);
  9148. }
  9149. p2.subtractToRef(p1, this._edge);
  9150. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9151. var edgeSquaredLength = this._edge.lengthSquared();
  9152. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9153. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9154. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9155. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9156. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9157. lowestRoot = getLowestRoot(a, b, c, t);
  9158. if (lowestRoot.found) {
  9159. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9160. if (f >= 0.0 && f <= 1.0) {
  9161. t = lowestRoot.root;
  9162. found = true;
  9163. this._edge.scaleInPlace(f);
  9164. p1.addToRef(this._edge, this._collisionPoint);
  9165. }
  9166. }
  9167. p3.subtractToRef(p2, this._edge);
  9168. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9169. edgeSquaredLength = this._edge.lengthSquared();
  9170. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9171. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9172. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9173. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9174. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9175. lowestRoot = getLowestRoot(a, b, c, t);
  9176. if (lowestRoot.found) {
  9177. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9178. if (f >= 0.0 && f <= 1.0) {
  9179. t = lowestRoot.root;
  9180. found = true;
  9181. this._edge.scaleInPlace(f);
  9182. p2.addToRef(this._edge, this._collisionPoint);
  9183. }
  9184. }
  9185. p1.subtractToRef(p3, this._edge);
  9186. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9187. edgeSquaredLength = this._edge.lengthSquared();
  9188. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9189. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9190. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9191. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9192. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9193. lowestRoot = getLowestRoot(a, b, c, t);
  9194. if (lowestRoot.found) {
  9195. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9196. if (f >= 0.0 && f <= 1.0) {
  9197. t = lowestRoot.root;
  9198. found = true;
  9199. this._edge.scaleInPlace(f);
  9200. p3.addToRef(this._edge, this._collisionPoint);
  9201. }
  9202. }
  9203. }
  9204. if (found) {
  9205. var distToCollision = t * this.velocity.length();
  9206. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9207. if (!this.intersectionPoint) {
  9208. this.intersectionPoint = this._collisionPoint.clone();
  9209. }
  9210. else {
  9211. this.intersectionPoint.copyFrom(this._collisionPoint);
  9212. }
  9213. this.nearestDistance = distToCollision;
  9214. this.collisionFound = true;
  9215. }
  9216. }
  9217. };
  9218. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9219. for (var i = indexStart; i < indexEnd; i += 3) {
  9220. var p1 = pts[indices[i] - decal];
  9221. var p2 = pts[indices[i + 1] - decal];
  9222. var p3 = pts[indices[i + 2] - decal];
  9223. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9224. }
  9225. };
  9226. Collider.prototype._getResponse = function (pos, vel) {
  9227. pos.addToRef(vel, this._destinationPoint);
  9228. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9229. this.basePoint.addToRef(vel, pos);
  9230. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9231. this._slidePlaneNormal.normalize();
  9232. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9233. pos.addInPlace(this._displacementVector);
  9234. this.intersectionPoint.addInPlace(this._displacementVector);
  9235. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9236. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9237. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9238. };
  9239. return Collider;
  9240. })();
  9241. BABYLON.Collider = Collider;
  9242. })(BABYLON || (BABYLON = {}));
  9243. var BABYLON;
  9244. (function (BABYLON) {
  9245. //WebWorker code will be inserted to this variable.
  9246. BABYLON.CollisionWorker = "";
  9247. (function (WorkerTaskType) {
  9248. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9249. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9250. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9251. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9252. var WorkerTaskType = BABYLON.WorkerTaskType;
  9253. (function (WorkerReplyType) {
  9254. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9255. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9256. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9257. var WorkerReplyType = BABYLON.WorkerReplyType;
  9258. var CollisionCoordinatorWorker = (function () {
  9259. function CollisionCoordinatorWorker() {
  9260. var _this = this;
  9261. this._scaledPosition = BABYLON.Vector3.Zero();
  9262. this._scaledVelocity = BABYLON.Vector3.Zero();
  9263. this.onMeshUpdated = function (mesh) {
  9264. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9265. };
  9266. this.onGeometryUpdated = function (geometry) {
  9267. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9268. };
  9269. this._afterRender = function () {
  9270. if (!_this._init)
  9271. return;
  9272. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9273. return;
  9274. }
  9275. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9276. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9277. if (_this._runningUpdated > 4) {
  9278. return;
  9279. }
  9280. ++_this._runningUpdated;
  9281. var payload = {
  9282. updatedMeshes: _this._addUpdateMeshesList,
  9283. updatedGeometries: _this._addUpdateGeometriesList,
  9284. removedGeometries: _this._toRemoveGeometryArray,
  9285. removedMeshes: _this._toRemoveMeshesArray
  9286. };
  9287. var message = {
  9288. payload: payload,
  9289. taskType: WorkerTaskType.UPDATE
  9290. };
  9291. var serializable = [];
  9292. for (var id in payload.updatedGeometries) {
  9293. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9294. //prepare transferables
  9295. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9296. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9297. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9298. }
  9299. }
  9300. _this._worker.postMessage(message, serializable);
  9301. _this._addUpdateMeshesList = {};
  9302. _this._addUpdateGeometriesList = {};
  9303. _this._toRemoveGeometryArray = [];
  9304. _this._toRemoveMeshesArray = [];
  9305. };
  9306. this._onMessageFromWorker = function (e) {
  9307. var returnData = e.data;
  9308. if (returnData.error != WorkerReplyType.SUCCESS) {
  9309. //TODO what errors can be returned from the worker?
  9310. BABYLON.Tools.Warn("error returned from worker!");
  9311. return;
  9312. }
  9313. switch (returnData.taskType) {
  9314. case WorkerTaskType.INIT:
  9315. _this._init = true;
  9316. //Update the worked with ALL of the scene's current state
  9317. _this._scene.meshes.forEach(function (mesh) {
  9318. _this.onMeshAdded(mesh);
  9319. });
  9320. _this._scene.getGeometries().forEach(function (geometry) {
  9321. _this.onGeometryAdded(geometry);
  9322. });
  9323. break;
  9324. case WorkerTaskType.UPDATE:
  9325. _this._runningUpdated--;
  9326. break;
  9327. case WorkerTaskType.COLLIDE:
  9328. _this._runningCollisionTask = false;
  9329. var returnPayload = returnData.payload;
  9330. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9331. return;
  9332. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9333. //cleanup
  9334. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9335. break;
  9336. }
  9337. };
  9338. this._collisionsCallbackArray = [];
  9339. this._init = false;
  9340. this._runningUpdated = 0;
  9341. this._runningCollisionTask = false;
  9342. this._addUpdateMeshesList = {};
  9343. this._addUpdateGeometriesList = {};
  9344. this._toRemoveGeometryArray = [];
  9345. this._toRemoveMeshesArray = [];
  9346. }
  9347. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9348. if (!this._init)
  9349. return;
  9350. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9351. return;
  9352. position.divideToRef(collider.radius, this._scaledPosition);
  9353. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9354. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9355. var payload = {
  9356. collider: {
  9357. position: this._scaledPosition.asArray(),
  9358. velocity: this._scaledVelocity.asArray(),
  9359. radius: collider.radius.asArray()
  9360. },
  9361. collisionId: collisionIndex,
  9362. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9363. maximumRetry: maximumRetry
  9364. };
  9365. var message = {
  9366. payload: payload,
  9367. taskType: WorkerTaskType.COLLIDE
  9368. };
  9369. this._worker.postMessage(message);
  9370. };
  9371. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9372. this._scene = scene;
  9373. this._scene.registerAfterRender(this._afterRender);
  9374. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9375. this._worker = new Worker(workerUrl);
  9376. this._worker.onmessage = this._onMessageFromWorker;
  9377. var message = {
  9378. payload: {},
  9379. taskType: WorkerTaskType.INIT
  9380. };
  9381. this._worker.postMessage(message);
  9382. };
  9383. CollisionCoordinatorWorker.prototype.destroy = function () {
  9384. this._scene.unregisterAfterRender(this._afterRender);
  9385. this._worker.terminate();
  9386. };
  9387. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9388. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9389. this.onMeshUpdated(mesh);
  9390. };
  9391. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9392. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9393. };
  9394. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9395. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9396. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9397. this.onGeometryUpdated(geometry);
  9398. };
  9399. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9400. this._toRemoveGeometryArray.push(geometry.id);
  9401. };
  9402. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9403. var submeshes = [];
  9404. if (mesh.subMeshes) {
  9405. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9406. return {
  9407. position: idx,
  9408. verticesStart: sm.verticesStart,
  9409. verticesCount: sm.verticesCount,
  9410. indexStart: sm.indexStart,
  9411. indexCount: sm.indexCount,
  9412. hasMaterial: !!sm.getMaterial(),
  9413. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9414. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9415. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9416. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9417. };
  9418. });
  9419. }
  9420. var geometryId = null;
  9421. if (mesh instanceof BABYLON.Mesh) {
  9422. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9423. }
  9424. else if (mesh instanceof BABYLON.InstancedMesh) {
  9425. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9426. }
  9427. return {
  9428. uniqueId: mesh.uniqueId,
  9429. id: mesh.id,
  9430. name: mesh.name,
  9431. geometryId: geometryId,
  9432. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9433. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9434. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9435. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9436. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9437. subMeshes: submeshes,
  9438. checkCollisions: mesh.checkCollisions
  9439. };
  9440. };
  9441. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9442. return {
  9443. id: geometry.id,
  9444. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9445. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9446. indices: new Int32Array(geometry.getIndices() || []),
  9447. };
  9448. };
  9449. return CollisionCoordinatorWorker;
  9450. })();
  9451. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9452. var CollisionCoordinatorLegacy = (function () {
  9453. function CollisionCoordinatorLegacy() {
  9454. this._scaledPosition = BABYLON.Vector3.Zero();
  9455. this._scaledVelocity = BABYLON.Vector3.Zero();
  9456. this._finalPosition = BABYLON.Vector3.Zero();
  9457. }
  9458. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9459. position.divideToRef(collider.radius, this._scaledPosition);
  9460. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9461. collider.collidedMesh = null;
  9462. collider.retry = 0;
  9463. collider.initialVelocity = this._scaledVelocity;
  9464. collider.initialPosition = this._scaledPosition;
  9465. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9466. this._finalPosition.multiplyInPlace(collider.radius);
  9467. //run the callback
  9468. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9469. };
  9470. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9471. this._scene = scene;
  9472. };
  9473. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9474. //Legacy need no destruction method.
  9475. };
  9476. //No update in legacy mode
  9477. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9478. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9479. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9480. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9481. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9482. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9483. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9484. if (excludedMesh === void 0) { excludedMesh = null; }
  9485. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9486. if (collider.retry >= maximumRetry) {
  9487. finalPosition.copyFrom(position);
  9488. return;
  9489. }
  9490. collider._initialize(position, velocity, closeDistance);
  9491. // Check all meshes
  9492. for (var index = 0; index < this._scene.meshes.length; index++) {
  9493. var mesh = this._scene.meshes[index];
  9494. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9495. mesh._checkCollision(collider);
  9496. }
  9497. }
  9498. if (!collider.collisionFound) {
  9499. position.addToRef(velocity, finalPosition);
  9500. return;
  9501. }
  9502. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9503. collider._getResponse(position, velocity);
  9504. }
  9505. if (velocity.length() <= closeDistance) {
  9506. finalPosition.copyFrom(position);
  9507. return;
  9508. }
  9509. collider.retry++;
  9510. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9511. };
  9512. return CollisionCoordinatorLegacy;
  9513. })();
  9514. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9515. })(BABYLON || (BABYLON = {}));
  9516. var BABYLON;
  9517. (function (BABYLON) {
  9518. var VRCameraMetrics = (function () {
  9519. function VRCameraMetrics() {
  9520. this.compensateDistortion = true;
  9521. }
  9522. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9523. get: function () {
  9524. return this.hResolution / (2 * this.vResolution);
  9525. },
  9526. enumerable: true,
  9527. configurable: true
  9528. });
  9529. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9530. get: function () {
  9531. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9537. get: function () {
  9538. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9539. var h = (4 * meters) / this.hScreenSize;
  9540. return BABYLON.Matrix.Translation(h, 0, 0);
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9546. get: function () {
  9547. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9548. var h = (4 * meters) / this.hScreenSize;
  9549. return BABYLON.Matrix.Translation(-h, 0, 0);
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9555. get: function () {
  9556. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9562. get: function () {
  9563. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. VRCameraMetrics.GetDefault = function () {
  9569. var result = new VRCameraMetrics();
  9570. result.hResolution = 1280;
  9571. result.vResolution = 800;
  9572. result.hScreenSize = 0.149759993;
  9573. result.vScreenSize = 0.0935999975;
  9574. result.vScreenCenter = 0.0467999987,
  9575. result.eyeToScreenDistance = 0.0410000011;
  9576. result.lensSeparationDistance = 0.0635000020;
  9577. result.interpupillaryDistance = 0.0640000030;
  9578. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9579. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9580. result.postProcessScaleFactor = 1.714605507808412;
  9581. result.lensCenterOffset = 0.151976421;
  9582. return result;
  9583. };
  9584. return VRCameraMetrics;
  9585. })();
  9586. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9587. var Camera = (function (_super) {
  9588. __extends(Camera, _super);
  9589. function Camera(name, position, scene) {
  9590. _super.call(this, name, scene);
  9591. this.position = position;
  9592. // Members
  9593. this.upVector = BABYLON.Vector3.Up();
  9594. this.orthoLeft = null;
  9595. this.orthoRight = null;
  9596. this.orthoBottom = null;
  9597. this.orthoTop = null;
  9598. this.fov = 0.8;
  9599. this.minZ = 1.0;
  9600. this.maxZ = 10000.0;
  9601. this.inertia = 0.9;
  9602. this.mode = Camera.PERSPECTIVE_CAMERA;
  9603. this.isIntermediate = false;
  9604. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9605. this.layerMask = 0x0FFFFFFF;
  9606. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9607. // Camera rig members
  9608. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9609. this._rigCameras = new Array();
  9610. // Cache
  9611. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9612. this._projectionMatrix = new BABYLON.Matrix();
  9613. this._postProcesses = new Array();
  9614. this._postProcessesTakenIndices = [];
  9615. this._activeMeshes = new BABYLON.SmartArray(256);
  9616. this._globalPosition = BABYLON.Vector3.Zero();
  9617. scene.addCamera(this);
  9618. if (!scene.activeCamera) {
  9619. scene.activeCamera = this;
  9620. }
  9621. }
  9622. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9623. get: function () {
  9624. return Camera._PERSPECTIVE_CAMERA;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9630. get: function () {
  9631. return Camera._ORTHOGRAPHIC_CAMERA;
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9637. get: function () {
  9638. return Camera._FOVMODE_VERTICAL_FIXED;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9644. get: function () {
  9645. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9651. get: function () {
  9652. return Camera._RIG_MODE_NONE;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9658. get: function () {
  9659. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9665. get: function () {
  9666. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9672. get: function () {
  9673. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9679. get: function () {
  9680. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9686. get: function () {
  9687. return Camera._RIG_MODE_VR;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Camera.prototype, "globalPosition", {
  9693. get: function () {
  9694. return this._globalPosition;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Camera.prototype.getActiveMeshes = function () {
  9700. return this._activeMeshes;
  9701. };
  9702. Camera.prototype.isActiveMesh = function (mesh) {
  9703. return (this._activeMeshes.indexOf(mesh) !== -1);
  9704. };
  9705. //Cache
  9706. Camera.prototype._initCache = function () {
  9707. _super.prototype._initCache.call(this);
  9708. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9709. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9710. this._cache.mode = undefined;
  9711. this._cache.minZ = undefined;
  9712. this._cache.maxZ = undefined;
  9713. this._cache.fov = undefined;
  9714. this._cache.aspectRatio = undefined;
  9715. this._cache.orthoLeft = undefined;
  9716. this._cache.orthoRight = undefined;
  9717. this._cache.orthoBottom = undefined;
  9718. this._cache.orthoTop = undefined;
  9719. this._cache.renderWidth = undefined;
  9720. this._cache.renderHeight = undefined;
  9721. };
  9722. Camera.prototype._updateCache = function (ignoreParentClass) {
  9723. if (!ignoreParentClass) {
  9724. _super.prototype._updateCache.call(this);
  9725. }
  9726. var engine = this.getEngine();
  9727. this._cache.position.copyFrom(this.position);
  9728. this._cache.upVector.copyFrom(this.upVector);
  9729. this._cache.mode = this.mode;
  9730. this._cache.minZ = this.minZ;
  9731. this._cache.maxZ = this.maxZ;
  9732. this._cache.fov = this.fov;
  9733. this._cache.aspectRatio = engine.getAspectRatio(this);
  9734. this._cache.orthoLeft = this.orthoLeft;
  9735. this._cache.orthoRight = this.orthoRight;
  9736. this._cache.orthoBottom = this.orthoBottom;
  9737. this._cache.orthoTop = this.orthoTop;
  9738. this._cache.renderWidth = engine.getRenderWidth();
  9739. this._cache.renderHeight = engine.getRenderHeight();
  9740. };
  9741. Camera.prototype._updateFromScene = function () {
  9742. this.updateCache();
  9743. this._update();
  9744. };
  9745. // Synchronized
  9746. Camera.prototype._isSynchronized = function () {
  9747. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9748. };
  9749. Camera.prototype._isSynchronizedViewMatrix = function () {
  9750. if (!_super.prototype._isSynchronized.call(this))
  9751. return false;
  9752. return this._cache.position.equals(this.position)
  9753. && this._cache.upVector.equals(this.upVector)
  9754. && this.isSynchronizedWithParent();
  9755. };
  9756. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9757. var check = this._cache.mode === this.mode
  9758. && this._cache.minZ === this.minZ
  9759. && this._cache.maxZ === this.maxZ;
  9760. if (!check) {
  9761. return false;
  9762. }
  9763. var engine = this.getEngine();
  9764. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9765. check = this._cache.fov === this.fov
  9766. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9767. }
  9768. else {
  9769. check = this._cache.orthoLeft === this.orthoLeft
  9770. && this._cache.orthoRight === this.orthoRight
  9771. && this._cache.orthoBottom === this.orthoBottom
  9772. && this._cache.orthoTop === this.orthoTop
  9773. && this._cache.renderWidth === engine.getRenderWidth()
  9774. && this._cache.renderHeight === engine.getRenderHeight();
  9775. }
  9776. return check;
  9777. };
  9778. // Controls
  9779. Camera.prototype.attachControl = function (element) {
  9780. };
  9781. Camera.prototype.detachControl = function (element) {
  9782. };
  9783. Camera.prototype._update = function () {
  9784. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9785. this._updateRigCameras();
  9786. }
  9787. this._checkInputs();
  9788. };
  9789. Camera.prototype._checkInputs = function () {
  9790. };
  9791. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9792. if (insertAt === void 0) { insertAt = null; }
  9793. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9794. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9795. return 0;
  9796. }
  9797. if (insertAt == null || insertAt < 0) {
  9798. this._postProcesses.push(postProcess);
  9799. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9800. return this._postProcesses.length - 1;
  9801. }
  9802. var add = 0;
  9803. var i;
  9804. var start;
  9805. if (this._postProcesses[insertAt]) {
  9806. start = this._postProcesses.length - 1;
  9807. for (i = start; i >= insertAt + 1; --i) {
  9808. this._postProcesses[i + 1] = this._postProcesses[i];
  9809. }
  9810. add = 1;
  9811. }
  9812. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9813. if (this._postProcessesTakenIndices[i] < insertAt) {
  9814. continue;
  9815. }
  9816. start = this._postProcessesTakenIndices.length - 1;
  9817. for (var j = start; j >= i; --j) {
  9818. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9819. }
  9820. this._postProcessesTakenIndices[i] = insertAt;
  9821. break;
  9822. }
  9823. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9824. this._postProcessesTakenIndices.push(insertAt);
  9825. }
  9826. var result = insertAt + add;
  9827. this._postProcesses[result] = postProcess;
  9828. return result;
  9829. };
  9830. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9831. if (atIndices === void 0) { atIndices = null; }
  9832. var result = [];
  9833. var i;
  9834. var index;
  9835. if (!atIndices) {
  9836. var length = this._postProcesses.length;
  9837. for (i = 0; i < length; i++) {
  9838. if (this._postProcesses[i] !== postProcess) {
  9839. continue;
  9840. }
  9841. delete this._postProcesses[i];
  9842. index = this._postProcessesTakenIndices.indexOf(i);
  9843. this._postProcessesTakenIndices.splice(index, 1);
  9844. }
  9845. }
  9846. else {
  9847. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9848. for (i = 0; i < atIndices.length; i++) {
  9849. var foundPostProcess = this._postProcesses[atIndices[i]];
  9850. if (foundPostProcess !== postProcess) {
  9851. result.push(i);
  9852. continue;
  9853. }
  9854. delete this._postProcesses[atIndices[i]];
  9855. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9856. this._postProcessesTakenIndices.splice(index, 1);
  9857. }
  9858. }
  9859. return result;
  9860. };
  9861. Camera.prototype.getWorldMatrix = function () {
  9862. if (!this._worldMatrix) {
  9863. this._worldMatrix = BABYLON.Matrix.Identity();
  9864. }
  9865. var viewMatrix = this.getViewMatrix();
  9866. viewMatrix.invertToRef(this._worldMatrix);
  9867. return this._worldMatrix;
  9868. };
  9869. Camera.prototype._getViewMatrix = function () {
  9870. return BABYLON.Matrix.Identity();
  9871. };
  9872. Camera.prototype.getViewMatrix = function (force) {
  9873. this._computedViewMatrix = this._computeViewMatrix(force);
  9874. if (!force && this._isSynchronizedViewMatrix()) {
  9875. return this._computedViewMatrix;
  9876. }
  9877. if (!this.parent || !this.parent.getWorldMatrix) {
  9878. this._globalPosition.copyFrom(this.position);
  9879. }
  9880. else {
  9881. if (!this._worldMatrix) {
  9882. this._worldMatrix = BABYLON.Matrix.Identity();
  9883. }
  9884. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9885. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9886. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9887. this._computedViewMatrix.invert();
  9888. this._markSyncedWithParent();
  9889. }
  9890. this._currentRenderId = this.getScene().getRenderId();
  9891. return this._computedViewMatrix;
  9892. };
  9893. Camera.prototype._computeViewMatrix = function (force) {
  9894. if (!force && this._isSynchronizedViewMatrix()) {
  9895. return this._computedViewMatrix;
  9896. }
  9897. this._computedViewMatrix = this._getViewMatrix();
  9898. this._currentRenderId = this.getScene().getRenderId();
  9899. return this._computedViewMatrix;
  9900. };
  9901. Camera.prototype.getProjectionMatrix = function (force) {
  9902. if (!force && this._isSynchronizedProjectionMatrix()) {
  9903. return this._projectionMatrix;
  9904. }
  9905. var engine = this.getEngine();
  9906. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9907. if (this.minZ <= 0) {
  9908. this.minZ = 0.1;
  9909. }
  9910. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9911. return this._projectionMatrix;
  9912. }
  9913. var halfWidth = engine.getRenderWidth() / 2.0;
  9914. var halfHeight = engine.getRenderHeight() / 2.0;
  9915. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9916. return this._projectionMatrix;
  9917. };
  9918. Camera.prototype.dispose = function () {
  9919. // Animations
  9920. this.getScene().stopAnimation(this);
  9921. // Remove from scene
  9922. this.getScene().removeCamera(this);
  9923. while (this._rigCameras.length > 0) {
  9924. this._rigCameras.pop().dispose();
  9925. }
  9926. // Postprocesses
  9927. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9928. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9929. }
  9930. };
  9931. // ---- Camera rigs section ----
  9932. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9933. while (this._rigCameras.length > 0) {
  9934. this._rigCameras.pop().dispose();
  9935. }
  9936. this.cameraRigMode = mode;
  9937. this._cameraRigParams = {};
  9938. switch (this.cameraRigMode) {
  9939. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9940. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9941. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9942. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9943. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  9944. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  9945. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  9946. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  9947. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9948. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9949. break;
  9950. }
  9951. var postProcesses = new Array();
  9952. switch (this.cameraRigMode) {
  9953. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9954. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  9955. this._rigCameras[0].isIntermediate = true;
  9956. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  9957. postProcesses[1].onApply = function (effect) {
  9958. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  9959. };
  9960. break;
  9961. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9962. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9963. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9964. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  9965. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  9966. var secondCamIndex = 1 - firstCamIndex;
  9967. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  9968. this._rigCameras[firstCamIndex].isIntermediate = true;
  9969. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  9970. break;
  9971. case Camera.RIG_MODE_VR:
  9972. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9973. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9974. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  9975. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  9976. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9977. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  9978. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  9979. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  9980. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  9981. if (metrics.compensateDistortion) {
  9982. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  9983. }
  9984. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  9985. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  9986. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  9987. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  9988. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  9989. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  9990. if (metrics.compensateDistortion) {
  9991. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  9992. }
  9993. break;
  9994. }
  9995. this._update();
  9996. };
  9997. Camera.prototype._getVRProjectionMatrix = function () {
  9998. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  9999. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10000. return this._projectionMatrix;
  10001. };
  10002. Camera.prototype.setCameraRigParameter = function (name, value) {
  10003. this._cameraRigParams[name] = value;
  10004. //provisionnally:
  10005. if (name === "interaxialDistance") {
  10006. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10007. }
  10008. };
  10009. /**
  10010. * May needs to be overridden by children so sub has required properties to be copied
  10011. */
  10012. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10013. return null;
  10014. };
  10015. /**
  10016. * May needs to be overridden by children
  10017. */
  10018. Camera.prototype._updateRigCameras = function () {
  10019. for (var i = 0; i < this._rigCameras.length; i++) {
  10020. this._rigCameras[i].minZ = this.minZ;
  10021. this._rigCameras[i].maxZ = this.maxZ;
  10022. this._rigCameras[i].fov = this.fov;
  10023. }
  10024. // only update viewport when ANAGLYPH
  10025. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10026. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10027. }
  10028. };
  10029. // Statics
  10030. Camera._PERSPECTIVE_CAMERA = 0;
  10031. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10032. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10033. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10034. Camera._RIG_MODE_NONE = 0;
  10035. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10036. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10037. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10038. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10039. Camera._RIG_MODE_VR = 20;
  10040. return Camera;
  10041. })(BABYLON.Node);
  10042. BABYLON.Camera = Camera;
  10043. })(BABYLON || (BABYLON = {}));
  10044. var BABYLON;
  10045. (function (BABYLON) {
  10046. var TargetCamera = (function (_super) {
  10047. __extends(TargetCamera, _super);
  10048. function TargetCamera(name, position, scene) {
  10049. _super.call(this, name, position, scene);
  10050. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10051. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10052. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10053. this.speed = 2.0;
  10054. this.noRotationConstraint = false;
  10055. this.lockedTarget = null;
  10056. this._currentTarget = BABYLON.Vector3.Zero();
  10057. this._viewMatrix = BABYLON.Matrix.Zero();
  10058. this._camMatrix = BABYLON.Matrix.Zero();
  10059. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10060. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10061. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10062. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10063. this._lookAtTemp = BABYLON.Matrix.Zero();
  10064. this._tempMatrix = BABYLON.Matrix.Zero();
  10065. }
  10066. TargetCamera.prototype.getFrontPosition = function (distance) {
  10067. var direction = this.getTarget().subtract(this.position);
  10068. direction.normalize();
  10069. direction.scaleInPlace(distance);
  10070. return this.globalPosition.add(direction);
  10071. };
  10072. TargetCamera.prototype._getLockedTargetPosition = function () {
  10073. if (!this.lockedTarget) {
  10074. return null;
  10075. }
  10076. return this.lockedTarget.position || this.lockedTarget;
  10077. };
  10078. // Cache
  10079. TargetCamera.prototype._initCache = function () {
  10080. _super.prototype._initCache.call(this);
  10081. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10082. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10083. };
  10084. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10085. if (!ignoreParentClass) {
  10086. _super.prototype._updateCache.call(this);
  10087. }
  10088. var lockedTargetPosition = this._getLockedTargetPosition();
  10089. if (!lockedTargetPosition) {
  10090. this._cache.lockedTarget = null;
  10091. }
  10092. else {
  10093. if (!this._cache.lockedTarget) {
  10094. this._cache.lockedTarget = lockedTargetPosition.clone();
  10095. }
  10096. else {
  10097. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10098. }
  10099. }
  10100. this._cache.rotation.copyFrom(this.rotation);
  10101. };
  10102. // Synchronized
  10103. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10104. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10105. return false;
  10106. }
  10107. var lockedTargetPosition = this._getLockedTargetPosition();
  10108. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10109. && this._cache.rotation.equals(this.rotation);
  10110. };
  10111. // Methods
  10112. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10113. var engine = this.getEngine();
  10114. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10115. };
  10116. // Target
  10117. TargetCamera.prototype.setTarget = function (target) {
  10118. this.upVector.normalize();
  10119. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10120. this._camMatrix.invert();
  10121. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10122. var vDir = target.subtract(this.position);
  10123. if (vDir.x >= 0.0) {
  10124. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10125. }
  10126. else {
  10127. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10128. }
  10129. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10130. if (isNaN(this.rotation.x)) {
  10131. this.rotation.x = 0;
  10132. }
  10133. if (isNaN(this.rotation.y)) {
  10134. this.rotation.y = 0;
  10135. }
  10136. if (isNaN(this.rotation.z)) {
  10137. this.rotation.z = 0;
  10138. }
  10139. };
  10140. TargetCamera.prototype.getTarget = function () {
  10141. return this._currentTarget;
  10142. };
  10143. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10144. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10145. };
  10146. TargetCamera.prototype._updatePosition = function () {
  10147. this.position.addInPlace(this.cameraDirection);
  10148. };
  10149. TargetCamera.prototype._checkInputs = function () {
  10150. var needToMove = this._decideIfNeedsToMove();
  10151. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10152. // Move
  10153. if (needToMove) {
  10154. this._updatePosition();
  10155. }
  10156. // Rotate
  10157. if (needToRotate) {
  10158. this.rotation.x += this.cameraRotation.x;
  10159. this.rotation.y += this.cameraRotation.y;
  10160. if (!this.noRotationConstraint) {
  10161. var limit = (Math.PI / 2) * 0.95;
  10162. if (this.rotation.x > limit)
  10163. this.rotation.x = limit;
  10164. if (this.rotation.x < -limit)
  10165. this.rotation.x = -limit;
  10166. }
  10167. }
  10168. // Inertia
  10169. if (needToMove) {
  10170. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10171. this.cameraDirection.x = 0;
  10172. }
  10173. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10174. this.cameraDirection.y = 0;
  10175. }
  10176. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10177. this.cameraDirection.z = 0;
  10178. }
  10179. this.cameraDirection.scaleInPlace(this.inertia);
  10180. }
  10181. if (needToRotate) {
  10182. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10183. this.cameraRotation.x = 0;
  10184. }
  10185. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10186. this.cameraRotation.y = 0;
  10187. }
  10188. this.cameraRotation.scaleInPlace(this.inertia);
  10189. }
  10190. _super.prototype._checkInputs.call(this);
  10191. };
  10192. TargetCamera.prototype._getViewMatrix = function () {
  10193. if (!this.lockedTarget) {
  10194. // Compute
  10195. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10196. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10197. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10198. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10199. this._lookAtTemp.invert();
  10200. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10201. }
  10202. else {
  10203. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10204. }
  10205. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10206. // Computing target and final matrix
  10207. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10208. }
  10209. else {
  10210. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10211. }
  10212. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10213. return this._viewMatrix;
  10214. };
  10215. TargetCamera.prototype._getVRViewMatrix = function () {
  10216. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10217. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10218. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10219. // Computing target and final matrix
  10220. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10221. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10222. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10223. return this._viewMatrix;
  10224. };
  10225. /**
  10226. * @override
  10227. * Override Camera.createRigCamera
  10228. */
  10229. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10230. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10231. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10232. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10233. rigCamera._cameraRigParams = {};
  10234. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10235. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10236. }
  10237. return rigCamera;
  10238. }
  10239. return null;
  10240. };
  10241. /**
  10242. * @override
  10243. * Override Camera._updateRigCameras
  10244. */
  10245. TargetCamera.prototype._updateRigCameras = function () {
  10246. switch (this.cameraRigMode) {
  10247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10249. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10251. case BABYLON.Camera.RIG_MODE_VR:
  10252. var camLeft = this._rigCameras[0];
  10253. var camRight = this._rigCameras[1];
  10254. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10255. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10256. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10257. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10258. camLeft.position.copyFrom(this.position);
  10259. camRight.position.copyFrom(this.position);
  10260. }
  10261. else {
  10262. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10263. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10264. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10265. camLeft.setTarget(this.getTarget());
  10266. camRight.setTarget(this.getTarget());
  10267. }
  10268. break;
  10269. }
  10270. _super.prototype._updateRigCameras.call(this);
  10271. };
  10272. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10273. if (!this._rigCamTransformMatrix) {
  10274. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10275. }
  10276. var target = this.getTarget();
  10277. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10278. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10279. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10280. };
  10281. return TargetCamera;
  10282. })(BABYLON.Camera);
  10283. BABYLON.TargetCamera = TargetCamera;
  10284. })(BABYLON || (BABYLON = {}));
  10285. var BABYLON;
  10286. (function (BABYLON) {
  10287. var FreeCamera = (function (_super) {
  10288. __extends(FreeCamera, _super);
  10289. function FreeCamera(name, position, scene) {
  10290. var _this = this;
  10291. _super.call(this, name, position, scene);
  10292. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10293. this.keysUp = [38];
  10294. this.keysDown = [40];
  10295. this.keysLeft = [37];
  10296. this.keysRight = [39];
  10297. this.checkCollisions = false;
  10298. this.applyGravity = false;
  10299. this.angularSensibility = 2000.0;
  10300. this._keys = [];
  10301. this._collider = new BABYLON.Collider();
  10302. this._needMoveForGravity = false;
  10303. this._oldPosition = BABYLON.Vector3.Zero();
  10304. this._diffPosition = BABYLON.Vector3.Zero();
  10305. this._newPosition = BABYLON.Vector3.Zero();
  10306. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10307. if (collidedMesh === void 0) { collidedMesh = null; }
  10308. //TODO move this to the collision coordinator!
  10309. if (_this.getScene().workerCollisions)
  10310. newPosition.multiplyInPlace(_this._collider.radius);
  10311. var updatePosition = function (newPos) {
  10312. _this._newPosition.copyFrom(newPos);
  10313. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10314. var oldPosition = _this.position.clone();
  10315. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10316. _this.position.addInPlace(_this._diffPosition);
  10317. if (_this.onCollide && collidedMesh) {
  10318. _this.onCollide(collidedMesh);
  10319. }
  10320. }
  10321. };
  10322. updatePosition(newPosition);
  10323. };
  10324. }
  10325. // Controls
  10326. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10327. var _this = this;
  10328. var previousPosition;
  10329. var engine = this.getEngine();
  10330. if (this._attachedElement) {
  10331. return;
  10332. }
  10333. this._attachedElement = element;
  10334. if (this._onMouseDown === undefined) {
  10335. this._onMouseDown = function (evt) {
  10336. previousPosition = {
  10337. x: evt.clientX,
  10338. y: evt.clientY
  10339. };
  10340. if (!noPreventDefault) {
  10341. evt.preventDefault();
  10342. }
  10343. };
  10344. this._onMouseUp = function (evt) {
  10345. previousPosition = null;
  10346. if (!noPreventDefault) {
  10347. evt.preventDefault();
  10348. }
  10349. };
  10350. this._onMouseOut = function (evt) {
  10351. previousPosition = null;
  10352. _this._keys = [];
  10353. if (!noPreventDefault) {
  10354. evt.preventDefault();
  10355. }
  10356. };
  10357. this._onMouseMove = function (evt) {
  10358. if (!previousPosition && !engine.isPointerLock) {
  10359. return;
  10360. }
  10361. var offsetX;
  10362. var offsetY;
  10363. if (!engine.isPointerLock) {
  10364. offsetX = evt.clientX - previousPosition.x;
  10365. offsetY = evt.clientY - previousPosition.y;
  10366. }
  10367. else {
  10368. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10369. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10370. }
  10371. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10372. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10373. previousPosition = {
  10374. x: evt.clientX,
  10375. y: evt.clientY
  10376. };
  10377. if (!noPreventDefault) {
  10378. evt.preventDefault();
  10379. }
  10380. };
  10381. this._onKeyDown = function (evt) {
  10382. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10383. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10384. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10385. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10386. var index = _this._keys.indexOf(evt.keyCode);
  10387. if (index === -1) {
  10388. _this._keys.push(evt.keyCode);
  10389. }
  10390. if (!noPreventDefault) {
  10391. evt.preventDefault();
  10392. }
  10393. }
  10394. };
  10395. this._onKeyUp = function (evt) {
  10396. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10397. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10398. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10399. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10400. var index = _this._keys.indexOf(evt.keyCode);
  10401. if (index >= 0) {
  10402. _this._keys.splice(index, 1);
  10403. }
  10404. if (!noPreventDefault) {
  10405. evt.preventDefault();
  10406. }
  10407. }
  10408. };
  10409. this._onLostFocus = function () {
  10410. _this._keys = [];
  10411. };
  10412. this._reset = function () {
  10413. _this._keys = [];
  10414. previousPosition = null;
  10415. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10416. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10417. };
  10418. }
  10419. element.addEventListener("mousedown", this._onMouseDown, false);
  10420. element.addEventListener("mouseup", this._onMouseUp, false);
  10421. element.addEventListener("mouseout", this._onMouseOut, false);
  10422. element.addEventListener("mousemove", this._onMouseMove, false);
  10423. BABYLON.Tools.RegisterTopRootEvents([
  10424. { name: "keydown", handler: this._onKeyDown },
  10425. { name: "keyup", handler: this._onKeyUp },
  10426. { name: "blur", handler: this._onLostFocus }
  10427. ]);
  10428. };
  10429. FreeCamera.prototype.detachControl = function (element) {
  10430. if (this._attachedElement != element) {
  10431. return;
  10432. }
  10433. element.removeEventListener("mousedown", this._onMouseDown);
  10434. element.removeEventListener("mouseup", this._onMouseUp);
  10435. element.removeEventListener("mouseout", this._onMouseOut);
  10436. element.removeEventListener("mousemove", this._onMouseMove);
  10437. BABYLON.Tools.UnregisterTopRootEvents([
  10438. { name: "keydown", handler: this._onKeyDown },
  10439. { name: "keyup", handler: this._onKeyUp },
  10440. { name: "blur", handler: this._onLostFocus }
  10441. ]);
  10442. this._attachedElement = null;
  10443. if (this._reset) {
  10444. this._reset();
  10445. }
  10446. };
  10447. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10448. var globalPosition;
  10449. if (this.parent) {
  10450. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10451. }
  10452. else {
  10453. globalPosition = this.position;
  10454. }
  10455. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10456. this._collider.radius = this.ellipsoid;
  10457. //no need for clone, as long as gravity is not on.
  10458. var actualVelocity = velocity;
  10459. //add gravity to the velocity to prevent the dual-collision checking
  10460. if (this.applyGravity) {
  10461. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10462. actualVelocity = velocity.add(this.getScene().gravity);
  10463. }
  10464. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10465. };
  10466. FreeCamera.prototype._checkInputs = function () {
  10467. if (!this._localDirection) {
  10468. this._localDirection = BABYLON.Vector3.Zero();
  10469. this._transformedDirection = BABYLON.Vector3.Zero();
  10470. }
  10471. // Keyboard
  10472. for (var index = 0; index < this._keys.length; index++) {
  10473. var keyCode = this._keys[index];
  10474. var speed = this._computeLocalCameraSpeed();
  10475. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10476. this._localDirection.copyFromFloats(-speed, 0, 0);
  10477. }
  10478. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10479. this._localDirection.copyFromFloats(0, 0, speed);
  10480. }
  10481. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10482. this._localDirection.copyFromFloats(speed, 0, 0);
  10483. }
  10484. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10485. this._localDirection.copyFromFloats(0, 0, -speed);
  10486. }
  10487. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10488. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10489. this.cameraDirection.addInPlace(this._transformedDirection);
  10490. }
  10491. _super.prototype._checkInputs.call(this);
  10492. };
  10493. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10494. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10495. };
  10496. FreeCamera.prototype._updatePosition = function () {
  10497. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10498. this._collideWithWorld(this.cameraDirection);
  10499. }
  10500. else {
  10501. this.position.addInPlace(this.cameraDirection);
  10502. }
  10503. };
  10504. return FreeCamera;
  10505. })(BABYLON.TargetCamera);
  10506. BABYLON.FreeCamera = FreeCamera;
  10507. })(BABYLON || (BABYLON = {}));
  10508. var BABYLON;
  10509. (function (BABYLON) {
  10510. var FollowCamera = (function (_super) {
  10511. __extends(FollowCamera, _super);
  10512. function FollowCamera(name, position, scene) {
  10513. _super.call(this, name, position, scene);
  10514. this.radius = 12;
  10515. this.rotationOffset = 0;
  10516. this.heightOffset = 4;
  10517. this.cameraAcceleration = 0.05;
  10518. this.maxCameraSpeed = 20;
  10519. }
  10520. FollowCamera.prototype.getRadians = function (degrees) {
  10521. return degrees * Math.PI / 180;
  10522. };
  10523. FollowCamera.prototype.follow = function (cameraTarget) {
  10524. if (!cameraTarget)
  10525. return;
  10526. var yRotation;
  10527. if (cameraTarget.rotationQuaternion) {
  10528. var rotMatrix = new BABYLON.Matrix();
  10529. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10530. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10531. }
  10532. else {
  10533. yRotation = cameraTarget.rotation.y;
  10534. }
  10535. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10536. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10537. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10538. var dx = targetX - this.position.x;
  10539. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10540. var dz = (targetZ) - this.position.z;
  10541. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10542. var vy = dy * this.cameraAcceleration;
  10543. var vz = dz * this.cameraAcceleration * 2;
  10544. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10545. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10546. }
  10547. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10548. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10549. }
  10550. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10551. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10552. }
  10553. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10554. this.setTarget(cameraTarget.position);
  10555. };
  10556. FollowCamera.prototype._checkInputs = function () {
  10557. _super.prototype._checkInputs.call(this);
  10558. this.follow(this.target);
  10559. };
  10560. return FollowCamera;
  10561. })(BABYLON.TargetCamera);
  10562. BABYLON.FollowCamera = FollowCamera;
  10563. var ArcFollowCamera = (function (_super) {
  10564. __extends(ArcFollowCamera, _super);
  10565. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10566. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10567. this.alpha = alpha;
  10568. this.beta = beta;
  10569. this.radius = radius;
  10570. this.target = target;
  10571. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10572. this.follow();
  10573. }
  10574. ArcFollowCamera.prototype.follow = function () {
  10575. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10576. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10577. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10578. this.position = this.target.position.add(this._cartesianCoordinates);
  10579. this.setTarget(this.target.position);
  10580. };
  10581. ArcFollowCamera.prototype._checkInputs = function () {
  10582. _super.prototype._checkInputs.call(this);
  10583. this.follow();
  10584. };
  10585. return ArcFollowCamera;
  10586. })(BABYLON.TargetCamera);
  10587. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10588. })(BABYLON || (BABYLON = {}));
  10589. var BABYLON;
  10590. (function (BABYLON) {
  10591. // We're mainly based on the logic defined into the FreeCamera code
  10592. var TouchCamera = (function (_super) {
  10593. __extends(TouchCamera, _super);
  10594. function TouchCamera(name, position, scene) {
  10595. _super.call(this, name, position, scene);
  10596. this._offsetX = null;
  10597. this._offsetY = null;
  10598. this._pointerCount = 0;
  10599. this._pointerPressed = [];
  10600. this.angularSensibility = 200000.0;
  10601. this.moveSensibility = 500.0;
  10602. }
  10603. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10604. var _this = this;
  10605. var previousPosition;
  10606. if (this._attachedCanvas) {
  10607. return;
  10608. }
  10609. this._attachedCanvas = canvas;
  10610. if (this._onPointerDown === undefined) {
  10611. this._onPointerDown = function (evt) {
  10612. if (!noPreventDefault) {
  10613. evt.preventDefault();
  10614. }
  10615. _this._pointerPressed.push(evt.pointerId);
  10616. if (_this._pointerPressed.length !== 1) {
  10617. return;
  10618. }
  10619. previousPosition = {
  10620. x: evt.clientX,
  10621. y: evt.clientY
  10622. };
  10623. };
  10624. this._onPointerUp = function (evt) {
  10625. if (!noPreventDefault) {
  10626. evt.preventDefault();
  10627. }
  10628. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10629. if (index === -1) {
  10630. return;
  10631. }
  10632. _this._pointerPressed.splice(index, 1);
  10633. if (index != 0) {
  10634. return;
  10635. }
  10636. previousPosition = null;
  10637. _this._offsetX = null;
  10638. _this._offsetY = null;
  10639. };
  10640. this._onPointerMove = function (evt) {
  10641. if (!noPreventDefault) {
  10642. evt.preventDefault();
  10643. }
  10644. if (!previousPosition) {
  10645. return;
  10646. }
  10647. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10648. if (index != 0) {
  10649. return;
  10650. }
  10651. _this._offsetX = evt.clientX - previousPosition.x;
  10652. _this._offsetY = -(evt.clientY - previousPosition.y);
  10653. };
  10654. this._onLostFocus = function () {
  10655. _this._offsetX = null;
  10656. _this._offsetY = null;
  10657. };
  10658. }
  10659. canvas.addEventListener("pointerdown", this._onPointerDown);
  10660. canvas.addEventListener("pointerup", this._onPointerUp);
  10661. canvas.addEventListener("pointerout", this._onPointerUp);
  10662. canvas.addEventListener("pointermove", this._onPointerMove);
  10663. BABYLON.Tools.RegisterTopRootEvents([
  10664. { name: "blur", handler: this._onLostFocus }
  10665. ]);
  10666. };
  10667. TouchCamera.prototype.detachControl = function (canvas) {
  10668. if (this._attachedCanvas != canvas) {
  10669. return;
  10670. }
  10671. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10672. canvas.removeEventListener("pointerup", this._onPointerUp);
  10673. canvas.removeEventListener("pointerout", this._onPointerUp);
  10674. canvas.removeEventListener("pointermove", this._onPointerMove);
  10675. BABYLON.Tools.UnregisterTopRootEvents([
  10676. { name: "blur", handler: this._onLostFocus }
  10677. ]);
  10678. this._attachedCanvas = null;
  10679. };
  10680. TouchCamera.prototype._checkInputs = function () {
  10681. if (this._offsetX) {
  10682. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10683. if (this._pointerPressed.length > 1) {
  10684. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10685. }
  10686. else {
  10687. var speed = this._computeLocalCameraSpeed();
  10688. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10689. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10690. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10691. }
  10692. }
  10693. _super.prototype._checkInputs.call(this);
  10694. };
  10695. return TouchCamera;
  10696. })(BABYLON.FreeCamera);
  10697. BABYLON.TouchCamera = TouchCamera;
  10698. })(BABYLON || (BABYLON = {}));
  10699. var BABYLON;
  10700. (function (BABYLON) {
  10701. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10702. var ArcRotateCamera = (function (_super) {
  10703. __extends(ArcRotateCamera, _super);
  10704. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10705. var _this = this;
  10706. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10707. this.alpha = alpha;
  10708. this.beta = beta;
  10709. this.radius = radius;
  10710. this.target = target;
  10711. this.inertialAlphaOffset = 0;
  10712. this.inertialBetaOffset = 0;
  10713. this.inertialRadiusOffset = 0;
  10714. this.lowerAlphaLimit = null;
  10715. this.upperAlphaLimit = null;
  10716. this.lowerBetaLimit = 0.01;
  10717. this.upperBetaLimit = Math.PI;
  10718. this.lowerRadiusLimit = null;
  10719. this.upperRadiusLimit = null;
  10720. this.angularSensibilityX = 1000.0;
  10721. this.angularSensibilityY = 1000.0;
  10722. this.wheelPrecision = 3.0;
  10723. this.pinchPrecision = 2.0;
  10724. this.panningSensibility = 50.0;
  10725. this.inertialPanningX = 0;
  10726. this.inertialPanningY = 0;
  10727. this.keysUp = [38];
  10728. this.keysDown = [40];
  10729. this.keysLeft = [37];
  10730. this.keysRight = [39];
  10731. this.zoomOnFactor = 1;
  10732. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10733. this.pinchInwards = true;
  10734. this.allowUpsideDown = true;
  10735. this._keys = [];
  10736. this._viewMatrix = new BABYLON.Matrix();
  10737. this._isRightClick = false;
  10738. this._isCtrlPushed = false;
  10739. this.checkCollisions = false;
  10740. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10741. this._collider = new BABYLON.Collider();
  10742. this._previousPosition = BABYLON.Vector3.Zero();
  10743. this._collisionVelocity = BABYLON.Vector3.Zero();
  10744. this._newPosition = BABYLON.Vector3.Zero();
  10745. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10746. if (collidedMesh === void 0) { collidedMesh = null; }
  10747. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10748. newPosition.multiplyInPlace(_this._collider.radius);
  10749. }
  10750. if (!collidedMesh) {
  10751. _this._previousPosition.copyFrom(_this.position);
  10752. }
  10753. else {
  10754. _this.setPosition(_this.position);
  10755. if (_this.onCollide) {
  10756. _this.onCollide(collidedMesh);
  10757. }
  10758. }
  10759. // Recompute because of constraints
  10760. var cosa = Math.cos(_this.alpha);
  10761. var sina = Math.sin(_this.alpha);
  10762. var cosb = Math.cos(_this.beta);
  10763. var sinb = Math.sin(_this.beta);
  10764. var target = _this._getTargetPosition();
  10765. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10766. _this.position.copyFrom(_this._newPosition);
  10767. var up = _this.upVector;
  10768. if (_this.allowUpsideDown && _this.beta < 0) {
  10769. var up = up.clone();
  10770. up = up.negate();
  10771. }
  10772. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10773. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10774. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10775. _this._collisionTriggered = false;
  10776. };
  10777. if (!this.target) {
  10778. this.target = BABYLON.Vector3.Zero();
  10779. }
  10780. this.getViewMatrix();
  10781. }
  10782. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10783. //deprecated angularSensibility support
  10784. get: function () {
  10785. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10786. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10787. },
  10788. //deprecated angularSensibility support
  10789. set: function (value) {
  10790. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10791. this.angularSensibilityX = value;
  10792. this.angularSensibilityY = value;
  10793. },
  10794. enumerable: true,
  10795. configurable: true
  10796. });
  10797. ArcRotateCamera.prototype._getTargetPosition = function () {
  10798. return this.target.position || this.target;
  10799. };
  10800. // Cache
  10801. ArcRotateCamera.prototype._initCache = function () {
  10802. _super.prototype._initCache.call(this);
  10803. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10804. this._cache.alpha = undefined;
  10805. this._cache.beta = undefined;
  10806. this._cache.radius = undefined;
  10807. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10808. };
  10809. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10810. if (!ignoreParentClass) {
  10811. _super.prototype._updateCache.call(this);
  10812. }
  10813. this._cache.target.copyFrom(this._getTargetPosition());
  10814. this._cache.alpha = this.alpha;
  10815. this._cache.beta = this.beta;
  10816. this._cache.radius = this.radius;
  10817. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10818. };
  10819. // Synchronized
  10820. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10821. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10822. return false;
  10823. return this._cache.target.equals(this._getTargetPosition())
  10824. && this._cache.alpha === this.alpha
  10825. && this._cache.beta === this.beta
  10826. && this._cache.radius === this.radius
  10827. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10828. };
  10829. // Methods
  10830. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10831. var _this = this;
  10832. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10833. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10834. var previousPinchDistance = 0;
  10835. var pointers = new BABYLON.SmartCollection();
  10836. if (this._attachedElement) {
  10837. return;
  10838. }
  10839. this._attachedElement = element;
  10840. var engine = this.getEngine();
  10841. if (this._onPointerDown === undefined) {
  10842. this._onPointerDown = function (evt) {
  10843. // Manage panning with right click
  10844. _this._isRightClick = evt.button === 2 ? true : false;
  10845. // manage pointers
  10846. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10847. cacheSoloPointer = pointers.item(evt.pointerId);
  10848. if (!noPreventDefault) {
  10849. evt.preventDefault();
  10850. }
  10851. };
  10852. this._onPointerUp = function (evt) {
  10853. cacheSoloPointer = null;
  10854. previousPinchDistance = 0;
  10855. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10856. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10857. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10858. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10859. pointers.empty();
  10860. if (!noPreventDefault) {
  10861. evt.preventDefault();
  10862. }
  10863. };
  10864. this._onContextMenu = function (evt) {
  10865. evt.preventDefault();
  10866. };
  10867. this._onPointerMove = function (evt) {
  10868. if (!noPreventDefault) {
  10869. evt.preventDefault();
  10870. }
  10871. switch (pointers.count) {
  10872. case 1:
  10873. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10874. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10875. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10876. }
  10877. else {
  10878. var offsetX = evt.clientX - cacheSoloPointer.x;
  10879. var offsetY = evt.clientY - cacheSoloPointer.y;
  10880. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10881. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10882. }
  10883. cacheSoloPointer.x = evt.clientX;
  10884. cacheSoloPointer.y = evt.clientY;
  10885. break;
  10886. case 2:
  10887. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10888. pointers.item(evt.pointerId).x = evt.clientX;
  10889. pointers.item(evt.pointerId).y = evt.clientY;
  10890. var direction = _this.pinchInwards ? 1 : -1;
  10891. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10892. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10893. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10894. if (previousPinchDistance === 0) {
  10895. previousPinchDistance = pinchSquaredDistance;
  10896. return;
  10897. }
  10898. if (pinchSquaredDistance !== previousPinchDistance) {
  10899. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10900. previousPinchDistance = pinchSquaredDistance;
  10901. }
  10902. break;
  10903. default:
  10904. if (pointers.item(evt.pointerId)) {
  10905. pointers.item(evt.pointerId).x = evt.clientX;
  10906. pointers.item(evt.pointerId).y = evt.clientY;
  10907. }
  10908. }
  10909. };
  10910. this._onMouseMove = function (evt) {
  10911. if (!engine.isPointerLock) {
  10912. return;
  10913. }
  10914. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10915. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10916. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10917. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10918. if (!noPreventDefault) {
  10919. evt.preventDefault();
  10920. }
  10921. };
  10922. this._wheel = function (event) {
  10923. var delta = 0;
  10924. if (event.wheelDelta) {
  10925. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10926. }
  10927. else if (event.detail) {
  10928. delta = -event.detail / _this.wheelPrecision;
  10929. }
  10930. if (delta)
  10931. _this.inertialRadiusOffset += delta;
  10932. if (event.preventDefault) {
  10933. if (!noPreventDefault) {
  10934. event.preventDefault();
  10935. }
  10936. }
  10937. };
  10938. this._onKeyDown = function (evt) {
  10939. _this._isCtrlPushed = evt.ctrlKey;
  10940. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10941. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10942. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10943. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10944. var index = _this._keys.indexOf(evt.keyCode);
  10945. if (index === -1) {
  10946. _this._keys.push(evt.keyCode);
  10947. }
  10948. if (evt.preventDefault) {
  10949. if (!noPreventDefault) {
  10950. evt.preventDefault();
  10951. }
  10952. }
  10953. }
  10954. };
  10955. this._onKeyUp = function (evt) {
  10956. _this._isCtrlPushed = evt.ctrlKey;
  10957. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10958. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10959. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10960. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10961. var index = _this._keys.indexOf(evt.keyCode);
  10962. if (index >= 0) {
  10963. _this._keys.splice(index, 1);
  10964. }
  10965. if (evt.preventDefault) {
  10966. if (!noPreventDefault) {
  10967. evt.preventDefault();
  10968. }
  10969. }
  10970. }
  10971. };
  10972. this._onLostFocus = function () {
  10973. _this._keys = [];
  10974. pointers.empty();
  10975. previousPinchDistance = 0;
  10976. cacheSoloPointer = null;
  10977. };
  10978. this._onGestureStart = function (e) {
  10979. if (window.MSGesture === undefined) {
  10980. return;
  10981. }
  10982. if (!_this._MSGestureHandler) {
  10983. _this._MSGestureHandler = new MSGesture();
  10984. _this._MSGestureHandler.target = element;
  10985. }
  10986. _this._MSGestureHandler.addPointer(e.pointerId);
  10987. };
  10988. this._onGesture = function (e) {
  10989. _this.radius *= e.scale;
  10990. if (e.preventDefault) {
  10991. if (!noPreventDefault) {
  10992. e.stopPropagation();
  10993. e.preventDefault();
  10994. }
  10995. }
  10996. };
  10997. this._reset = function () {
  10998. _this._keys = [];
  10999. _this.inertialAlphaOffset = 0;
  11000. _this.inertialBetaOffset = 0;
  11001. _this.inertialRadiusOffset = 0;
  11002. pointers.empty();
  11003. previousPinchDistance = 0;
  11004. cacheSoloPointer = null;
  11005. };
  11006. }
  11007. if (!useCtrlForPanning) {
  11008. element.addEventListener("contextmenu", this._onContextMenu, false);
  11009. }
  11010. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11011. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11012. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11013. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11014. element.addEventListener("mousemove", this._onMouseMove, false);
  11015. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11016. element.addEventListener("MSGestureChange", this._onGesture, false);
  11017. element.addEventListener('mousewheel', this._wheel, false);
  11018. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11019. BABYLON.Tools.RegisterTopRootEvents([
  11020. { name: "keydown", handler: this._onKeyDown },
  11021. { name: "keyup", handler: this._onKeyUp },
  11022. { name: "blur", handler: this._onLostFocus }
  11023. ]);
  11024. };
  11025. ArcRotateCamera.prototype.detachControl = function (element) {
  11026. if (this._attachedElement !== element) {
  11027. return;
  11028. }
  11029. element.removeEventListener("contextmenu", this._onContextMenu);
  11030. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11031. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11032. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11033. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11034. element.removeEventListener("mousemove", this._onMouseMove);
  11035. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11036. element.removeEventListener("MSGestureChange", this._onGesture);
  11037. element.removeEventListener('mousewheel', this._wheel);
  11038. element.removeEventListener('DOMMouseScroll', this._wheel);
  11039. BABYLON.Tools.UnregisterTopRootEvents([
  11040. { name: "keydown", handler: this._onKeyDown },
  11041. { name: "keyup", handler: this._onKeyUp },
  11042. { name: "blur", handler: this._onLostFocus }
  11043. ]);
  11044. this._MSGestureHandler = null;
  11045. this._attachedElement = null;
  11046. if (this._reset) {
  11047. this._reset();
  11048. }
  11049. };
  11050. ArcRotateCamera.prototype._checkInputs = function () {
  11051. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11052. if (this._collisionTriggered) {
  11053. return;
  11054. }
  11055. // Keyboard
  11056. for (var index = 0; index < this._keys.length; index++) {
  11057. var keyCode = this._keys[index];
  11058. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11059. this.inertialAlphaOffset -= 0.01;
  11060. }
  11061. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11062. this.inertialBetaOffset -= 0.01;
  11063. }
  11064. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11065. this.inertialAlphaOffset += 0.01;
  11066. }
  11067. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11068. this.inertialBetaOffset += 0.01;
  11069. }
  11070. }
  11071. // Inertia
  11072. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11073. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11074. this.beta += this.inertialBetaOffset;
  11075. this.radius -= this.inertialRadiusOffset;
  11076. this.inertialAlphaOffset *= this.inertia;
  11077. this.inertialBetaOffset *= this.inertia;
  11078. this.inertialRadiusOffset *= this.inertia;
  11079. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11080. this.inertialAlphaOffset = 0;
  11081. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11082. this.inertialBetaOffset = 0;
  11083. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11084. this.inertialRadiusOffset = 0;
  11085. }
  11086. // Panning inertia
  11087. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11088. if (!this._localDirection) {
  11089. this._localDirection = BABYLON.Vector3.Zero();
  11090. this._transformedDirection = BABYLON.Vector3.Zero();
  11091. }
  11092. this.inertialPanningX *= this.inertia;
  11093. this.inertialPanningY *= this.inertia;
  11094. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11095. this.inertialPanningX = 0;
  11096. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11097. this.inertialPanningY = 0;
  11098. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11099. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11100. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11101. this.target.addInPlace(this._transformedDirection);
  11102. }
  11103. // Limits
  11104. this._checkLimits();
  11105. _super.prototype._checkInputs.call(this);
  11106. };
  11107. ArcRotateCamera.prototype._checkLimits = function () {
  11108. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11109. if (this.allowUpsideDown && this.beta > Math.PI) {
  11110. this.beta = this.beta - (2 * Math.PI);
  11111. }
  11112. }
  11113. else {
  11114. if (this.beta < this.lowerBetaLimit) {
  11115. this.beta = this.lowerBetaLimit;
  11116. }
  11117. }
  11118. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11119. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11120. this.beta = this.beta + (2 * Math.PI);
  11121. }
  11122. }
  11123. else {
  11124. if (this.beta > this.upperBetaLimit) {
  11125. this.beta = this.upperBetaLimit;
  11126. }
  11127. }
  11128. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11129. this.alpha = this.lowerAlphaLimit;
  11130. }
  11131. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11132. this.alpha = this.upperAlphaLimit;
  11133. }
  11134. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11135. this.radius = this.lowerRadiusLimit;
  11136. }
  11137. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11138. this.radius = this.upperRadiusLimit;
  11139. }
  11140. };
  11141. ArcRotateCamera.prototype.setPosition = function (position) {
  11142. if (this.position.equals(position)) {
  11143. return;
  11144. }
  11145. var radiusv3 = position.subtract(this._getTargetPosition());
  11146. this.radius = radiusv3.length();
  11147. // Alpha
  11148. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11149. if (radiusv3.z < 0) {
  11150. this.alpha = 2 * Math.PI - this.alpha;
  11151. }
  11152. // Beta
  11153. this.beta = Math.acos(radiusv3.y / this.radius);
  11154. this._checkLimits();
  11155. };
  11156. ArcRotateCamera.prototype.setTarget = function (target) {
  11157. this.target = target;
  11158. };
  11159. ArcRotateCamera.prototype._getViewMatrix = function () {
  11160. // Compute
  11161. var cosa = Math.cos(this.alpha);
  11162. var sina = Math.sin(this.alpha);
  11163. var cosb = Math.cos(this.beta);
  11164. var sinb = Math.sin(this.beta);
  11165. var target = this._getTargetPosition();
  11166. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11167. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11168. this._collider.radius = this.collisionRadius;
  11169. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11170. this._collisionTriggered = true;
  11171. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11172. }
  11173. else {
  11174. this.position.copyFrom(this._newPosition);
  11175. var up = this.upVector;
  11176. if (this.allowUpsideDown && this.beta < 0) {
  11177. var up = up.clone();
  11178. up = up.negate();
  11179. }
  11180. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11181. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11182. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11183. }
  11184. return this._viewMatrix;
  11185. };
  11186. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11187. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11188. meshes = meshes || this.getScene().meshes;
  11189. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11190. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11191. this.radius = distance * this.zoomOnFactor;
  11192. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11193. };
  11194. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11195. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11196. var meshesOrMinMaxVector;
  11197. var distance;
  11198. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11199. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11200. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11201. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11202. }
  11203. else {
  11204. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11205. distance = meshesOrMinMaxVectorAndDistance.distance;
  11206. }
  11207. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11208. if (!doNotUpdateMaxZ) {
  11209. this.maxZ = distance * 2;
  11210. }
  11211. };
  11212. /**
  11213. * @override
  11214. * Override Camera.createRigCamera
  11215. */
  11216. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11217. switch (this.cameraRigMode) {
  11218. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11219. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11220. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11222. case BABYLON.Camera.RIG_MODE_VR:
  11223. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11224. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11225. }
  11226. };
  11227. /**
  11228. * @override
  11229. * Override Camera._updateRigCameras
  11230. */
  11231. ArcRotateCamera.prototype._updateRigCameras = function () {
  11232. switch (this.cameraRigMode) {
  11233. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11234. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11235. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11236. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11237. case BABYLON.Camera.RIG_MODE_VR:
  11238. var camLeft = this._rigCameras[0];
  11239. var camRight = this._rigCameras[1];
  11240. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11241. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11242. camLeft.beta = camRight.beta = this.beta;
  11243. camLeft.radius = camRight.radius = this.radius;
  11244. break;
  11245. }
  11246. _super.prototype._updateRigCameras.call(this);
  11247. };
  11248. return ArcRotateCamera;
  11249. })(BABYLON.TargetCamera);
  11250. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11251. })(BABYLON || (BABYLON = {}));
  11252. var BABYLON;
  11253. (function (BABYLON) {
  11254. var RenderingManager = (function () {
  11255. function RenderingManager(scene) {
  11256. this._renderingGroups = new Array();
  11257. this._scene = scene;
  11258. }
  11259. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11260. if (this._scene._activeParticleSystems.length === 0) {
  11261. return;
  11262. }
  11263. // Particles
  11264. var activeCamera = this._scene.activeCamera;
  11265. var beforeParticlesDate = BABYLON.Tools.Now;
  11266. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11267. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11268. if (particleSystem.renderingGroupId !== index) {
  11269. continue;
  11270. }
  11271. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11272. continue;
  11273. }
  11274. this._clearDepthBuffer();
  11275. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11276. this._scene._activeParticles += particleSystem.render();
  11277. }
  11278. }
  11279. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11280. };
  11281. RenderingManager.prototype._renderSprites = function (index) {
  11282. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11283. return;
  11284. }
  11285. // Sprites
  11286. var activeCamera = this._scene.activeCamera;
  11287. var beforeSpritessDate = BABYLON.Tools.Now;
  11288. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11289. var spriteManager = this._scene.spriteManagers[id];
  11290. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11291. this._clearDepthBuffer();
  11292. spriteManager.render();
  11293. }
  11294. }
  11295. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11296. };
  11297. RenderingManager.prototype._clearDepthBuffer = function () {
  11298. if (this._depthBufferAlreadyCleaned) {
  11299. return;
  11300. }
  11301. this._scene.getEngine().clear(0, false, true);
  11302. this._depthBufferAlreadyCleaned = true;
  11303. };
  11304. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11305. if (this._currentRenderSprites) {
  11306. this._renderSprites(this._currentIndex);
  11307. }
  11308. if (this._currentRenderParticles) {
  11309. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11310. }
  11311. };
  11312. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11313. this._currentActiveMeshes = activeMeshes;
  11314. this._currentRenderParticles = renderParticles;
  11315. this._currentRenderSprites = renderSprites;
  11316. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11317. this._depthBufferAlreadyCleaned = false;
  11318. var renderingGroup = this._renderingGroups[index];
  11319. var needToStepBack = false;
  11320. this._currentIndex = index;
  11321. if (renderingGroup) {
  11322. this._clearDepthBuffer();
  11323. if (!renderingGroup.onBeforeTransparentRendering) {
  11324. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11325. }
  11326. if (!renderingGroup.render(customRenderFunction)) {
  11327. this._renderingGroups.splice(index, 1);
  11328. needToStepBack = true;
  11329. this._renderSpritesAndParticles();
  11330. }
  11331. }
  11332. else {
  11333. this._renderSpritesAndParticles();
  11334. }
  11335. if (needToStepBack) {
  11336. index--;
  11337. }
  11338. }
  11339. };
  11340. RenderingManager.prototype.reset = function () {
  11341. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11342. if (renderingGroup) {
  11343. renderingGroup.prepare();
  11344. }
  11345. });
  11346. };
  11347. RenderingManager.prototype.dispatch = function (subMesh) {
  11348. var mesh = subMesh.getMesh();
  11349. var renderingGroupId = mesh.renderingGroupId || 0;
  11350. if (!this._renderingGroups[renderingGroupId]) {
  11351. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11352. }
  11353. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11354. };
  11355. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11356. return RenderingManager;
  11357. })();
  11358. BABYLON.RenderingManager = RenderingManager;
  11359. })(BABYLON || (BABYLON = {}));
  11360. var BABYLON;
  11361. (function (BABYLON) {
  11362. var RenderingGroup = (function () {
  11363. function RenderingGroup(index, scene) {
  11364. this.index = index;
  11365. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11366. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11367. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11368. this._scene = scene;
  11369. }
  11370. RenderingGroup.prototype.render = function (customRenderFunction) {
  11371. if (customRenderFunction) {
  11372. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11373. return true;
  11374. }
  11375. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11376. if (this.onBeforeTransparentRendering) {
  11377. this.onBeforeTransparentRendering();
  11378. }
  11379. return false;
  11380. }
  11381. var engine = this._scene.getEngine();
  11382. // Opaque
  11383. var subIndex;
  11384. var submesh;
  11385. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11386. submesh = this._opaqueSubMeshes.data[subIndex];
  11387. submesh.render(false);
  11388. }
  11389. // Alpha test
  11390. engine.setAlphaTesting(true);
  11391. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11392. submesh = this._alphaTestSubMeshes.data[subIndex];
  11393. submesh.render(false);
  11394. }
  11395. engine.setAlphaTesting(false);
  11396. if (this.onBeforeTransparentRendering) {
  11397. this.onBeforeTransparentRendering();
  11398. }
  11399. // Transparent
  11400. if (this._transparentSubMeshes.length) {
  11401. // Sorting
  11402. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11403. submesh = this._transparentSubMeshes.data[subIndex];
  11404. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11405. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11406. }
  11407. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11408. sortedArray.sort(function (a, b) {
  11409. // Alpha index first
  11410. if (a._alphaIndex > b._alphaIndex) {
  11411. return 1;
  11412. }
  11413. if (a._alphaIndex < b._alphaIndex) {
  11414. return -1;
  11415. }
  11416. // Then distance to camera
  11417. if (a._distanceToCamera < b._distanceToCamera) {
  11418. return 1;
  11419. }
  11420. if (a._distanceToCamera > b._distanceToCamera) {
  11421. return -1;
  11422. }
  11423. return 0;
  11424. });
  11425. // Rendering
  11426. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11427. submesh = sortedArray[subIndex];
  11428. submesh.render(true);
  11429. }
  11430. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11431. }
  11432. return true;
  11433. };
  11434. RenderingGroup.prototype.prepare = function () {
  11435. this._opaqueSubMeshes.reset();
  11436. this._transparentSubMeshes.reset();
  11437. this._alphaTestSubMeshes.reset();
  11438. };
  11439. RenderingGroup.prototype.dispatch = function (subMesh) {
  11440. var material = subMesh.getMaterial();
  11441. var mesh = subMesh.getMesh();
  11442. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11443. this._transparentSubMeshes.push(subMesh);
  11444. }
  11445. else if (material.needAlphaTesting()) {
  11446. this._alphaTestSubMeshes.push(subMesh);
  11447. }
  11448. else {
  11449. this._opaqueSubMeshes.push(subMesh); // Opaque
  11450. }
  11451. };
  11452. return RenderingGroup;
  11453. })();
  11454. BABYLON.RenderingGroup = RenderingGroup;
  11455. })(BABYLON || (BABYLON = {}));
  11456. var BABYLON;
  11457. (function (BABYLON) {
  11458. /**
  11459. * Represents a scene to be rendered by the engine.
  11460. * @see http://doc.babylonjs.com/page.php?p=21911
  11461. */
  11462. var Scene = (function () {
  11463. /**
  11464. * @constructor
  11465. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11466. */
  11467. function Scene(engine) {
  11468. // Members
  11469. this.autoClear = true;
  11470. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11471. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11472. this.forceWireframe = false;
  11473. this.forcePointsCloud = false;
  11474. this.forceShowBoundingBoxes = false;
  11475. this.animationsEnabled = true;
  11476. this.constantlyUpdateMeshUnderPointer = false;
  11477. 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
  11478. // Fog
  11479. /**
  11480. * is fog enabled on this scene.
  11481. * @type {boolean}
  11482. */
  11483. this.fogEnabled = true;
  11484. this.fogMode = Scene.FOGMODE_NONE;
  11485. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11486. this.fogDensity = 0.1;
  11487. this.fogStart = 0;
  11488. this.fogEnd = 1000.0;
  11489. // Lights
  11490. /**
  11491. * is shadow enabled on this scene.
  11492. * @type {boolean}
  11493. */
  11494. this.shadowsEnabled = true;
  11495. /**
  11496. * is light enabled on this scene.
  11497. * @type {boolean}
  11498. */
  11499. this.lightsEnabled = true;
  11500. /**
  11501. * All of the lights added to this scene.
  11502. * @see BABYLON.Light
  11503. * @type {BABYLON.Light[]}
  11504. */
  11505. this.lights = new Array();
  11506. // Cameras
  11507. /**
  11508. * All of the cameras added to this scene.
  11509. * @see BABYLON.Camera
  11510. * @type {BABYLON.Camera[]}
  11511. */
  11512. this.cameras = new Array();
  11513. this.activeCameras = new Array();
  11514. // Meshes
  11515. /**
  11516. * All of the (abstract) meshes added to this scene.
  11517. * @see BABYLON.AbstractMesh
  11518. * @type {BABYLON.AbstractMesh[]}
  11519. */
  11520. this.meshes = new Array();
  11521. // Geometries
  11522. this._geometries = new Array();
  11523. this.materials = new Array();
  11524. this.multiMaterials = new Array();
  11525. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11526. // Textures
  11527. this.texturesEnabled = true;
  11528. this.textures = new Array();
  11529. // Particles
  11530. this.particlesEnabled = true;
  11531. this.particleSystems = new Array();
  11532. // Sprites
  11533. this.spritesEnabled = true;
  11534. this.spriteManagers = new Array();
  11535. // Layers
  11536. this.layers = new Array();
  11537. // Skeletons
  11538. this.skeletonsEnabled = true;
  11539. this.skeletons = new Array();
  11540. // Lens flares
  11541. this.lensFlaresEnabled = true;
  11542. this.lensFlareSystems = new Array();
  11543. // Collisions
  11544. this.collisionsEnabled = true;
  11545. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11546. // Postprocesses
  11547. this.postProcessesEnabled = true;
  11548. // Customs render targets
  11549. this.renderTargetsEnabled = true;
  11550. this.dumpNextRenderTargets = false;
  11551. this.customRenderTargets = new Array();
  11552. // Imported meshes
  11553. this.importedMeshesFiles = new Array();
  11554. // Probes
  11555. this.probesEnabled = true;
  11556. this.reflectionProbes = new Array();
  11557. this._actionManagers = new Array();
  11558. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11559. // Procedural textures
  11560. this.proceduralTexturesEnabled = true;
  11561. this._proceduralTextures = new Array();
  11562. this.soundTracks = new Array();
  11563. this._audioEnabled = true;
  11564. this._headphone = false;
  11565. this._totalVertices = 0;
  11566. this._activeIndices = 0;
  11567. this._activeParticles = 0;
  11568. this._lastFrameDuration = 0;
  11569. this._evaluateActiveMeshesDuration = 0;
  11570. this._renderTargetsDuration = 0;
  11571. this._particlesDuration = 0;
  11572. this._renderDuration = 0;
  11573. this._spritesDuration = 0;
  11574. this._animationRatio = 0;
  11575. this._renderId = 0;
  11576. this._executeWhenReadyTimeoutId = -1;
  11577. this._toBeDisposed = new BABYLON.SmartArray(256);
  11578. this._onReadyCallbacks = new Array();
  11579. this._pendingData = []; //ANY
  11580. this._onBeforeRenderCallbacks = new Array();
  11581. this._onAfterRenderCallbacks = new Array();
  11582. this._activeMeshes = new BABYLON.SmartArray(256);
  11583. this._processedMaterials = new BABYLON.SmartArray(256);
  11584. this._renderTargets = new BABYLON.SmartArray(256);
  11585. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11586. this._activeSkeletons = new BABYLON.SmartArray(32);
  11587. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11588. this._activeBones = 0;
  11589. this._activeAnimatables = new Array();
  11590. this._transformMatrix = BABYLON.Matrix.Zero();
  11591. this._edgesRenderers = new BABYLON.SmartArray(16);
  11592. this._uniqueIdCounter = 0;
  11593. this._engine = engine;
  11594. engine.scenes.push(this);
  11595. this._renderingManager = new BABYLON.RenderingManager(this);
  11596. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11597. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11598. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11599. if (BABYLON.OutlineRenderer) {
  11600. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11601. }
  11602. this.attachControl();
  11603. this._debugLayer = new BABYLON.DebugLayer(this);
  11604. if (BABYLON.SoundTrack) {
  11605. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11606. }
  11607. //simplification queue
  11608. if (BABYLON.SimplificationQueue) {
  11609. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11610. }
  11611. //collision coordinator initialization. For now legacy per default.
  11612. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11613. }
  11614. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11615. get: function () {
  11616. return Scene._FOGMODE_NONE;
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11622. get: function () {
  11623. return Scene._FOGMODE_EXP;
  11624. },
  11625. enumerable: true,
  11626. configurable: true
  11627. });
  11628. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11629. get: function () {
  11630. return Scene._FOGMODE_EXP2;
  11631. },
  11632. enumerable: true,
  11633. configurable: true
  11634. });
  11635. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11636. get: function () {
  11637. return Scene._FOGMODE_LINEAR;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Scene.prototype, "debugLayer", {
  11643. // Properties
  11644. get: function () {
  11645. return this._debugLayer;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11651. get: function () {
  11652. return this._workerCollisions;
  11653. },
  11654. set: function (enabled) {
  11655. enabled = (enabled && !!Worker);
  11656. this._workerCollisions = enabled;
  11657. if (this.collisionCoordinator) {
  11658. this.collisionCoordinator.destroy();
  11659. }
  11660. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11661. this.collisionCoordinator.init(this);
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11667. get: function () {
  11668. return this._selectionOctree;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11674. /**
  11675. * The mesh that is currently under the pointer.
  11676. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11677. */
  11678. get: function () {
  11679. return this._meshUnderPointer;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Scene.prototype, "pointerX", {
  11685. /**
  11686. * Current on-screen X position of the pointer
  11687. * @return {number} X position of the pointer
  11688. */
  11689. get: function () {
  11690. return this._pointerX;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Scene.prototype, "pointerY", {
  11696. /**
  11697. * Current on-screen Y position of the pointer
  11698. * @return {number} Y position of the pointer
  11699. */
  11700. get: function () {
  11701. return this._pointerY;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Scene.prototype.getCachedMaterial = function () {
  11707. return this._cachedMaterial;
  11708. };
  11709. Scene.prototype.getBoundingBoxRenderer = function () {
  11710. return this._boundingBoxRenderer;
  11711. };
  11712. Scene.prototype.getOutlineRenderer = function () {
  11713. return this._outlineRenderer;
  11714. };
  11715. Scene.prototype.getEngine = function () {
  11716. return this._engine;
  11717. };
  11718. Scene.prototype.getTotalVertices = function () {
  11719. return this._totalVertices;
  11720. };
  11721. Scene.prototype.getActiveIndices = function () {
  11722. return this._activeIndices;
  11723. };
  11724. Scene.prototype.getActiveParticles = function () {
  11725. return this._activeParticles;
  11726. };
  11727. Scene.prototype.getActiveBones = function () {
  11728. return this._activeBones;
  11729. };
  11730. // Stats
  11731. Scene.prototype.getLastFrameDuration = function () {
  11732. return this._lastFrameDuration;
  11733. };
  11734. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11735. return this._evaluateActiveMeshesDuration;
  11736. };
  11737. Scene.prototype.getActiveMeshes = function () {
  11738. return this._activeMeshes;
  11739. };
  11740. Scene.prototype.getRenderTargetsDuration = function () {
  11741. return this._renderTargetsDuration;
  11742. };
  11743. Scene.prototype.getRenderDuration = function () {
  11744. return this._renderDuration;
  11745. };
  11746. Scene.prototype.getParticlesDuration = function () {
  11747. return this._particlesDuration;
  11748. };
  11749. Scene.prototype.getSpritesDuration = function () {
  11750. return this._spritesDuration;
  11751. };
  11752. Scene.prototype.getAnimationRatio = function () {
  11753. return this._animationRatio;
  11754. };
  11755. Scene.prototype.getRenderId = function () {
  11756. return this._renderId;
  11757. };
  11758. Scene.prototype.incrementRenderId = function () {
  11759. this._renderId++;
  11760. };
  11761. Scene.prototype._updatePointerPosition = function (evt) {
  11762. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11763. this._pointerX = evt.clientX - canvasRect.left;
  11764. this._pointerY = evt.clientY - canvasRect.top;
  11765. if (this.cameraToUseForPointers) {
  11766. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11767. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11768. }
  11769. };
  11770. // Pointers handling
  11771. Scene.prototype.attachControl = function () {
  11772. var _this = this;
  11773. var spritePredicate = function (sprite) {
  11774. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11775. };
  11776. this._onPointerMove = function (evt) {
  11777. var canvas = _this._engine.getRenderingCanvas();
  11778. _this._updatePointerPosition(evt);
  11779. // Meshes
  11780. 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);
  11781. if (pickResult.hit && pickResult.pickedMesh) {
  11782. _this._meshUnderPointer = pickResult.pickedMesh;
  11783. _this.setPointerOverMesh(pickResult.pickedMesh);
  11784. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11785. canvas.style.cursor = "pointer";
  11786. }
  11787. else {
  11788. canvas.style.cursor = "";
  11789. }
  11790. }
  11791. else {
  11792. // Sprites
  11793. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11794. if (pickResult.hit && pickResult.pickedSprite) {
  11795. canvas.style.cursor = "pointer";
  11796. return;
  11797. }
  11798. // Restore pointer
  11799. _this.setPointerOverMesh(null);
  11800. canvas.style.cursor = "";
  11801. _this._meshUnderPointer = null;
  11802. }
  11803. };
  11804. this._onPointerDown = function (evt) {
  11805. _this._updatePointerPosition(evt);
  11806. var predicate = null;
  11807. // Meshes
  11808. if (!_this.onPointerDown) {
  11809. predicate = function (mesh) {
  11810. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11811. };
  11812. }
  11813. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11814. if (pickResult.hit && pickResult.pickedMesh) {
  11815. if (pickResult.pickedMesh.actionManager) {
  11816. switch (evt.button) {
  11817. case 0:
  11818. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11819. break;
  11820. case 1:
  11821. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11822. break;
  11823. case 2:
  11824. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11825. break;
  11826. }
  11827. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11828. }
  11829. }
  11830. if (_this.onPointerDown) {
  11831. _this.onPointerDown(evt, pickResult);
  11832. }
  11833. // Sprites
  11834. if (_this.spriteManagers.length > 0) {
  11835. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11836. if (pickResult.hit && pickResult.pickedSprite) {
  11837. if (pickResult.pickedSprite.actionManager) {
  11838. switch (evt.button) {
  11839. case 0:
  11840. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11841. break;
  11842. case 1:
  11843. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11844. break;
  11845. case 2:
  11846. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11847. break;
  11848. }
  11849. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11850. }
  11851. }
  11852. }
  11853. };
  11854. this._onPointerUp = function (evt) {
  11855. var predicate = null;
  11856. _this._updatePointerPosition(evt);
  11857. if (!_this.onPointerUp) {
  11858. predicate = function (mesh) {
  11859. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11860. };
  11861. }
  11862. // Meshes
  11863. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11864. if (pickResult.hit && pickResult.pickedMesh) {
  11865. if (pickResult.pickedMesh.actionManager) {
  11866. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11867. }
  11868. }
  11869. if (_this.onPointerUp) {
  11870. _this.onPointerUp(evt, pickResult);
  11871. }
  11872. // Sprites
  11873. if (_this.spriteManagers.length > 0) {
  11874. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11875. if (pickResult.hit && pickResult.pickedSprite) {
  11876. if (pickResult.pickedSprite.actionManager) {
  11877. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11878. }
  11879. }
  11880. }
  11881. };
  11882. this._onKeyDown = function (evt) {
  11883. if (_this.actionManager) {
  11884. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11885. }
  11886. };
  11887. this._onKeyUp = function (evt) {
  11888. if (_this.actionManager) {
  11889. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11890. }
  11891. };
  11892. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11893. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11894. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11895. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11896. // Wheel
  11897. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11898. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11899. BABYLON.Tools.RegisterTopRootEvents([
  11900. { name: "keydown", handler: this._onKeyDown },
  11901. { name: "keyup", handler: this._onKeyUp }
  11902. ]);
  11903. };
  11904. Scene.prototype.detachControl = function () {
  11905. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11906. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11907. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11908. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11909. // Wheel
  11910. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  11911. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  11912. BABYLON.Tools.UnregisterTopRootEvents([
  11913. { name: "keydown", handler: this._onKeyDown },
  11914. { name: "keyup", handler: this._onKeyUp }
  11915. ]);
  11916. };
  11917. // Ready
  11918. Scene.prototype.isReady = function () {
  11919. if (this._pendingData.length > 0) {
  11920. return false;
  11921. }
  11922. var index;
  11923. for (index = 0; index < this._geometries.length; index++) {
  11924. var geometry = this._geometries[index];
  11925. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11926. return false;
  11927. }
  11928. }
  11929. for (index = 0; index < this.meshes.length; index++) {
  11930. var mesh = this.meshes[index];
  11931. if (!mesh.isReady()) {
  11932. return false;
  11933. }
  11934. var mat = mesh.material;
  11935. if (mat) {
  11936. if (!mat.isReady(mesh)) {
  11937. return false;
  11938. }
  11939. }
  11940. }
  11941. return true;
  11942. };
  11943. Scene.prototype.resetCachedMaterial = function () {
  11944. this._cachedMaterial = null;
  11945. };
  11946. Scene.prototype.registerBeforeRender = function (func) {
  11947. this._onBeforeRenderCallbacks.push(func);
  11948. };
  11949. Scene.prototype.unregisterBeforeRender = function (func) {
  11950. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11951. if (index > -1) {
  11952. this._onBeforeRenderCallbacks.splice(index, 1);
  11953. }
  11954. };
  11955. Scene.prototype.registerAfterRender = function (func) {
  11956. this._onAfterRenderCallbacks.push(func);
  11957. };
  11958. Scene.prototype.unregisterAfterRender = function (func) {
  11959. var index = this._onAfterRenderCallbacks.indexOf(func);
  11960. if (index > -1) {
  11961. this._onAfterRenderCallbacks.splice(index, 1);
  11962. }
  11963. };
  11964. Scene.prototype._addPendingData = function (data) {
  11965. this._pendingData.push(data);
  11966. };
  11967. Scene.prototype._removePendingData = function (data) {
  11968. var index = this._pendingData.indexOf(data);
  11969. if (index !== -1) {
  11970. this._pendingData.splice(index, 1);
  11971. }
  11972. };
  11973. Scene.prototype.getWaitingItemsCount = function () {
  11974. return this._pendingData.length;
  11975. };
  11976. /**
  11977. * Registers a function to be executed when the scene is ready.
  11978. * @param {Function} func - the function to be executed.
  11979. */
  11980. Scene.prototype.executeWhenReady = function (func) {
  11981. var _this = this;
  11982. this._onReadyCallbacks.push(func);
  11983. if (this._executeWhenReadyTimeoutId !== -1) {
  11984. return;
  11985. }
  11986. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11987. _this._checkIsReady();
  11988. }, 150);
  11989. };
  11990. Scene.prototype._checkIsReady = function () {
  11991. var _this = this;
  11992. if (this.isReady()) {
  11993. this._onReadyCallbacks.forEach(function (func) {
  11994. func();
  11995. });
  11996. this._onReadyCallbacks = [];
  11997. this._executeWhenReadyTimeoutId = -1;
  11998. return;
  11999. }
  12000. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12001. _this._checkIsReady();
  12002. }, 150);
  12003. };
  12004. // Animations
  12005. /**
  12006. * Will start the animation sequence of a given target
  12007. * @param target - the target
  12008. * @param {number} from - from which frame should animation start
  12009. * @param {number} to - till which frame should animation run.
  12010. * @param {boolean} [loop] - should the animation loop
  12011. * @param {number} [speedRatio] - the speed in which to run the animation
  12012. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12013. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12014. * @return {BABYLON.Animatable} the animatable object created for this animation
  12015. * @see BABYLON.Animatable
  12016. * @see http://doc.babylonjs.com/page.php?p=22081
  12017. */
  12018. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12019. if (speedRatio === void 0) { speedRatio = 1.0; }
  12020. this.stopAnimation(target);
  12021. if (!animatable) {
  12022. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12023. }
  12024. // Local animations
  12025. if (target.animations) {
  12026. animatable.appendAnimations(target, target.animations);
  12027. }
  12028. // Children animations
  12029. if (target.getAnimatables) {
  12030. var animatables = target.getAnimatables();
  12031. for (var index = 0; index < animatables.length; index++) {
  12032. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12033. }
  12034. }
  12035. return animatable;
  12036. };
  12037. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12038. if (speedRatio === undefined) {
  12039. speedRatio = 1.0;
  12040. }
  12041. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12042. return animatable;
  12043. };
  12044. Scene.prototype.getAnimatableByTarget = function (target) {
  12045. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12046. if (this._activeAnimatables[index].target === target) {
  12047. return this._activeAnimatables[index];
  12048. }
  12049. }
  12050. return null;
  12051. };
  12052. /**
  12053. * Will stop the animation of the given target
  12054. * @param target - the target
  12055. * @see beginAnimation
  12056. */
  12057. Scene.prototype.stopAnimation = function (target) {
  12058. var animatable = this.getAnimatableByTarget(target);
  12059. if (animatable) {
  12060. animatable.stop();
  12061. }
  12062. };
  12063. Scene.prototype._animate = function () {
  12064. if (!this.animationsEnabled) {
  12065. return;
  12066. }
  12067. if (!this._animationStartDate) {
  12068. this._animationStartDate = BABYLON.Tools.Now;
  12069. }
  12070. // Getting time
  12071. var now = BABYLON.Tools.Now;
  12072. var delay = now - this._animationStartDate;
  12073. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12074. this._activeAnimatables[index]._animate(delay);
  12075. }
  12076. };
  12077. // Matrix
  12078. Scene.prototype.getViewMatrix = function () {
  12079. return this._viewMatrix;
  12080. };
  12081. Scene.prototype.getProjectionMatrix = function () {
  12082. return this._projectionMatrix;
  12083. };
  12084. Scene.prototype.getTransformMatrix = function () {
  12085. return this._transformMatrix;
  12086. };
  12087. Scene.prototype.setTransformMatrix = function (view, projection) {
  12088. this._viewMatrix = view;
  12089. this._projectionMatrix = projection;
  12090. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12091. };
  12092. // Methods
  12093. Scene.prototype.addMesh = function (newMesh) {
  12094. newMesh.uniqueId = this._uniqueIdCounter++;
  12095. var position = this.meshes.push(newMesh);
  12096. //notify the collision coordinator
  12097. this.collisionCoordinator.onMeshAdded(newMesh);
  12098. if (this.onNewMeshAdded) {
  12099. this.onNewMeshAdded(newMesh, position, this);
  12100. }
  12101. };
  12102. Scene.prototype.removeMesh = function (toRemove) {
  12103. var index = this.meshes.indexOf(toRemove);
  12104. if (index !== -1) {
  12105. // Remove from the scene if mesh found
  12106. this.meshes.splice(index, 1);
  12107. }
  12108. //notify the collision coordinator
  12109. this.collisionCoordinator.onMeshRemoved(toRemove);
  12110. if (this.onMeshRemoved) {
  12111. this.onMeshRemoved(toRemove);
  12112. }
  12113. return index;
  12114. };
  12115. Scene.prototype.removeSkeleton = function (toRemove) {
  12116. var index = this.skeletons.indexOf(toRemove);
  12117. if (index !== -1) {
  12118. // Remove from the scene if mesh found
  12119. this.skeletons.splice(index, 1);
  12120. }
  12121. return index;
  12122. };
  12123. Scene.prototype.removeLight = function (toRemove) {
  12124. var index = this.lights.indexOf(toRemove);
  12125. if (index !== -1) {
  12126. // Remove from the scene if mesh found
  12127. this.lights.splice(index, 1);
  12128. }
  12129. if (this.onLightRemoved) {
  12130. this.onLightRemoved(toRemove);
  12131. }
  12132. return index;
  12133. };
  12134. Scene.prototype.removeCamera = function (toRemove) {
  12135. var index = this.cameras.indexOf(toRemove);
  12136. if (index !== -1) {
  12137. // Remove from the scene if mesh found
  12138. this.cameras.splice(index, 1);
  12139. }
  12140. // Remove from activeCameras
  12141. var index2 = this.activeCameras.indexOf(toRemove);
  12142. if (index2 !== -1) {
  12143. // Remove from the scene if mesh found
  12144. this.activeCameras.splice(index2, 1);
  12145. }
  12146. // Reset the activeCamera
  12147. if (this.activeCamera === toRemove) {
  12148. if (this.cameras.length > 0) {
  12149. this.activeCamera = this.cameras[0];
  12150. }
  12151. else {
  12152. this.activeCamera = null;
  12153. }
  12154. }
  12155. if (this.onCameraRemoved) {
  12156. this.onCameraRemoved(toRemove);
  12157. }
  12158. return index;
  12159. };
  12160. Scene.prototype.addLight = function (newLight) {
  12161. newLight.uniqueId = this._uniqueIdCounter++;
  12162. var position = this.lights.push(newLight);
  12163. if (this.onNewLightAdded) {
  12164. this.onNewLightAdded(newLight, position, this);
  12165. }
  12166. };
  12167. Scene.prototype.addCamera = function (newCamera) {
  12168. newCamera.uniqueId = this._uniqueIdCounter++;
  12169. var position = this.cameras.push(newCamera);
  12170. if (this.onNewCameraAdded) {
  12171. this.onNewCameraAdded(newCamera, position, this);
  12172. }
  12173. };
  12174. /**
  12175. * sets the active camera of the scene using its ID
  12176. * @param {string} id - the camera's ID
  12177. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12178. * @see activeCamera
  12179. */
  12180. Scene.prototype.setActiveCameraByID = function (id) {
  12181. var camera = this.getCameraByID(id);
  12182. if (camera) {
  12183. this.activeCamera = camera;
  12184. return camera;
  12185. }
  12186. return null;
  12187. };
  12188. /**
  12189. * sets the active camera of the scene using its name
  12190. * @param {string} name - the camera's name
  12191. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12192. * @see activeCamera
  12193. */
  12194. Scene.prototype.setActiveCameraByName = function (name) {
  12195. var camera = this.getCameraByName(name);
  12196. if (camera) {
  12197. this.activeCamera = camera;
  12198. return camera;
  12199. }
  12200. return null;
  12201. };
  12202. /**
  12203. * get a material using its id
  12204. * @param {string} the material's ID
  12205. * @return {BABYLON.Material|null} the material or null if none found.
  12206. */
  12207. Scene.prototype.getMaterialByID = function (id) {
  12208. for (var index = 0; index < this.materials.length; index++) {
  12209. if (this.materials[index].id === id) {
  12210. return this.materials[index];
  12211. }
  12212. }
  12213. return null;
  12214. };
  12215. /**
  12216. * get a material using its name
  12217. * @param {string} the material's name
  12218. * @return {BABYLON.Material|null} the material or null if none found.
  12219. */
  12220. Scene.prototype.getMaterialByName = function (name) {
  12221. for (var index = 0; index < this.materials.length; index++) {
  12222. if (this.materials[index].name === name) {
  12223. return this.materials[index];
  12224. }
  12225. }
  12226. return null;
  12227. };
  12228. Scene.prototype.getLensFlareSystemByName = function (name) {
  12229. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12230. if (this.lensFlareSystems[index].name === name) {
  12231. return this.lensFlareSystems[index];
  12232. }
  12233. }
  12234. return null;
  12235. };
  12236. Scene.prototype.getCameraByID = function (id) {
  12237. for (var index = 0; index < this.cameras.length; index++) {
  12238. if (this.cameras[index].id === id) {
  12239. return this.cameras[index];
  12240. }
  12241. }
  12242. return null;
  12243. };
  12244. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12245. for (var index = 0; index < this.cameras.length; index++) {
  12246. if (this.cameras[index].uniqueId === uniqueId) {
  12247. return this.cameras[index];
  12248. }
  12249. }
  12250. return null;
  12251. };
  12252. /**
  12253. * get a camera using its name
  12254. * @param {string} the camera's name
  12255. * @return {BABYLON.Camera|null} the camera or null if none found.
  12256. */
  12257. Scene.prototype.getCameraByName = function (name) {
  12258. for (var index = 0; index < this.cameras.length; index++) {
  12259. if (this.cameras[index].name === name) {
  12260. return this.cameras[index];
  12261. }
  12262. }
  12263. return null;
  12264. };
  12265. /**
  12266. * get a light node using its name
  12267. * @param {string} the light's name
  12268. * @return {BABYLON.Light|null} the light or null if none found.
  12269. */
  12270. Scene.prototype.getLightByName = function (name) {
  12271. for (var index = 0; index < this.lights.length; index++) {
  12272. if (this.lights[index].name === name) {
  12273. return this.lights[index];
  12274. }
  12275. }
  12276. return null;
  12277. };
  12278. /**
  12279. * get a light node using its ID
  12280. * @param {string} the light's id
  12281. * @return {BABYLON.Light|null} the light or null if none found.
  12282. */
  12283. Scene.prototype.getLightByID = function (id) {
  12284. for (var index = 0; index < this.lights.length; index++) {
  12285. if (this.lights[index].id === id) {
  12286. return this.lights[index];
  12287. }
  12288. }
  12289. return null;
  12290. };
  12291. /**
  12292. * get a light node using its scene-generated unique ID
  12293. * @param {number} the light's unique id
  12294. * @return {BABYLON.Light|null} the light or null if none found.
  12295. */
  12296. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12297. for (var index = 0; index < this.lights.length; index++) {
  12298. if (this.lights[index].uniqueId === uniqueId) {
  12299. return this.lights[index];
  12300. }
  12301. }
  12302. return null;
  12303. };
  12304. /**
  12305. * get a geometry using its ID
  12306. * @param {string} the geometry's id
  12307. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12308. */
  12309. Scene.prototype.getGeometryByID = function (id) {
  12310. for (var index = 0; index < this._geometries.length; index++) {
  12311. if (this._geometries[index].id === id) {
  12312. return this._geometries[index];
  12313. }
  12314. }
  12315. return null;
  12316. };
  12317. /**
  12318. * add a new geometry to this scene.
  12319. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12320. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12321. * @return {boolean} was the geometry added or not
  12322. */
  12323. Scene.prototype.pushGeometry = function (geometry, force) {
  12324. if (!force && this.getGeometryByID(geometry.id)) {
  12325. return false;
  12326. }
  12327. this._geometries.push(geometry);
  12328. //notify the collision coordinator
  12329. this.collisionCoordinator.onGeometryAdded(geometry);
  12330. if (this.onGeometryAdded) {
  12331. this.onGeometryAdded(geometry);
  12332. }
  12333. return true;
  12334. };
  12335. /**
  12336. * Removes an existing geometry
  12337. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12338. * @return {boolean} was the geometry removed or not
  12339. */
  12340. Scene.prototype.removeGeometry = function (geometry) {
  12341. var index = this._geometries.indexOf(geometry);
  12342. if (index > -1) {
  12343. this._geometries.splice(index, 1);
  12344. //notify the collision coordinator
  12345. this.collisionCoordinator.onGeometryDeleted(geometry);
  12346. if (this.onGeometryRemoved) {
  12347. this.onGeometryRemoved(geometry);
  12348. }
  12349. return true;
  12350. }
  12351. return false;
  12352. };
  12353. Scene.prototype.getGeometries = function () {
  12354. return this._geometries;
  12355. };
  12356. /**
  12357. * Get the first added mesh found of a given ID
  12358. * @param {string} id - the id to search for
  12359. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12360. */
  12361. Scene.prototype.getMeshByID = function (id) {
  12362. for (var index = 0; index < this.meshes.length; index++) {
  12363. if (this.meshes[index].id === id) {
  12364. return this.meshes[index];
  12365. }
  12366. }
  12367. return null;
  12368. };
  12369. /**
  12370. * Get a mesh with its auto-generated unique id
  12371. * @param {number} uniqueId - the unique id to search for
  12372. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12373. */
  12374. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12375. for (var index = 0; index < this.meshes.length; index++) {
  12376. if (this.meshes[index].uniqueId === uniqueId) {
  12377. return this.meshes[index];
  12378. }
  12379. }
  12380. return null;
  12381. };
  12382. /**
  12383. * Get a the last added mesh found of a given ID
  12384. * @param {string} id - the id to search for
  12385. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12386. */
  12387. Scene.prototype.getLastMeshByID = function (id) {
  12388. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12389. if (this.meshes[index].id === id) {
  12390. return this.meshes[index];
  12391. }
  12392. }
  12393. return null;
  12394. };
  12395. /**
  12396. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12397. * @param {string} id - the id to search for
  12398. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12399. */
  12400. Scene.prototype.getLastEntryByID = function (id) {
  12401. var index;
  12402. for (index = this.meshes.length - 1; index >= 0; index--) {
  12403. if (this.meshes[index].id === id) {
  12404. return this.meshes[index];
  12405. }
  12406. }
  12407. for (index = this.cameras.length - 1; index >= 0; index--) {
  12408. if (this.cameras[index].id === id) {
  12409. return this.cameras[index];
  12410. }
  12411. }
  12412. for (index = this.lights.length - 1; index >= 0; index--) {
  12413. if (this.lights[index].id === id) {
  12414. return this.lights[index];
  12415. }
  12416. }
  12417. return null;
  12418. };
  12419. Scene.prototype.getNodeByID = function (id) {
  12420. var mesh = this.getMeshByID(id);
  12421. if (mesh) {
  12422. return mesh;
  12423. }
  12424. var light = this.getLightByID(id);
  12425. if (light) {
  12426. return light;
  12427. }
  12428. return this.getCameraByID(id);
  12429. };
  12430. Scene.prototype.getNodeByName = function (name) {
  12431. var mesh = this.getMeshByName(name);
  12432. if (mesh) {
  12433. return mesh;
  12434. }
  12435. var light = this.getLightByName(name);
  12436. if (light) {
  12437. return light;
  12438. }
  12439. return this.getCameraByName(name);
  12440. };
  12441. Scene.prototype.getMeshByName = function (name) {
  12442. for (var index = 0; index < this.meshes.length; index++) {
  12443. if (this.meshes[index].name === name) {
  12444. return this.meshes[index];
  12445. }
  12446. }
  12447. return null;
  12448. };
  12449. Scene.prototype.getSoundByName = function (name) {
  12450. var index;
  12451. if (BABYLON.AudioEngine) {
  12452. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12453. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12454. return this.mainSoundTrack.soundCollection[index];
  12455. }
  12456. }
  12457. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12458. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12459. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12460. return this.soundTracks[sdIndex].soundCollection[index];
  12461. }
  12462. }
  12463. }
  12464. }
  12465. return null;
  12466. };
  12467. Scene.prototype.getLastSkeletonByID = function (id) {
  12468. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12469. if (this.skeletons[index].id === id) {
  12470. return this.skeletons[index];
  12471. }
  12472. }
  12473. return null;
  12474. };
  12475. Scene.prototype.getSkeletonById = function (id) {
  12476. for (var index = 0; index < this.skeletons.length; index++) {
  12477. if (this.skeletons[index].id === id) {
  12478. return this.skeletons[index];
  12479. }
  12480. }
  12481. return null;
  12482. };
  12483. Scene.prototype.getSkeletonByName = function (name) {
  12484. for (var index = 0; index < this.skeletons.length; index++) {
  12485. if (this.skeletons[index].name === name) {
  12486. return this.skeletons[index];
  12487. }
  12488. }
  12489. return null;
  12490. };
  12491. Scene.prototype.isActiveMesh = function (mesh) {
  12492. return (this._activeMeshes.indexOf(mesh) !== -1);
  12493. };
  12494. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12495. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12496. var material = subMesh.getMaterial();
  12497. if (mesh.showSubMeshesBoundingBox) {
  12498. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12499. }
  12500. if (material) {
  12501. // Render targets
  12502. if (material.getRenderTargetTextures) {
  12503. if (this._processedMaterials.indexOf(material) === -1) {
  12504. this._processedMaterials.push(material);
  12505. this._renderTargets.concat(material.getRenderTargetTextures());
  12506. }
  12507. }
  12508. // Dispatch
  12509. this._activeIndices += subMesh.indexCount;
  12510. this._renderingManager.dispatch(subMesh);
  12511. }
  12512. }
  12513. };
  12514. Scene.prototype._evaluateActiveMeshes = function () {
  12515. this.activeCamera._activeMeshes.reset();
  12516. this._activeMeshes.reset();
  12517. this._renderingManager.reset();
  12518. this._processedMaterials.reset();
  12519. this._activeParticleSystems.reset();
  12520. this._activeSkeletons.reset();
  12521. this._softwareSkinnedMeshes.reset();
  12522. this._boundingBoxRenderer.reset();
  12523. this._edgesRenderers.reset();
  12524. if (!this._frustumPlanes) {
  12525. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12526. }
  12527. else {
  12528. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12529. }
  12530. // Meshes
  12531. var meshes;
  12532. var len;
  12533. if (this._selectionOctree) {
  12534. var selection = this._selectionOctree.select(this._frustumPlanes);
  12535. meshes = selection.data;
  12536. len = selection.length;
  12537. }
  12538. else {
  12539. len = this.meshes.length;
  12540. meshes = this.meshes;
  12541. }
  12542. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12543. var mesh = meshes[meshIndex];
  12544. if (mesh.isBlocked) {
  12545. continue;
  12546. }
  12547. this._totalVertices += mesh.getTotalVertices();
  12548. if (!mesh.isReady() || !mesh.isEnabled()) {
  12549. continue;
  12550. }
  12551. mesh.computeWorldMatrix();
  12552. // Intersections
  12553. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12554. this._meshesForIntersections.pushNoDuplicate(mesh);
  12555. }
  12556. // Switch to current LOD
  12557. var meshLOD = mesh.getLOD(this.activeCamera);
  12558. if (!meshLOD) {
  12559. continue;
  12560. }
  12561. mesh._preActivate();
  12562. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12563. this._activeMeshes.push(mesh);
  12564. this.activeCamera._activeMeshes.push(mesh);
  12565. mesh._activate(this._renderId);
  12566. this._activeMesh(meshLOD);
  12567. }
  12568. }
  12569. // Particle systems
  12570. var beforeParticlesDate = BABYLON.Tools.Now;
  12571. if (this.particlesEnabled) {
  12572. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12573. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12574. var particleSystem = this.particleSystems[particleIndex];
  12575. if (!particleSystem.isStarted()) {
  12576. continue;
  12577. }
  12578. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12579. this._activeParticleSystems.push(particleSystem);
  12580. particleSystem.animate();
  12581. }
  12582. }
  12583. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12584. }
  12585. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12586. };
  12587. Scene.prototype._activeMesh = function (mesh) {
  12588. if (mesh.skeleton && this.skeletonsEnabled) {
  12589. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12590. if (!mesh.computeBonesUsingShaders) {
  12591. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12592. }
  12593. }
  12594. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12595. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12596. }
  12597. if (mesh._edgesRenderer) {
  12598. this._edgesRenderers.push(mesh._edgesRenderer);
  12599. }
  12600. if (mesh && mesh.subMeshes) {
  12601. // Submeshes Octrees
  12602. var len;
  12603. var subMeshes;
  12604. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12605. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12606. len = intersections.length;
  12607. subMeshes = intersections.data;
  12608. }
  12609. else {
  12610. subMeshes = mesh.subMeshes;
  12611. len = subMeshes.length;
  12612. }
  12613. for (var subIndex = 0; subIndex < len; subIndex++) {
  12614. var subMesh = subMeshes[subIndex];
  12615. this._evaluateSubMesh(subMesh, mesh);
  12616. }
  12617. }
  12618. };
  12619. Scene.prototype.updateTransformMatrix = function (force) {
  12620. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12621. };
  12622. Scene.prototype._renderForCamera = function (camera) {
  12623. var engine = this._engine;
  12624. this.activeCamera = camera;
  12625. if (!this.activeCamera)
  12626. throw new Error("Active camera not set");
  12627. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12628. // Viewport
  12629. engine.setViewport(this.activeCamera.viewport);
  12630. // Camera
  12631. this.resetCachedMaterial();
  12632. this._renderId++;
  12633. this.updateTransformMatrix();
  12634. if (this.beforeCameraRender) {
  12635. this.beforeCameraRender(this.activeCamera);
  12636. }
  12637. // Meshes
  12638. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12639. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12640. this._evaluateActiveMeshes();
  12641. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12642. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12643. // Skeletons
  12644. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12645. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12646. skeleton.prepare();
  12647. }
  12648. // Software skinning
  12649. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12650. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12651. mesh.applySkeleton(mesh.skeleton);
  12652. }
  12653. // Render targets
  12654. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12655. if (this.renderTargetsEnabled) {
  12656. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12657. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12658. var renderTarget = this._renderTargets.data[renderIndex];
  12659. if (renderTarget._shouldRender()) {
  12660. this._renderId++;
  12661. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12662. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12663. }
  12664. }
  12665. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12666. this._renderId++;
  12667. }
  12668. if (this._renderTargets.length > 0) {
  12669. engine.restoreDefaultFramebuffer();
  12670. }
  12671. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12672. // Prepare Frame
  12673. this.postProcessManager._prepareFrame();
  12674. var beforeRenderDate = BABYLON.Tools.Now;
  12675. // Backgrounds
  12676. var layerIndex;
  12677. var layer;
  12678. if (this.layers.length) {
  12679. engine.setDepthBuffer(false);
  12680. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12681. layer = this.layers[layerIndex];
  12682. if (layer.isBackground) {
  12683. layer.render();
  12684. }
  12685. }
  12686. engine.setDepthBuffer(true);
  12687. }
  12688. // Render
  12689. BABYLON.Tools.StartPerformanceCounter("Main render");
  12690. this._renderingManager.render(null, null, true, true);
  12691. BABYLON.Tools.EndPerformanceCounter("Main render");
  12692. // Bounding boxes
  12693. this._boundingBoxRenderer.render();
  12694. // Edges
  12695. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12696. this._edgesRenderers.data[edgesRendererIndex].render();
  12697. }
  12698. // Lens flares
  12699. if (this.lensFlaresEnabled) {
  12700. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12701. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12702. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12703. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12704. lensFlareSystem.render();
  12705. }
  12706. }
  12707. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12708. }
  12709. // Foregrounds
  12710. if (this.layers.length) {
  12711. engine.setDepthBuffer(false);
  12712. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12713. layer = this.layers[layerIndex];
  12714. if (!layer.isBackground) {
  12715. layer.render();
  12716. }
  12717. }
  12718. engine.setDepthBuffer(true);
  12719. }
  12720. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12721. // Finalize frame
  12722. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12723. // Update camera
  12724. this.activeCamera._updateFromScene();
  12725. // Reset some special arrays
  12726. this._renderTargets.reset();
  12727. if (this.afterCameraRender) {
  12728. this.afterCameraRender(this.activeCamera);
  12729. }
  12730. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12731. };
  12732. Scene.prototype._processSubCameras = function (camera) {
  12733. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12734. this._renderForCamera(camera);
  12735. return;
  12736. }
  12737. // rig cameras
  12738. for (var index = 0; index < camera._rigCameras.length; index++) {
  12739. this._renderForCamera(camera._rigCameras[index]);
  12740. }
  12741. this.activeCamera = camera;
  12742. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12743. // Update camera
  12744. this.activeCamera._updateFromScene();
  12745. };
  12746. Scene.prototype._checkIntersections = function () {
  12747. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12748. var sourceMesh = this._meshesForIntersections.data[index];
  12749. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12750. var action = sourceMesh.actionManager.actions[actionIndex];
  12751. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12752. var parameters = action.getTriggerParameter();
  12753. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12754. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12755. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12756. if (areIntersecting && currentIntersectionInProgress === -1) {
  12757. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12758. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12759. sourceMesh._intersectionsInProgress.push(otherMesh);
  12760. }
  12761. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12762. sourceMesh._intersectionsInProgress.push(otherMesh);
  12763. }
  12764. }
  12765. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12766. //They intersected, and now they don't.
  12767. //is this trigger an exit trigger? execute an event.
  12768. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12769. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12770. }
  12771. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12772. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12773. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12774. }
  12775. }
  12776. }
  12777. }
  12778. }
  12779. };
  12780. Scene.prototype.render = function () {
  12781. var startDate = BABYLON.Tools.Now;
  12782. this._particlesDuration = 0;
  12783. this._spritesDuration = 0;
  12784. this._activeParticles = 0;
  12785. this._renderDuration = 0;
  12786. this._renderTargetsDuration = 0;
  12787. this._evaluateActiveMeshesDuration = 0;
  12788. this._totalVertices = 0;
  12789. this._activeIndices = 0;
  12790. this._activeBones = 0;
  12791. this.getEngine().resetDrawCalls();
  12792. this._meshesForIntersections.reset();
  12793. this.resetCachedMaterial();
  12794. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12795. // Actions
  12796. if (this.actionManager) {
  12797. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12798. }
  12799. //Simplification Queue
  12800. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12801. this.simplificationQueue.executeNext();
  12802. }
  12803. // Animations
  12804. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12805. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12806. this._animate();
  12807. // Physics
  12808. if (this._physicsEngine) {
  12809. BABYLON.Tools.StartPerformanceCounter("Physics");
  12810. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12811. BABYLON.Tools.EndPerformanceCounter("Physics");
  12812. }
  12813. // Before render
  12814. if (this.beforeRender) {
  12815. this.beforeRender();
  12816. }
  12817. var callbackIndex;
  12818. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12819. this._onBeforeRenderCallbacks[callbackIndex]();
  12820. }
  12821. // Customs render targets
  12822. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12823. var engine = this.getEngine();
  12824. var currentActiveCamera = this.activeCamera;
  12825. if (this.renderTargetsEnabled) {
  12826. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12827. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12828. var renderTarget = this.customRenderTargets[customIndex];
  12829. if (renderTarget._shouldRender()) {
  12830. this._renderId++;
  12831. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12832. if (!this.activeCamera)
  12833. throw new Error("Active camera not set");
  12834. // Viewport
  12835. engine.setViewport(this.activeCamera.viewport);
  12836. // Camera
  12837. this.updateTransformMatrix();
  12838. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12839. }
  12840. }
  12841. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12842. this._renderId++;
  12843. }
  12844. if (this.customRenderTargets.length > 0) {
  12845. engine.restoreDefaultFramebuffer();
  12846. }
  12847. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12848. this.activeCamera = currentActiveCamera;
  12849. // Procedural textures
  12850. if (this.proceduralTexturesEnabled) {
  12851. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12852. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12853. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12854. if (proceduralTexture._shouldRender()) {
  12855. proceduralTexture.render();
  12856. }
  12857. }
  12858. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12859. }
  12860. // Clear
  12861. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12862. // Shadows
  12863. if (this.shadowsEnabled) {
  12864. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12865. var light = this.lights[lightIndex];
  12866. var shadowGenerator = light.getShadowGenerator();
  12867. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12868. this._renderTargets.push(shadowGenerator.getShadowMap());
  12869. }
  12870. }
  12871. }
  12872. // Depth renderer
  12873. if (this._depthRenderer) {
  12874. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12875. }
  12876. // RenderPipeline
  12877. this.postProcessRenderPipelineManager.update();
  12878. // Multi-cameras?
  12879. if (this.activeCameras.length > 0) {
  12880. var currentRenderId = this._renderId;
  12881. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12882. this._renderId = currentRenderId;
  12883. this._processSubCameras(this.activeCameras[cameraIndex]);
  12884. }
  12885. }
  12886. else {
  12887. if (!this.activeCamera) {
  12888. throw new Error("No camera defined");
  12889. }
  12890. this._processSubCameras(this.activeCamera);
  12891. }
  12892. // Intersection checks
  12893. this._checkIntersections();
  12894. // Update the audio listener attached to the camera
  12895. if (BABYLON.AudioEngine) {
  12896. this._updateAudioParameters();
  12897. }
  12898. // After render
  12899. if (this.afterRender) {
  12900. this.afterRender();
  12901. }
  12902. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12903. this._onAfterRenderCallbacks[callbackIndex]();
  12904. }
  12905. // Cleaning
  12906. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12907. this._toBeDisposed.data[index].dispose();
  12908. this._toBeDisposed[index] = null;
  12909. }
  12910. this._toBeDisposed.reset();
  12911. if (this.dumpNextRenderTargets) {
  12912. this.dumpNextRenderTargets = false;
  12913. }
  12914. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12915. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12916. };
  12917. Scene.prototype._updateAudioParameters = function () {
  12918. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  12919. return;
  12920. }
  12921. var listeningCamera;
  12922. var audioEngine = BABYLON.Engine.audioEngine;
  12923. if (this.activeCameras.length > 0) {
  12924. listeningCamera = this.activeCameras[0];
  12925. }
  12926. else {
  12927. listeningCamera = this.activeCamera;
  12928. }
  12929. if (listeningCamera && audioEngine.canUseWebAudio) {
  12930. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12931. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12932. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12933. cameraDirection.normalize();
  12934. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12935. var i;
  12936. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12937. var sound = this.mainSoundTrack.soundCollection[i];
  12938. if (sound.useCustomAttenuation) {
  12939. sound.updateDistanceFromListener();
  12940. }
  12941. }
  12942. for (i = 0; i < this.soundTracks.length; i++) {
  12943. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12944. sound = this.soundTracks[i].soundCollection[j];
  12945. if (sound.useCustomAttenuation) {
  12946. sound.updateDistanceFromListener();
  12947. }
  12948. }
  12949. }
  12950. }
  12951. };
  12952. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12953. // Audio
  12954. get: function () {
  12955. return this._audioEnabled;
  12956. },
  12957. set: function (value) {
  12958. this._audioEnabled = value;
  12959. if (BABYLON.AudioEngine) {
  12960. if (this._audioEnabled) {
  12961. this._enableAudio();
  12962. }
  12963. else {
  12964. this._disableAudio();
  12965. }
  12966. }
  12967. },
  12968. enumerable: true,
  12969. configurable: true
  12970. });
  12971. Scene.prototype._disableAudio = function () {
  12972. var i;
  12973. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12974. this.mainSoundTrack.soundCollection[i].pause();
  12975. }
  12976. for (i = 0; i < this.soundTracks.length; i++) {
  12977. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12978. this.soundTracks[i].soundCollection[j].pause();
  12979. }
  12980. }
  12981. };
  12982. Scene.prototype._enableAudio = function () {
  12983. var i;
  12984. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12985. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12986. this.mainSoundTrack.soundCollection[i].play();
  12987. }
  12988. }
  12989. for (i = 0; i < this.soundTracks.length; i++) {
  12990. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12991. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12992. this.soundTracks[i].soundCollection[j].play();
  12993. }
  12994. }
  12995. }
  12996. };
  12997. Object.defineProperty(Scene.prototype, "headphone", {
  12998. get: function () {
  12999. return this._headphone;
  13000. },
  13001. set: function (value) {
  13002. this._headphone = value;
  13003. if (BABYLON.AudioEngine) {
  13004. if (this._headphone) {
  13005. this._switchAudioModeForHeadphones();
  13006. }
  13007. else {
  13008. this._switchAudioModeForNormalSpeakers();
  13009. }
  13010. }
  13011. },
  13012. enumerable: true,
  13013. configurable: true
  13014. });
  13015. Scene.prototype._switchAudioModeForHeadphones = function () {
  13016. this.mainSoundTrack.switchPanningModelToHRTF();
  13017. for (var i = 0; i < this.soundTracks.length; i++) {
  13018. this.soundTracks[i].switchPanningModelToHRTF();
  13019. }
  13020. };
  13021. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13022. this.mainSoundTrack.switchPanningModelToEqualPower();
  13023. for (var i = 0; i < this.soundTracks.length; i++) {
  13024. this.soundTracks[i].switchPanningModelToEqualPower();
  13025. }
  13026. };
  13027. Scene.prototype.enableDepthRenderer = function () {
  13028. if (this._depthRenderer) {
  13029. return this._depthRenderer;
  13030. }
  13031. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13032. return this._depthRenderer;
  13033. };
  13034. Scene.prototype.disableDepthRenderer = function () {
  13035. if (!this._depthRenderer) {
  13036. return;
  13037. }
  13038. this._depthRenderer.dispose();
  13039. this._depthRenderer = null;
  13040. };
  13041. Scene.prototype.dispose = function () {
  13042. this.beforeRender = null;
  13043. this.afterRender = null;
  13044. this.skeletons = [];
  13045. this._boundingBoxRenderer.dispose();
  13046. if (this._depthRenderer) {
  13047. this._depthRenderer.dispose();
  13048. }
  13049. // Debug layer
  13050. this.debugLayer.hide();
  13051. // Events
  13052. if (this.onDispose) {
  13053. this.onDispose();
  13054. }
  13055. this._onBeforeRenderCallbacks = [];
  13056. this._onAfterRenderCallbacks = [];
  13057. this.detachControl();
  13058. // Release sounds & sounds tracks
  13059. if (BABYLON.AudioEngine) {
  13060. this.disposeSounds();
  13061. }
  13062. // Detach cameras
  13063. var canvas = this._engine.getRenderingCanvas();
  13064. var index;
  13065. for (index = 0; index < this.cameras.length; index++) {
  13066. this.cameras[index].detachControl(canvas);
  13067. }
  13068. // Release lights
  13069. while (this.lights.length) {
  13070. this.lights[0].dispose();
  13071. }
  13072. // Release meshes
  13073. while (this.meshes.length) {
  13074. this.meshes[0].dispose(true);
  13075. }
  13076. // Release cameras
  13077. while (this.cameras.length) {
  13078. this.cameras[0].dispose();
  13079. }
  13080. // Release materials
  13081. while (this.materials.length) {
  13082. this.materials[0].dispose();
  13083. }
  13084. // Release particles
  13085. while (this.particleSystems.length) {
  13086. this.particleSystems[0].dispose();
  13087. }
  13088. // Release sprites
  13089. while (this.spriteManagers.length) {
  13090. this.spriteManagers[0].dispose();
  13091. }
  13092. // Release layers
  13093. while (this.layers.length) {
  13094. this.layers[0].dispose();
  13095. }
  13096. // Release textures
  13097. while (this.textures.length) {
  13098. this.textures[0].dispose();
  13099. }
  13100. // Post-processes
  13101. this.postProcessManager.dispose();
  13102. // Physics
  13103. if (this._physicsEngine) {
  13104. this.disablePhysicsEngine();
  13105. }
  13106. // Remove from engine
  13107. index = this._engine.scenes.indexOf(this);
  13108. if (index > -1) {
  13109. this._engine.scenes.splice(index, 1);
  13110. }
  13111. this._engine.wipeCaches();
  13112. };
  13113. // Release sounds & sounds tracks
  13114. Scene.prototype.disposeSounds = function () {
  13115. this.mainSoundTrack.dispose();
  13116. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13117. this.soundTracks[scIndex].dispose();
  13118. }
  13119. };
  13120. // Octrees
  13121. Scene.prototype.getWorldExtends = function () {
  13122. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13123. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13124. for (var index = 0; index < this.meshes.length; index++) {
  13125. var mesh = this.meshes[index];
  13126. mesh.computeWorldMatrix(true);
  13127. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13128. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13129. BABYLON.Tools.CheckExtends(minBox, min, max);
  13130. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13131. }
  13132. return {
  13133. min: min,
  13134. max: max
  13135. };
  13136. };
  13137. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13138. if (maxCapacity === void 0) { maxCapacity = 64; }
  13139. if (maxDepth === void 0) { maxDepth = 2; }
  13140. if (!this._selectionOctree) {
  13141. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13142. }
  13143. var worldExtends = this.getWorldExtends();
  13144. // Update octree
  13145. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13146. return this._selectionOctree;
  13147. };
  13148. // Picking
  13149. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13150. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13151. var engine = this._engine;
  13152. if (!camera) {
  13153. if (!this.activeCamera)
  13154. throw new Error("Active camera not set");
  13155. camera = this.activeCamera;
  13156. }
  13157. var cameraViewport = camera.viewport;
  13158. var viewport = cameraViewport.toGlobal(engine);
  13159. // Moving coordinates to local viewport world
  13160. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13161. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13162. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13163. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13164. };
  13165. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13166. var engine = this._engine;
  13167. if (!camera) {
  13168. if (!this.activeCamera)
  13169. throw new Error("Active camera not set");
  13170. camera = this.activeCamera;
  13171. }
  13172. var cameraViewport = camera.viewport;
  13173. var viewport = cameraViewport.toGlobal(engine);
  13174. var identity = BABYLON.Matrix.Identity();
  13175. // Moving coordinates to local viewport world
  13176. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13177. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13178. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13179. };
  13180. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13181. var pickingInfo = null;
  13182. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13183. var mesh = this.meshes[meshIndex];
  13184. if (predicate) {
  13185. if (!predicate(mesh)) {
  13186. continue;
  13187. }
  13188. }
  13189. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13190. continue;
  13191. }
  13192. var world = mesh.getWorldMatrix();
  13193. var ray = rayFunction(world);
  13194. var result = mesh.intersects(ray, fastCheck);
  13195. if (!result || !result.hit)
  13196. continue;
  13197. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13198. continue;
  13199. pickingInfo = result;
  13200. if (fastCheck) {
  13201. break;
  13202. }
  13203. }
  13204. return pickingInfo || new BABYLON.PickingInfo();
  13205. };
  13206. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13207. var pickingInfo = null;
  13208. camera = camera || this.activeCamera;
  13209. if (this.spriteManagers.length > 0) {
  13210. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13211. var spriteManager = this.spriteManagers[spriteIndex];
  13212. if (!spriteManager.isPickable) {
  13213. continue;
  13214. }
  13215. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13216. if (!result || !result.hit)
  13217. continue;
  13218. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13219. continue;
  13220. pickingInfo = result;
  13221. if (fastCheck) {
  13222. break;
  13223. }
  13224. }
  13225. }
  13226. return pickingInfo || new BABYLON.PickingInfo();
  13227. };
  13228. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13229. var _this = this;
  13230. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13231. /// <param name="x">X position on screen</param>
  13232. /// <param name="y">Y position on screen</param>
  13233. /// <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>
  13234. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13235. /// <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>
  13236. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13237. };
  13238. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13239. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13240. /// <param name="x">X position on screen</param>
  13241. /// <param name="y">Y position on screen</param>
  13242. /// <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>
  13243. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13244. /// <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>
  13245. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13246. };
  13247. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13248. var _this = this;
  13249. return this._internalPick(function (world) {
  13250. if (!_this._pickWithRayInverseMatrix) {
  13251. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13252. }
  13253. world.invertToRef(_this._pickWithRayInverseMatrix);
  13254. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13255. }, predicate, fastCheck);
  13256. };
  13257. Scene.prototype.setPointerOverMesh = function (mesh) {
  13258. if (this._pointerOverMesh === mesh) {
  13259. return;
  13260. }
  13261. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13262. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13263. }
  13264. this._pointerOverMesh = mesh;
  13265. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13266. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13267. }
  13268. };
  13269. Scene.prototype.getPointerOverMesh = function () {
  13270. return this._pointerOverMesh;
  13271. };
  13272. // Physics
  13273. Scene.prototype.getPhysicsEngine = function () {
  13274. return this._physicsEngine;
  13275. };
  13276. /**
  13277. * Enables physics to the current scene
  13278. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13279. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13280. * @return {boolean} was the physics engine initialized
  13281. */
  13282. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13283. if (this._physicsEngine) {
  13284. return true;
  13285. }
  13286. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13287. if (!this._physicsEngine.isSupported()) {
  13288. this._physicsEngine = null;
  13289. return false;
  13290. }
  13291. this._physicsEngine._initialize(gravity);
  13292. return true;
  13293. };
  13294. Scene.prototype.disablePhysicsEngine = function () {
  13295. if (!this._physicsEngine) {
  13296. return;
  13297. }
  13298. this._physicsEngine.dispose();
  13299. this._physicsEngine = undefined;
  13300. };
  13301. Scene.prototype.isPhysicsEnabled = function () {
  13302. return this._physicsEngine !== undefined;
  13303. };
  13304. /**
  13305. * Sets the gravity of the physics engine (and NOT of the scene)
  13306. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13307. */
  13308. Scene.prototype.setGravity = function (gravity) {
  13309. if (!this._physicsEngine) {
  13310. return;
  13311. }
  13312. this._physicsEngine._setGravity(gravity);
  13313. };
  13314. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13315. if (parts.parts) {
  13316. options = parts;
  13317. parts = parts.parts;
  13318. }
  13319. if (!this._physicsEngine) {
  13320. return null;
  13321. }
  13322. for (var index = 0; index < parts.length; index++) {
  13323. var mesh = parts[index].mesh;
  13324. mesh._physicImpostor = parts[index].impostor;
  13325. mesh._physicsMass = options.mass / parts.length;
  13326. mesh._physicsFriction = options.friction;
  13327. mesh._physicRestitution = options.restitution;
  13328. }
  13329. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13330. };
  13331. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13332. for (var index = 0; index < compound.parts.length; index++) {
  13333. var mesh = compound.parts[index].mesh;
  13334. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13335. this._physicsEngine._unregisterMesh(mesh);
  13336. }
  13337. };
  13338. // Misc.
  13339. Scene.prototype.createDefaultCameraOrLight = function () {
  13340. // Light
  13341. if (this.lights.length === 0) {
  13342. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13343. }
  13344. // Camera
  13345. if (!this.activeCamera) {
  13346. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13347. // Compute position
  13348. var worldExtends = this.getWorldExtends();
  13349. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13350. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13351. camera.setTarget(worldCenter);
  13352. this.activeCamera = camera;
  13353. }
  13354. };
  13355. // Tags
  13356. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13357. if (tagsQuery === undefined) {
  13358. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13359. return list;
  13360. }
  13361. var listByTags = [];
  13362. forEach = forEach || (function (item) { return; });
  13363. for (var i in list) {
  13364. var item = list[i];
  13365. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13366. listByTags.push(item);
  13367. forEach(item);
  13368. }
  13369. }
  13370. return listByTags;
  13371. };
  13372. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13373. return this._getByTags(this.meshes, tagsQuery, forEach);
  13374. };
  13375. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13376. return this._getByTags(this.cameras, tagsQuery, forEach);
  13377. };
  13378. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13379. return this._getByTags(this.lights, tagsQuery, forEach);
  13380. };
  13381. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13382. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13383. };
  13384. // Statics
  13385. Scene._FOGMODE_NONE = 0;
  13386. Scene._FOGMODE_EXP = 1;
  13387. Scene._FOGMODE_EXP2 = 2;
  13388. Scene._FOGMODE_LINEAR = 3;
  13389. Scene.MinDeltaTime = 1.0;
  13390. Scene.MaxDeltaTime = 1000.0;
  13391. return Scene;
  13392. })();
  13393. BABYLON.Scene = Scene;
  13394. })(BABYLON || (BABYLON = {}));
  13395. var BABYLON;
  13396. (function (BABYLON) {
  13397. var VertexBuffer = (function () {
  13398. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13399. if (engine instanceof BABYLON.Mesh) {
  13400. this._engine = engine.getScene().getEngine();
  13401. }
  13402. else {
  13403. this._engine = engine;
  13404. }
  13405. this._updatable = updatable;
  13406. this._data = data;
  13407. if (!postponeInternalCreation) {
  13408. this.create();
  13409. }
  13410. this._kind = kind;
  13411. if (stride) {
  13412. this._strideSize = stride;
  13413. return;
  13414. }
  13415. // Deduce stride from kind
  13416. switch (kind) {
  13417. case VertexBuffer.PositionKind:
  13418. this._strideSize = 3;
  13419. break;
  13420. case VertexBuffer.NormalKind:
  13421. this._strideSize = 3;
  13422. break;
  13423. case VertexBuffer.UVKind:
  13424. case VertexBuffer.UV2Kind:
  13425. case VertexBuffer.UV3Kind:
  13426. case VertexBuffer.UV4Kind:
  13427. case VertexBuffer.UV5Kind:
  13428. case VertexBuffer.UV6Kind:
  13429. this._strideSize = 2;
  13430. break;
  13431. case VertexBuffer.ColorKind:
  13432. this._strideSize = 4;
  13433. break;
  13434. case VertexBuffer.MatricesIndicesKind:
  13435. this._strideSize = 4;
  13436. break;
  13437. case VertexBuffer.MatricesWeightsKind:
  13438. this._strideSize = 4;
  13439. break;
  13440. }
  13441. }
  13442. // Properties
  13443. VertexBuffer.prototype.isUpdatable = function () {
  13444. return this._updatable;
  13445. };
  13446. VertexBuffer.prototype.getData = function () {
  13447. return this._data;
  13448. };
  13449. VertexBuffer.prototype.getBuffer = function () {
  13450. return this._buffer;
  13451. };
  13452. VertexBuffer.prototype.getStrideSize = function () {
  13453. return this._strideSize;
  13454. };
  13455. // Methods
  13456. VertexBuffer.prototype.create = function (data) {
  13457. if (!data && this._buffer) {
  13458. return; // nothing to do
  13459. }
  13460. data = data || this._data;
  13461. if (!this._buffer) {
  13462. if (this._updatable) {
  13463. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13464. }
  13465. else {
  13466. this._buffer = this._engine.createVertexBuffer(data);
  13467. }
  13468. }
  13469. if (this._updatable) {
  13470. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13471. this._data = data;
  13472. }
  13473. };
  13474. VertexBuffer.prototype.update = function (data) {
  13475. this.create(data);
  13476. };
  13477. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13478. if (!this._buffer) {
  13479. return;
  13480. }
  13481. if (this._updatable) {
  13482. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13483. this._data = null;
  13484. }
  13485. };
  13486. VertexBuffer.prototype.dispose = function () {
  13487. if (!this._buffer) {
  13488. return;
  13489. }
  13490. if (this._engine._releaseBuffer(this._buffer)) {
  13491. this._buffer = null;
  13492. }
  13493. };
  13494. Object.defineProperty(VertexBuffer, "PositionKind", {
  13495. get: function () {
  13496. return VertexBuffer._PositionKind;
  13497. },
  13498. enumerable: true,
  13499. configurable: true
  13500. });
  13501. Object.defineProperty(VertexBuffer, "NormalKind", {
  13502. get: function () {
  13503. return VertexBuffer._NormalKind;
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Object.defineProperty(VertexBuffer, "UVKind", {
  13509. get: function () {
  13510. return VertexBuffer._UVKind;
  13511. },
  13512. enumerable: true,
  13513. configurable: true
  13514. });
  13515. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13516. get: function () {
  13517. return VertexBuffer._UV2Kind;
  13518. },
  13519. enumerable: true,
  13520. configurable: true
  13521. });
  13522. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13523. get: function () {
  13524. return VertexBuffer._UV3Kind;
  13525. },
  13526. enumerable: true,
  13527. configurable: true
  13528. });
  13529. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13530. get: function () {
  13531. return VertexBuffer._UV4Kind;
  13532. },
  13533. enumerable: true,
  13534. configurable: true
  13535. });
  13536. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13537. get: function () {
  13538. return VertexBuffer._UV5Kind;
  13539. },
  13540. enumerable: true,
  13541. configurable: true
  13542. });
  13543. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13544. get: function () {
  13545. return VertexBuffer._UV6Kind;
  13546. },
  13547. enumerable: true,
  13548. configurable: true
  13549. });
  13550. Object.defineProperty(VertexBuffer, "ColorKind", {
  13551. get: function () {
  13552. return VertexBuffer._ColorKind;
  13553. },
  13554. enumerable: true,
  13555. configurable: true
  13556. });
  13557. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13558. get: function () {
  13559. return VertexBuffer._MatricesIndicesKind;
  13560. },
  13561. enumerable: true,
  13562. configurable: true
  13563. });
  13564. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13565. get: function () {
  13566. return VertexBuffer._MatricesWeightsKind;
  13567. },
  13568. enumerable: true,
  13569. configurable: true
  13570. });
  13571. // Enums
  13572. VertexBuffer._PositionKind = "position";
  13573. VertexBuffer._NormalKind = "normal";
  13574. VertexBuffer._UVKind = "uv";
  13575. VertexBuffer._UV2Kind = "uv2";
  13576. VertexBuffer._UV3Kind = "uv3";
  13577. VertexBuffer._UV4Kind = "uv4";
  13578. VertexBuffer._UV5Kind = "uv5";
  13579. VertexBuffer._UV6Kind = "uv6";
  13580. VertexBuffer._ColorKind = "color";
  13581. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13582. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13583. return VertexBuffer;
  13584. })();
  13585. BABYLON.VertexBuffer = VertexBuffer;
  13586. })(BABYLON || (BABYLON = {}));
  13587. var BABYLON;
  13588. (function (BABYLON) {
  13589. /**
  13590. * Creates an instance based on a source mesh.
  13591. */
  13592. var InstancedMesh = (function (_super) {
  13593. __extends(InstancedMesh, _super);
  13594. function InstancedMesh(name, source) {
  13595. _super.call(this, name, source.getScene());
  13596. source.instances.push(this);
  13597. this._sourceMesh = source;
  13598. this.position.copyFrom(source.position);
  13599. this.rotation.copyFrom(source.rotation);
  13600. this.scaling.copyFrom(source.scaling);
  13601. if (source.rotationQuaternion) {
  13602. this.rotationQuaternion = source.rotationQuaternion.clone();
  13603. }
  13604. this.infiniteDistance = source.infiniteDistance;
  13605. this.setPivotMatrix(source.getPivotMatrix());
  13606. this.refreshBoundingInfo();
  13607. this._syncSubMeshes();
  13608. }
  13609. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13610. // Methods
  13611. get: function () {
  13612. return this._sourceMesh.receiveShadows;
  13613. },
  13614. enumerable: true,
  13615. configurable: true
  13616. });
  13617. Object.defineProperty(InstancedMesh.prototype, "material", {
  13618. get: function () {
  13619. return this._sourceMesh.material;
  13620. },
  13621. enumerable: true,
  13622. configurable: true
  13623. });
  13624. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13625. get: function () {
  13626. return this._sourceMesh.visibility;
  13627. },
  13628. enumerable: true,
  13629. configurable: true
  13630. });
  13631. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13632. get: function () {
  13633. return this._sourceMesh.skeleton;
  13634. },
  13635. enumerable: true,
  13636. configurable: true
  13637. });
  13638. InstancedMesh.prototype.getTotalVertices = function () {
  13639. return this._sourceMesh.getTotalVertices();
  13640. };
  13641. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13642. get: function () {
  13643. return this._sourceMesh;
  13644. },
  13645. enumerable: true,
  13646. configurable: true
  13647. });
  13648. InstancedMesh.prototype.getVerticesData = function (kind) {
  13649. return this._sourceMesh.getVerticesData(kind);
  13650. };
  13651. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13652. return this._sourceMesh.isVerticesDataPresent(kind);
  13653. };
  13654. InstancedMesh.prototype.getIndices = function () {
  13655. return this._sourceMesh.getIndices();
  13656. };
  13657. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13658. get: function () {
  13659. return this._sourceMesh._positions;
  13660. },
  13661. enumerable: true,
  13662. configurable: true
  13663. });
  13664. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13665. var meshBB = this._sourceMesh.getBoundingInfo();
  13666. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13667. this._updateBoundingInfo();
  13668. };
  13669. InstancedMesh.prototype._preActivate = function () {
  13670. if (this._currentLOD) {
  13671. this._currentLOD._preActivate();
  13672. }
  13673. };
  13674. InstancedMesh.prototype._activate = function (renderId) {
  13675. if (this._currentLOD) {
  13676. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13677. }
  13678. };
  13679. InstancedMesh.prototype.getLOD = function (camera) {
  13680. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13681. if (this._currentLOD === this.sourceMesh) {
  13682. return this;
  13683. }
  13684. return this._currentLOD;
  13685. };
  13686. InstancedMesh.prototype._syncSubMeshes = function () {
  13687. this.releaseSubMeshes();
  13688. if (this._sourceMesh.subMeshes) {
  13689. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13690. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13691. }
  13692. }
  13693. };
  13694. InstancedMesh.prototype._generatePointsArray = function () {
  13695. return this._sourceMesh._generatePointsArray();
  13696. };
  13697. // Clone
  13698. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13699. var result = this._sourceMesh.createInstance(name);
  13700. // Deep copy
  13701. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13702. // Bounding info
  13703. this.refreshBoundingInfo();
  13704. // Parent
  13705. if (newParent) {
  13706. result.parent = newParent;
  13707. }
  13708. if (!doNotCloneChildren) {
  13709. // Children
  13710. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13711. var mesh = this.getScene().meshes[index];
  13712. if (mesh.parent === this) {
  13713. mesh.clone(mesh.name, result);
  13714. }
  13715. }
  13716. }
  13717. result.computeWorldMatrix(true);
  13718. return result;
  13719. };
  13720. // Dispoe
  13721. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13722. // Remove from mesh
  13723. var index = this._sourceMesh.instances.indexOf(this);
  13724. this._sourceMesh.instances.splice(index, 1);
  13725. _super.prototype.dispose.call(this, doNotRecurse);
  13726. };
  13727. return InstancedMesh;
  13728. })(BABYLON.AbstractMesh);
  13729. BABYLON.InstancedMesh = InstancedMesh;
  13730. })(BABYLON || (BABYLON = {}));
  13731. var BABYLON;
  13732. (function (BABYLON) {
  13733. var _InstancesBatch = (function () {
  13734. function _InstancesBatch() {
  13735. this.mustReturn = false;
  13736. this.visibleInstances = new Array();
  13737. this.renderSelf = new Array();
  13738. }
  13739. return _InstancesBatch;
  13740. })();
  13741. BABYLON._InstancesBatch = _InstancesBatch;
  13742. var Mesh = (function (_super) {
  13743. __extends(Mesh, _super);
  13744. /**
  13745. * @constructor
  13746. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13747. * @param {Scene} scene - The scene to add this mesh to.
  13748. * @param {Node} parent - The parent of this mesh, if it has one
  13749. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13750. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13751. * When false, achieved by calling a clone(), also passing False.
  13752. * This will make creation of children, recursive.
  13753. */
  13754. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13755. if (parent === void 0) { parent = null; }
  13756. _super.call(this, name, scene);
  13757. // Members
  13758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13759. this.instances = new Array();
  13760. this._LODLevels = new Array();
  13761. this._onBeforeRenderCallbacks = new Array();
  13762. this._onAfterRenderCallbacks = new Array();
  13763. this._visibleInstances = {};
  13764. this._renderIdForInstances = new Array();
  13765. this._batchCache = new _InstancesBatch();
  13766. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13767. this._sideOrientation = Mesh._DEFAULTSIDE;
  13768. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13769. if (source) {
  13770. // Geometry
  13771. if (source._geometry) {
  13772. source._geometry.applyToMesh(this);
  13773. }
  13774. // Deep copy
  13775. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13776. this.id = name + "." + source.id;
  13777. // Material
  13778. this.material = source.material;
  13779. var index;
  13780. if (!doNotCloneChildren) {
  13781. // Children
  13782. for (index = 0; index < scene.meshes.length; index++) {
  13783. var mesh = scene.meshes[index];
  13784. if (mesh.parent === source) {
  13785. // doNotCloneChildren is always going to be False
  13786. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13787. }
  13788. }
  13789. }
  13790. // Particles
  13791. for (index = 0; index < scene.particleSystems.length; index++) {
  13792. var system = scene.particleSystems[index];
  13793. if (system.emitter === source) {
  13794. system.clone(system.name, this);
  13795. }
  13796. }
  13797. this.computeWorldMatrix(true);
  13798. }
  13799. // Parent
  13800. if (parent !== null) {
  13801. this.parent = parent;
  13802. }
  13803. }
  13804. Object.defineProperty(Mesh, "FRONTSIDE", {
  13805. get: function () {
  13806. return Mesh._FRONTSIDE;
  13807. },
  13808. enumerable: true,
  13809. configurable: true
  13810. });
  13811. Object.defineProperty(Mesh, "BACKSIDE", {
  13812. get: function () {
  13813. return Mesh._BACKSIDE;
  13814. },
  13815. enumerable: true,
  13816. configurable: true
  13817. });
  13818. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13819. get: function () {
  13820. return Mesh._DOUBLESIDE;
  13821. },
  13822. enumerable: true,
  13823. configurable: true
  13824. });
  13825. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13826. get: function () {
  13827. return Mesh._DEFAULTSIDE;
  13828. },
  13829. enumerable: true,
  13830. configurable: true
  13831. });
  13832. Object.defineProperty(Mesh, "NO_CAP", {
  13833. get: function () {
  13834. return Mesh._NO_CAP;
  13835. },
  13836. enumerable: true,
  13837. configurable: true
  13838. });
  13839. Object.defineProperty(Mesh, "CAP_START", {
  13840. get: function () {
  13841. return Mesh._CAP_START;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. Object.defineProperty(Mesh, "CAP_END", {
  13847. get: function () {
  13848. return Mesh._CAP_END;
  13849. },
  13850. enumerable: true,
  13851. configurable: true
  13852. });
  13853. Object.defineProperty(Mesh, "CAP_ALL", {
  13854. get: function () {
  13855. return Mesh._CAP_ALL;
  13856. },
  13857. enumerable: true,
  13858. configurable: true
  13859. });
  13860. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13861. // Methods
  13862. get: function () {
  13863. return this._LODLevels.length > 0;
  13864. },
  13865. enumerable: true,
  13866. configurable: true
  13867. });
  13868. Mesh.prototype._sortLODLevels = function () {
  13869. this._LODLevels.sort(function (a, b) {
  13870. if (a.distance < b.distance) {
  13871. return 1;
  13872. }
  13873. if (a.distance > b.distance) {
  13874. return -1;
  13875. }
  13876. return 0;
  13877. });
  13878. };
  13879. /**
  13880. * Add a mesh as LOD level triggered at the given distance.
  13881. * @param {number} distance - the distance from the center of the object to show this level
  13882. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13883. * @return {BABYLON.Mesh} this mesh (for chaining)
  13884. */
  13885. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13886. if (mesh && mesh._masterMesh) {
  13887. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13888. return this;
  13889. }
  13890. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13891. this._LODLevels.push(level);
  13892. if (mesh) {
  13893. mesh._masterMesh = this;
  13894. }
  13895. this._sortLODLevels();
  13896. return this;
  13897. };
  13898. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13899. for (var index = 0; index < this._LODLevels.length; index++) {
  13900. var level = this._LODLevels[index];
  13901. if (level.distance === distance) {
  13902. return level.mesh;
  13903. }
  13904. }
  13905. return null;
  13906. };
  13907. /**
  13908. * Remove a mesh from the LOD array
  13909. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13910. * @return {BABYLON.Mesh} this mesh (for chaining)
  13911. */
  13912. Mesh.prototype.removeLODLevel = function (mesh) {
  13913. for (var index = 0; index < this._LODLevels.length; index++) {
  13914. if (this._LODLevels[index].mesh === mesh) {
  13915. this._LODLevels.splice(index, 1);
  13916. if (mesh) {
  13917. mesh._masterMesh = null;
  13918. }
  13919. }
  13920. }
  13921. this._sortLODLevels();
  13922. return this;
  13923. };
  13924. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13925. if (!this._LODLevels || this._LODLevels.length === 0) {
  13926. return this;
  13927. }
  13928. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13929. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13930. if (this.onLODLevelSelection) {
  13931. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13932. }
  13933. return this;
  13934. }
  13935. for (var index = 0; index < this._LODLevels.length; index++) {
  13936. var level = this._LODLevels[index];
  13937. if (level.distance < distanceToCamera) {
  13938. if (level.mesh) {
  13939. level.mesh._preActivate();
  13940. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13941. }
  13942. if (this.onLODLevelSelection) {
  13943. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13944. }
  13945. return level.mesh;
  13946. }
  13947. }
  13948. if (this.onLODLevelSelection) {
  13949. this.onLODLevelSelection(distanceToCamera, this, this);
  13950. }
  13951. return this;
  13952. };
  13953. Object.defineProperty(Mesh.prototype, "geometry", {
  13954. get: function () {
  13955. return this._geometry;
  13956. },
  13957. enumerable: true,
  13958. configurable: true
  13959. });
  13960. Mesh.prototype.getTotalVertices = function () {
  13961. if (!this._geometry) {
  13962. return 0;
  13963. }
  13964. return this._geometry.getTotalVertices();
  13965. };
  13966. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13967. if (!this._geometry) {
  13968. return null;
  13969. }
  13970. return this._geometry.getVerticesData(kind, copyWhenShared);
  13971. };
  13972. Mesh.prototype.getVertexBuffer = function (kind) {
  13973. if (!this._geometry) {
  13974. return undefined;
  13975. }
  13976. return this._geometry.getVertexBuffer(kind);
  13977. };
  13978. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13979. if (!this._geometry) {
  13980. if (this._delayInfo) {
  13981. return this._delayInfo.indexOf(kind) !== -1;
  13982. }
  13983. return false;
  13984. }
  13985. return this._geometry.isVerticesDataPresent(kind);
  13986. };
  13987. Mesh.prototype.getVerticesDataKinds = function () {
  13988. if (!this._geometry) {
  13989. var result = [];
  13990. if (this._delayInfo) {
  13991. for (var kind in this._delayInfo) {
  13992. result.push(kind);
  13993. }
  13994. }
  13995. return result;
  13996. }
  13997. return this._geometry.getVerticesDataKinds();
  13998. };
  13999. Mesh.prototype.getTotalIndices = function () {
  14000. if (!this._geometry) {
  14001. return 0;
  14002. }
  14003. return this._geometry.getTotalIndices();
  14004. };
  14005. Mesh.prototype.getIndices = function (copyWhenShared) {
  14006. if (!this._geometry) {
  14007. return [];
  14008. }
  14009. return this._geometry.getIndices(copyWhenShared);
  14010. };
  14011. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14012. get: function () {
  14013. return this._masterMesh !== null && this._masterMesh !== undefined;
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. Mesh.prototype.isReady = function () {
  14019. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14020. return false;
  14021. }
  14022. return _super.prototype.isReady.call(this);
  14023. };
  14024. Mesh.prototype.isDisposed = function () {
  14025. return this._isDisposed;
  14026. };
  14027. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14028. get: function () {
  14029. return this._sideOrientation;
  14030. },
  14031. set: function (sideO) {
  14032. this._sideOrientation = sideO;
  14033. },
  14034. enumerable: true,
  14035. configurable: true
  14036. });
  14037. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14038. get: function () {
  14039. return this._areNormalsFrozen;
  14040. },
  14041. enumerable: true,
  14042. configurable: true
  14043. });
  14044. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14045. Mesh.prototype.freezeNormals = function () {
  14046. this._areNormalsFrozen = true;
  14047. };
  14048. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14049. Mesh.prototype.unfreezeNormals = function () {
  14050. this._areNormalsFrozen = false;
  14051. };
  14052. // Methods
  14053. Mesh.prototype._preActivate = function () {
  14054. var sceneRenderId = this.getScene().getRenderId();
  14055. if (this._preActivateId === sceneRenderId) {
  14056. return;
  14057. }
  14058. this._preActivateId = sceneRenderId;
  14059. this._visibleInstances = null;
  14060. };
  14061. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14062. if (!this._visibleInstances) {
  14063. this._visibleInstances = {};
  14064. this._visibleInstances.defaultRenderId = renderId;
  14065. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14066. }
  14067. if (!this._visibleInstances[renderId]) {
  14068. this._visibleInstances[renderId] = new Array();
  14069. }
  14070. this._visibleInstances[renderId].push(instance);
  14071. };
  14072. Mesh.prototype.refreshBoundingInfo = function () {
  14073. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14074. if (data) {
  14075. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14076. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14077. }
  14078. if (this.subMeshes) {
  14079. for (var index = 0; index < this.subMeshes.length; index++) {
  14080. this.subMeshes[index].refreshBoundingInfo();
  14081. }
  14082. }
  14083. this._updateBoundingInfo();
  14084. };
  14085. Mesh.prototype._createGlobalSubMesh = function () {
  14086. var totalVertices = this.getTotalVertices();
  14087. if (!totalVertices || !this.getIndices()) {
  14088. return null;
  14089. }
  14090. this.releaseSubMeshes();
  14091. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14092. };
  14093. Mesh.prototype.subdivide = function (count) {
  14094. if (count < 1) {
  14095. return;
  14096. }
  14097. var totalIndices = this.getTotalIndices();
  14098. var subdivisionSize = (totalIndices / count) | 0;
  14099. var offset = 0;
  14100. // Ensure that subdivisionSize is a multiple of 3
  14101. while (subdivisionSize % 3 !== 0) {
  14102. subdivisionSize++;
  14103. }
  14104. this.releaseSubMeshes();
  14105. for (var index = 0; index < count; index++) {
  14106. if (offset >= totalIndices) {
  14107. break;
  14108. }
  14109. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14110. offset += subdivisionSize;
  14111. }
  14112. this.synchronizeInstances();
  14113. };
  14114. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14115. if (!this._geometry) {
  14116. var vertexData = new BABYLON.VertexData();
  14117. vertexData.set(data, kind);
  14118. var scene = this.getScene();
  14119. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14120. }
  14121. else {
  14122. this._geometry.setVerticesData(kind, data, updatable, stride);
  14123. }
  14124. };
  14125. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14126. if (!this._geometry) {
  14127. return;
  14128. }
  14129. if (!makeItUnique) {
  14130. this._geometry.updateVerticesData(kind, data, updateExtends);
  14131. }
  14132. else {
  14133. this.makeGeometryUnique();
  14134. this.updateVerticesData(kind, data, updateExtends, false);
  14135. }
  14136. };
  14137. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14138. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14139. if (!this._geometry) {
  14140. return;
  14141. }
  14142. if (!makeItUnique) {
  14143. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14144. }
  14145. else {
  14146. this.makeGeometryUnique();
  14147. this.updateVerticesDataDirectly(kind, data, offset, false);
  14148. }
  14149. };
  14150. // Mesh positions update function :
  14151. // updates the mesh positions according to the positionFunction returned values.
  14152. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14153. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14154. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14155. if (computeNormals === void 0) { computeNormals = true; }
  14156. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14157. positionFunction(positions);
  14158. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14159. if (computeNormals) {
  14160. var indices = this.getIndices();
  14161. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14162. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14163. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14164. }
  14165. };
  14166. Mesh.prototype.makeGeometryUnique = function () {
  14167. if (!this._geometry) {
  14168. return;
  14169. }
  14170. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14171. geometry.applyToMesh(this);
  14172. };
  14173. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14174. if (!this._geometry) {
  14175. var vertexData = new BABYLON.VertexData();
  14176. vertexData.indices = indices;
  14177. var scene = this.getScene();
  14178. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14179. }
  14180. else {
  14181. this._geometry.setIndices(indices, totalVertices);
  14182. }
  14183. };
  14184. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14185. var engine = this.getScene().getEngine();
  14186. // Wireframe
  14187. var indexToBind;
  14188. switch (fillMode) {
  14189. case BABYLON.Material.PointFillMode:
  14190. indexToBind = null;
  14191. break;
  14192. case BABYLON.Material.WireFrameFillMode:
  14193. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14194. break;
  14195. default:
  14196. case BABYLON.Material.TriangleFillMode:
  14197. indexToBind = this._geometry.getIndexBuffer();
  14198. break;
  14199. }
  14200. // VBOs
  14201. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14202. };
  14203. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14204. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14205. return;
  14206. }
  14207. var engine = this.getScene().getEngine();
  14208. // Draw order
  14209. switch (fillMode) {
  14210. case BABYLON.Material.PointFillMode:
  14211. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14212. break;
  14213. case BABYLON.Material.WireFrameFillMode:
  14214. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14215. break;
  14216. default:
  14217. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14218. }
  14219. };
  14220. Mesh.prototype.registerBeforeRender = function (func) {
  14221. this._onBeforeRenderCallbacks.push(func);
  14222. };
  14223. Mesh.prototype.unregisterBeforeRender = function (func) {
  14224. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14225. if (index > -1) {
  14226. this._onBeforeRenderCallbacks.splice(index, 1);
  14227. }
  14228. };
  14229. Mesh.prototype.registerAfterRender = function (func) {
  14230. this._onAfterRenderCallbacks.push(func);
  14231. };
  14232. Mesh.prototype.unregisterAfterRender = function (func) {
  14233. var index = this._onAfterRenderCallbacks.indexOf(func);
  14234. if (index > -1) {
  14235. this._onAfterRenderCallbacks.splice(index, 1);
  14236. }
  14237. };
  14238. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14239. var scene = this.getScene();
  14240. this._batchCache.mustReturn = false;
  14241. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14242. this._batchCache.visibleInstances[subMeshId] = null;
  14243. if (this._visibleInstances) {
  14244. var currentRenderId = scene.getRenderId();
  14245. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14246. var selfRenderId = this._renderId;
  14247. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14248. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14249. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14250. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14251. }
  14252. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14253. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14254. this._batchCache.mustReturn = true;
  14255. return this._batchCache;
  14256. }
  14257. if (currentRenderId !== selfRenderId) {
  14258. this._batchCache.renderSelf[subMeshId] = false;
  14259. }
  14260. }
  14261. this._renderIdForInstances[subMeshId] = currentRenderId;
  14262. }
  14263. return this._batchCache;
  14264. };
  14265. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14266. var visibleInstances = batch.visibleInstances[subMesh._id];
  14267. var matricesCount = visibleInstances.length + 1;
  14268. var bufferSize = matricesCount * 16 * 4;
  14269. while (this._instancesBufferSize < bufferSize) {
  14270. this._instancesBufferSize *= 2;
  14271. }
  14272. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14273. if (this._worldMatricesInstancesBuffer) {
  14274. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14275. }
  14276. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14277. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14278. }
  14279. var offset = 0;
  14280. var instancesCount = 0;
  14281. var world = this.getWorldMatrix();
  14282. if (batch.renderSelf[subMesh._id]) {
  14283. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14284. offset += 16;
  14285. instancesCount++;
  14286. }
  14287. if (visibleInstances) {
  14288. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14289. var instance = visibleInstances[instanceIndex];
  14290. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14291. offset += 16;
  14292. instancesCount++;
  14293. }
  14294. }
  14295. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14296. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14297. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14298. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14299. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14300. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14301. this._draw(subMesh, fillMode, instancesCount);
  14302. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14303. };
  14304. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14305. var scene = this.getScene();
  14306. var engine = scene.getEngine();
  14307. if (hardwareInstancedRendering) {
  14308. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14309. }
  14310. else {
  14311. if (batch.renderSelf[subMesh._id]) {
  14312. // Draw
  14313. if (onBeforeDraw) {
  14314. onBeforeDraw(false, this.getWorldMatrix());
  14315. }
  14316. this._draw(subMesh, fillMode);
  14317. }
  14318. if (batch.visibleInstances[subMesh._id]) {
  14319. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14320. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14321. // World
  14322. var world = instance.getWorldMatrix();
  14323. if (onBeforeDraw) {
  14324. onBeforeDraw(true, world);
  14325. }
  14326. // Draw
  14327. this._draw(subMesh, fillMode);
  14328. }
  14329. }
  14330. }
  14331. };
  14332. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14333. var scene = this.getScene();
  14334. // Managing instances
  14335. var batch = this._getInstancesRenderList(subMesh._id);
  14336. if (batch.mustReturn) {
  14337. return;
  14338. }
  14339. // Checking geometry state
  14340. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14341. return;
  14342. }
  14343. var callbackIndex;
  14344. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14345. this._onBeforeRenderCallbacks[callbackIndex](this);
  14346. }
  14347. var engine = scene.getEngine();
  14348. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14349. // Material
  14350. var effectiveMaterial = subMesh.getMaterial();
  14351. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14352. return;
  14353. }
  14354. // Outline - step 1
  14355. var savedDepthWrite = engine.getDepthWrite();
  14356. if (this.renderOutline) {
  14357. engine.setDepthWrite(false);
  14358. scene.getOutlineRenderer().render(subMesh, batch);
  14359. engine.setDepthWrite(savedDepthWrite);
  14360. }
  14361. effectiveMaterial._preBind();
  14362. var effect = effectiveMaterial.getEffect();
  14363. // Bind
  14364. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14365. this._bind(subMesh, effect, fillMode);
  14366. var world = this.getWorldMatrix();
  14367. effectiveMaterial.bind(world, this);
  14368. // Alpha mode
  14369. if (enableAlphaMode) {
  14370. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14371. }
  14372. // Draw
  14373. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14374. if (isInstance) {
  14375. effectiveMaterial.bindOnlyWorldMatrix(world);
  14376. }
  14377. });
  14378. // Unbind
  14379. effectiveMaterial.unbind();
  14380. // Outline - step 2
  14381. if (this.renderOutline && savedDepthWrite) {
  14382. engine.setDepthWrite(true);
  14383. engine.setColorWrite(false);
  14384. scene.getOutlineRenderer().render(subMesh, batch);
  14385. engine.setColorWrite(true);
  14386. }
  14387. // Overlay
  14388. if (this.renderOverlay) {
  14389. var currentMode = engine.getAlphaMode();
  14390. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14391. scene.getOutlineRenderer().render(subMesh, batch, true);
  14392. engine.setAlphaMode(currentMode);
  14393. }
  14394. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14395. this._onAfterRenderCallbacks[callbackIndex](this);
  14396. }
  14397. };
  14398. Mesh.prototype.getEmittedParticleSystems = function () {
  14399. var results = new Array();
  14400. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14401. var particleSystem = this.getScene().particleSystems[index];
  14402. if (particleSystem.emitter === this) {
  14403. results.push(particleSystem);
  14404. }
  14405. }
  14406. return results;
  14407. };
  14408. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14409. var results = new Array();
  14410. var descendants = this.getDescendants();
  14411. descendants.push(this);
  14412. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14413. var particleSystem = this.getScene().particleSystems[index];
  14414. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14415. results.push(particleSystem);
  14416. }
  14417. }
  14418. return results;
  14419. };
  14420. Mesh.prototype.getChildren = function () {
  14421. var results = [];
  14422. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14423. var mesh = this.getScene().meshes[index];
  14424. if (mesh.parent === this) {
  14425. results.push(mesh);
  14426. }
  14427. }
  14428. return results;
  14429. };
  14430. Mesh.prototype._checkDelayState = function () {
  14431. var _this = this;
  14432. var that = this;
  14433. var scene = this.getScene();
  14434. if (this._geometry) {
  14435. this._geometry.load(scene);
  14436. }
  14437. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14438. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14439. scene._addPendingData(that);
  14440. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14441. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14442. if (data instanceof ArrayBuffer) {
  14443. _this._delayLoadingFunction(data, _this);
  14444. }
  14445. else {
  14446. _this._delayLoadingFunction(JSON.parse(data), _this);
  14447. }
  14448. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14449. scene._removePendingData(_this);
  14450. }, function () { }, scene.database, getBinaryData);
  14451. }
  14452. };
  14453. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14454. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14455. return false;
  14456. }
  14457. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14458. return false;
  14459. }
  14460. this._checkDelayState();
  14461. return true;
  14462. };
  14463. Mesh.prototype.setMaterialByID = function (id) {
  14464. var materials = this.getScene().materials;
  14465. var index;
  14466. for (index = 0; index < materials.length; index++) {
  14467. if (materials[index].id === id) {
  14468. this.material = materials[index];
  14469. return;
  14470. }
  14471. }
  14472. // Multi
  14473. var multiMaterials = this.getScene().multiMaterials;
  14474. for (index = 0; index < multiMaterials.length; index++) {
  14475. if (multiMaterials[index].id === id) {
  14476. this.material = multiMaterials[index];
  14477. return;
  14478. }
  14479. }
  14480. };
  14481. Mesh.prototype.getAnimatables = function () {
  14482. var results = [];
  14483. if (this.material) {
  14484. results.push(this.material);
  14485. }
  14486. if (this.skeleton) {
  14487. results.push(this.skeleton);
  14488. }
  14489. return results;
  14490. };
  14491. // Geometry
  14492. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14493. // Position
  14494. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14495. return;
  14496. }
  14497. this._resetPointsArrayCache();
  14498. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14499. var temp = [];
  14500. var index;
  14501. for (index = 0; index < data.length; index += 3) {
  14502. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14503. }
  14504. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14505. // Normals
  14506. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14507. return;
  14508. }
  14509. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14510. temp = [];
  14511. for (index = 0; index < data.length; index += 3) {
  14512. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14513. }
  14514. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14515. // flip faces?
  14516. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14517. this.flipFaces();
  14518. }
  14519. };
  14520. // Will apply current transform to mesh and reset world matrix
  14521. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14522. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14523. this.scaling.copyFromFloats(1, 1, 1);
  14524. this.position.copyFromFloats(0, 0, 0);
  14525. this.rotation.copyFromFloats(0, 0, 0);
  14526. //only if quaternion is already set
  14527. if (this.rotationQuaternion) {
  14528. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14529. }
  14530. this._worldMatrix = BABYLON.Matrix.Identity();
  14531. };
  14532. // Cache
  14533. Mesh.prototype._resetPointsArrayCache = function () {
  14534. this._positions = null;
  14535. };
  14536. Mesh.prototype._generatePointsArray = function () {
  14537. if (this._positions)
  14538. return true;
  14539. this._positions = [];
  14540. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14541. if (!data) {
  14542. return false;
  14543. }
  14544. for (var index = 0; index < data.length; index += 3) {
  14545. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14546. }
  14547. return true;
  14548. };
  14549. // Clone
  14550. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14551. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14552. };
  14553. // Dispose
  14554. Mesh.prototype.dispose = function (doNotRecurse) {
  14555. if (this._geometry) {
  14556. this._geometry.releaseForMesh(this, true);
  14557. }
  14558. // Instances
  14559. if (this._worldMatricesInstancesBuffer) {
  14560. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14561. this._worldMatricesInstancesBuffer = null;
  14562. }
  14563. while (this.instances.length) {
  14564. this.instances[0].dispose();
  14565. }
  14566. _super.prototype.dispose.call(this, doNotRecurse);
  14567. };
  14568. // Geometric tools
  14569. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14570. var _this = this;
  14571. var scene = this.getScene();
  14572. var onload = function (img) {
  14573. // Getting height map data
  14574. var canvas = document.createElement("canvas");
  14575. var context = canvas.getContext("2d");
  14576. var heightMapWidth = img.width;
  14577. var heightMapHeight = img.height;
  14578. canvas.width = heightMapWidth;
  14579. canvas.height = heightMapHeight;
  14580. context.drawImage(img, 0, 0);
  14581. // Create VertexData from map data
  14582. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14583. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14584. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14585. //execute success callback, if set
  14586. if (onSuccess) {
  14587. onSuccess(_this);
  14588. }
  14589. };
  14590. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14591. };
  14592. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14594. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14595. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14596. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14597. return;
  14598. }
  14599. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14600. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14601. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14602. var position = BABYLON.Vector3.Zero();
  14603. var normal = BABYLON.Vector3.Zero();
  14604. var uv = BABYLON.Vector2.Zero();
  14605. for (var index = 0; index < positions.length; index += 3) {
  14606. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14607. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14608. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14609. // Compute height
  14610. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14611. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14612. var pos = (u + v * heightMapWidth) * 4;
  14613. var r = buffer[pos] / 255.0;
  14614. var g = buffer[pos + 1] / 255.0;
  14615. var b = buffer[pos + 2] / 255.0;
  14616. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14617. normal.normalize();
  14618. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14619. position = position.add(normal);
  14620. position.toArray(positions, index);
  14621. }
  14622. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14623. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14624. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14625. };
  14626. Mesh.prototype.convertToFlatShadedMesh = function () {
  14627. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14628. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14629. var kinds = this.getVerticesDataKinds();
  14630. var vbs = [];
  14631. var data = [];
  14632. var newdata = [];
  14633. var updatableNormals = false;
  14634. var kindIndex;
  14635. var kind;
  14636. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14637. kind = kinds[kindIndex];
  14638. var vertexBuffer = this.getVertexBuffer(kind);
  14639. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14640. updatableNormals = vertexBuffer.isUpdatable();
  14641. kinds.splice(kindIndex, 1);
  14642. kindIndex--;
  14643. continue;
  14644. }
  14645. vbs[kind] = vertexBuffer;
  14646. data[kind] = vbs[kind].getData();
  14647. newdata[kind] = [];
  14648. }
  14649. // Save previous submeshes
  14650. var previousSubmeshes = this.subMeshes.slice(0);
  14651. var indices = this.getIndices();
  14652. var totalIndices = this.getTotalIndices();
  14653. // Generating unique vertices per face
  14654. var index;
  14655. for (index = 0; index < totalIndices; index++) {
  14656. var vertexIndex = indices[index];
  14657. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14658. kind = kinds[kindIndex];
  14659. var stride = vbs[kind].getStrideSize();
  14660. for (var offset = 0; offset < stride; offset++) {
  14661. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14662. }
  14663. }
  14664. }
  14665. // Updating faces & normal
  14666. var normals = [];
  14667. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14668. for (index = 0; index < totalIndices; index += 3) {
  14669. indices[index] = index;
  14670. indices[index + 1] = index + 1;
  14671. indices[index + 2] = index + 2;
  14672. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14673. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14674. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14675. var p1p2 = p1.subtract(p2);
  14676. var p3p2 = p3.subtract(p2);
  14677. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14678. // Store same normals for every vertex
  14679. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14680. normals.push(normal.x);
  14681. normals.push(normal.y);
  14682. normals.push(normal.z);
  14683. }
  14684. }
  14685. this.setIndices(indices);
  14686. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14687. // Updating vertex buffers
  14688. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14689. kind = kinds[kindIndex];
  14690. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14691. }
  14692. // Updating submeshes
  14693. this.releaseSubMeshes();
  14694. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14695. var previousOne = previousSubmeshes[submeshIndex];
  14696. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14697. }
  14698. this.synchronizeInstances();
  14699. };
  14700. // will inverse faces orientations, and invert normals too if specified
  14701. Mesh.prototype.flipFaces = function (flipNormals) {
  14702. if (flipNormals === void 0) { flipNormals = false; }
  14703. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14704. var i;
  14705. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14706. for (i = 0; i < vertex_data.normals.length; i++) {
  14707. vertex_data.normals[i] *= -1;
  14708. }
  14709. }
  14710. var temp;
  14711. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14712. // reassign indices
  14713. temp = vertex_data.indices[i + 1];
  14714. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14715. vertex_data.indices[i + 2] = temp;
  14716. }
  14717. vertex_data.applyToMesh(this);
  14718. };
  14719. // Instances
  14720. Mesh.prototype.createInstance = function (name) {
  14721. return new BABYLON.InstancedMesh(name, this);
  14722. };
  14723. Mesh.prototype.synchronizeInstances = function () {
  14724. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14725. var instance = this.instances[instanceIndex];
  14726. instance._syncSubMeshes();
  14727. }
  14728. };
  14729. /**
  14730. * Simplify the mesh according to the given array of settings.
  14731. * Function will return immediately and will simplify async.
  14732. * @param settings a collection of simplification settings.
  14733. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14734. * @param type the type of simplification to run.
  14735. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14736. */
  14737. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14738. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14739. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14740. this.getScene().simplificationQueue.addTask({
  14741. settings: settings,
  14742. parallelProcessing: parallelProcessing,
  14743. mesh: this,
  14744. simplificationType: simplificationType,
  14745. successCallback: successCallback
  14746. });
  14747. };
  14748. /**
  14749. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14750. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14751. * This should be used together with the simplification to avoid disappearing triangles.
  14752. * @param successCallback an optional success callback to be called after the optimization finished.
  14753. */
  14754. Mesh.prototype.optimizeIndices = function (successCallback) {
  14755. var _this = this;
  14756. var indices = this.getIndices();
  14757. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14758. var vectorPositions = [];
  14759. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14760. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14761. }
  14762. var dupes = [];
  14763. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14764. var realPos = vectorPositions.length - 1 - iteration;
  14765. var testedPosition = vectorPositions[realPos];
  14766. for (var j = 0; j < realPos; ++j) {
  14767. var againstPosition = vectorPositions[j];
  14768. if (testedPosition.equals(againstPosition)) {
  14769. dupes[realPos] = j;
  14770. break;
  14771. }
  14772. }
  14773. }, function () {
  14774. for (var i = 0; i < indices.length; ++i) {
  14775. indices[i] = dupes[indices[i]] || indices[i];
  14776. }
  14777. //indices are now reordered
  14778. var originalSubMeshes = _this.subMeshes.slice(0);
  14779. _this.setIndices(indices);
  14780. _this.subMeshes = originalSubMeshes;
  14781. if (successCallback) {
  14782. successCallback(_this);
  14783. }
  14784. });
  14785. };
  14786. // Statics
  14787. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14788. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14789. pathArray: pathArray,
  14790. closeArray: closeArray,
  14791. closePath: closePath,
  14792. offset: offset,
  14793. updatable: updatable,
  14794. sideOrientation: sideOrientation,
  14795. instance: instance
  14796. }, scene);
  14797. };
  14798. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14799. var options = {
  14800. radius: radius,
  14801. tessellation: tessellation,
  14802. sideOrientation: sideOrientation,
  14803. updatable: updatable
  14804. };
  14805. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14806. };
  14807. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14808. var options = {
  14809. size: size,
  14810. sideOrientation: sideOrientation,
  14811. updatable: updatable
  14812. };
  14813. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14814. };
  14815. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14816. var options = {
  14817. segments: segments,
  14818. diameterX: diameter,
  14819. diameterY: diameter,
  14820. diameterZ: diameter,
  14821. sideOrientation: sideOrientation,
  14822. updatable: updatable
  14823. };
  14824. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14825. };
  14826. // Cylinder and cone
  14827. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14828. var options = {
  14829. height: height,
  14830. diameterTop: diameterTop,
  14831. diameterBottom: diameterBottom,
  14832. tessellation: tessellation,
  14833. subdivisions: subdivisions,
  14834. sideOrientation: sideOrientation,
  14835. updatable: updatable
  14836. };
  14837. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14838. };
  14839. // Torus (Code from SharpDX.org)
  14840. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14841. var options = {
  14842. diameter: diameter,
  14843. thickness: thickness,
  14844. tessellation: tessellation,
  14845. sideOrientation: sideOrientation,
  14846. updatable: updatable
  14847. };
  14848. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14849. };
  14850. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14851. var options = {
  14852. radius: radius,
  14853. tube: tube,
  14854. radialSegments: radialSegments,
  14855. tubularSegments: tubularSegments,
  14856. p: p,
  14857. q: q,
  14858. sideOrientation: sideOrientation,
  14859. updatable: updatable
  14860. };
  14861. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14862. };
  14863. // Lines
  14864. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14865. var options = {
  14866. points: points,
  14867. updatable: updatable,
  14868. instance: instance
  14869. };
  14870. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14871. };
  14872. // Dashed Lines
  14873. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14874. var options = {
  14875. points: points,
  14876. dashSize: dashSize,
  14877. gapSize: gapSize,
  14878. dashNb: dashNb,
  14879. updatable: updatable
  14880. };
  14881. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14882. };
  14883. // Extrusion
  14884. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14885. var options = {
  14886. shape: shape,
  14887. path: path,
  14888. scale: scale,
  14889. rotation: rotation,
  14890. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14891. sideOrientation: sideOrientation,
  14892. instance: instance,
  14893. updatable: updatable
  14894. };
  14895. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  14896. };
  14897. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  14898. var options = {
  14899. shape: shape,
  14900. path: path,
  14901. scaleFunction: scaleFunction,
  14902. rotationFunction: rotationFunction,
  14903. ribbonCloseArray: ribbonCloseArray,
  14904. ribbonClosePath: ribbonClosePath,
  14905. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14906. sideOrientation: sideOrientation,
  14907. instance: instance,
  14908. updatable: updatable
  14909. };
  14910. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  14911. };
  14912. // Lathe
  14913. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  14914. var options = {
  14915. shape: shape,
  14916. radius: radius,
  14917. tesselation: tessellation,
  14918. sideOrientation: sideOrientation,
  14919. updatable: updatable
  14920. };
  14921. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  14922. };
  14923. // Plane & ground
  14924. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14925. var options = {
  14926. size: size,
  14927. width: size,
  14928. height: size,
  14929. sideOrientation: sideOrientation,
  14930. updatable: updatable
  14931. };
  14932. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  14933. };
  14934. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14935. var options = {
  14936. width: width,
  14937. height: height,
  14938. subdivisions: subdivisions,
  14939. updatable: updatable
  14940. };
  14941. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  14942. };
  14943. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14944. var options = {
  14945. xmin: xmin,
  14946. zmin: zmin,
  14947. xmax: xmax,
  14948. zmax: zmax,
  14949. subdivisions: subdivisions,
  14950. precision: precision,
  14951. updatable: updatable
  14952. };
  14953. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  14954. };
  14955. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14956. var options = {
  14957. width: width,
  14958. height: height,
  14959. subdivisions: subdivisions,
  14960. minHeight: minHeight,
  14961. maxHeight: maxHeight,
  14962. updatable: updatable,
  14963. onReady: onReady
  14964. };
  14965. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  14966. };
  14967. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  14968. var options = {
  14969. path: path,
  14970. radius: radius,
  14971. tessellation: tessellation,
  14972. radiusFunction: radiusFunction,
  14973. arc: 1,
  14974. cap: cap,
  14975. updatable: updatable,
  14976. sideOrientation: sideOrientation,
  14977. instance: instance
  14978. };
  14979. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  14980. };
  14981. Mesh.CreatePolyhedron = function (name, options, scene) {
  14982. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  14983. };
  14984. // Decals
  14985. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14986. var options = {
  14987. position: position,
  14988. normal: normal,
  14989. size: size,
  14990. angle: angle
  14991. };
  14992. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  14993. };
  14994. // Skeletons
  14995. /**
  14996. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  14997. */
  14998. Mesh.prototype.setPositionsForCPUSkinning = function () {
  14999. var source;
  15000. if (!this._sourcePositions) {
  15001. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15002. this._sourcePositions = new Float32Array(source);
  15003. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15004. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15005. }
  15006. }
  15007. return this._sourcePositions;
  15008. };
  15009. /**
  15010. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15011. */
  15012. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15013. var source;
  15014. if (!this._sourceNormals) {
  15015. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15016. this._sourceNormals = new Float32Array(source);
  15017. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15018. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15019. }
  15020. }
  15021. return this._sourceNormals;
  15022. };
  15023. /**
  15024. * Update the vertex buffers by applying transformation from the bones
  15025. * @param {skeleton} skeleton to apply
  15026. */
  15027. Mesh.prototype.applySkeleton = function (skeleton) {
  15028. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15029. return this;
  15030. }
  15031. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15032. return this;
  15033. }
  15034. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15035. return this;
  15036. }
  15037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15038. return this;
  15039. }
  15040. if (!this._sourcePositions) {
  15041. this.setPositionsForCPUSkinning();
  15042. }
  15043. if (!this._sourceNormals) {
  15044. this.setNormalsForCPUSkinning();
  15045. }
  15046. // positionsData checks for not being Float32Array will only pass at most once
  15047. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15048. if (!(positionsData instanceof Float32Array)) {
  15049. positionsData = new Float32Array(positionsData);
  15050. }
  15051. // normalsData checks for not being Float32Array will only pass at most once
  15052. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15053. if (!(normalsData instanceof Float32Array)) {
  15054. normalsData = new Float32Array(normalsData);
  15055. }
  15056. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15057. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15058. var skeletonMatrices = skeleton.getTransformMatrices();
  15059. var tempVector3 = BABYLON.Vector3.Zero();
  15060. var finalMatrix = new BABYLON.Matrix();
  15061. var tempMatrix = new BABYLON.Matrix();
  15062. var matWeightIdx = 0;
  15063. for (var index = 0; index < positionsData.length; index += 3) {
  15064. for (var inf = 0; inf < this.numBoneInfluencers; inf++) {
  15065. var weight = matricesWeightsData[matWeightIdx + inf];
  15066. if (weight > 0) {
  15067. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15068. finalMatrix.addToSelf(tempMatrix);
  15069. }
  15070. else
  15071. break;
  15072. }
  15073. matWeightIdx += this.numBoneInfluencers;
  15074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15075. tempVector3.toArray(positionsData, index);
  15076. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15077. tempVector3.toArray(normalsData, index);
  15078. finalMatrix.reset();
  15079. }
  15080. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15081. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15082. return this;
  15083. };
  15084. // Tools
  15085. Mesh.MinMax = function (meshes) {
  15086. var minVector = null;
  15087. var maxVector = null;
  15088. for (var i in meshes) {
  15089. var mesh = meshes[i];
  15090. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15091. if (!minVector) {
  15092. minVector = boundingBox.minimumWorld;
  15093. maxVector = boundingBox.maximumWorld;
  15094. continue;
  15095. }
  15096. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15097. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15098. }
  15099. return {
  15100. min: minVector,
  15101. max: maxVector
  15102. };
  15103. };
  15104. Mesh.Center = function (meshesOrMinMaxVector) {
  15105. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15106. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15107. };
  15108. /**
  15109. * Merge the array of meshes into a single mesh for performance reasons.
  15110. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15111. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15112. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15113. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15114. */
  15115. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15116. if (disposeSource === void 0) { disposeSource = true; }
  15117. var index;
  15118. if (!allow32BitsIndices) {
  15119. var totalVertices = 0;
  15120. // Counting vertices
  15121. for (index = 0; index < meshes.length; index++) {
  15122. if (meshes[index]) {
  15123. totalVertices += meshes[index].getTotalVertices();
  15124. if (totalVertices > 65536) {
  15125. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15126. return null;
  15127. }
  15128. }
  15129. }
  15130. }
  15131. // Merge
  15132. var vertexData;
  15133. var otherVertexData;
  15134. var source;
  15135. for (index = 0; index < meshes.length; index++) {
  15136. if (meshes[index]) {
  15137. meshes[index].computeWorldMatrix(true);
  15138. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15139. otherVertexData.transform(meshes[index].getWorldMatrix());
  15140. if (vertexData) {
  15141. vertexData.merge(otherVertexData);
  15142. }
  15143. else {
  15144. vertexData = otherVertexData;
  15145. source = meshes[index];
  15146. }
  15147. }
  15148. }
  15149. if (!meshSubclass) {
  15150. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15151. }
  15152. vertexData.applyToMesh(meshSubclass);
  15153. // Setting properties
  15154. meshSubclass.material = source.material;
  15155. meshSubclass.checkCollisions = source.checkCollisions;
  15156. // Cleaning
  15157. if (disposeSource) {
  15158. for (index = 0; index < meshes.length; index++) {
  15159. if (meshes[index]) {
  15160. meshes[index].dispose();
  15161. }
  15162. }
  15163. }
  15164. return meshSubclass;
  15165. };
  15166. // Consts
  15167. Mesh._FRONTSIDE = 0;
  15168. Mesh._BACKSIDE = 1;
  15169. Mesh._DOUBLESIDE = 2;
  15170. Mesh._DEFAULTSIDE = 0;
  15171. Mesh._NO_CAP = 0;
  15172. Mesh._CAP_START = 1;
  15173. Mesh._CAP_END = 2;
  15174. Mesh._CAP_ALL = 3;
  15175. return Mesh;
  15176. })(BABYLON.AbstractMesh);
  15177. BABYLON.Mesh = Mesh;
  15178. })(BABYLON || (BABYLON = {}));
  15179. var BABYLON;
  15180. (function (BABYLON) {
  15181. var SubMesh = (function () {
  15182. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15183. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15184. this.materialIndex = materialIndex;
  15185. this.verticesStart = verticesStart;
  15186. this.verticesCount = verticesCount;
  15187. this.indexStart = indexStart;
  15188. this.indexCount = indexCount;
  15189. this._renderId = 0;
  15190. this._mesh = mesh;
  15191. this._renderingMesh = renderingMesh || mesh;
  15192. mesh.subMeshes.push(this);
  15193. this._trianglePlanes = [];
  15194. this._id = mesh.subMeshes.length - 1;
  15195. if (createBoundingBox) {
  15196. this.refreshBoundingInfo();
  15197. mesh.computeWorldMatrix(true);
  15198. }
  15199. }
  15200. SubMesh.prototype.getBoundingInfo = function () {
  15201. return this._boundingInfo;
  15202. };
  15203. SubMesh.prototype.getMesh = function () {
  15204. return this._mesh;
  15205. };
  15206. SubMesh.prototype.getRenderingMesh = function () {
  15207. return this._renderingMesh;
  15208. };
  15209. SubMesh.prototype.getMaterial = function () {
  15210. var rootMaterial = this._renderingMesh.material;
  15211. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15212. var multiMaterial = rootMaterial;
  15213. return multiMaterial.getSubMaterial(this.materialIndex);
  15214. }
  15215. if (!rootMaterial) {
  15216. return this._mesh.getScene().defaultMaterial;
  15217. }
  15218. return rootMaterial;
  15219. };
  15220. // Methods
  15221. SubMesh.prototype.refreshBoundingInfo = function () {
  15222. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15223. if (!data) {
  15224. this._boundingInfo = this._mesh._boundingInfo;
  15225. return;
  15226. }
  15227. var indices = this._renderingMesh.getIndices();
  15228. var extend;
  15229. //is this the only submesh?
  15230. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15231. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15232. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15233. }
  15234. else {
  15235. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15236. }
  15237. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15238. };
  15239. SubMesh.prototype._checkCollision = function (collider) {
  15240. return this._boundingInfo._checkCollision(collider);
  15241. };
  15242. SubMesh.prototype.updateBoundingInfo = function (world) {
  15243. if (!this._boundingInfo) {
  15244. this.refreshBoundingInfo();
  15245. }
  15246. this._boundingInfo._update(world);
  15247. };
  15248. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15249. return this._boundingInfo.isInFrustum(frustumPlanes);
  15250. };
  15251. SubMesh.prototype.render = function (enableAlphaMode) {
  15252. this._renderingMesh.render(this, enableAlphaMode);
  15253. };
  15254. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15255. if (!this._linesIndexBuffer) {
  15256. var linesIndices = [];
  15257. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15258. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15259. }
  15260. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15261. this.linesIndexCount = linesIndices.length;
  15262. }
  15263. return this._linesIndexBuffer;
  15264. };
  15265. SubMesh.prototype.canIntersects = function (ray) {
  15266. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15267. };
  15268. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15269. var intersectInfo = null;
  15270. // Triangles test
  15271. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15272. var p0 = positions[indices[index]];
  15273. var p1 = positions[indices[index + 1]];
  15274. var p2 = positions[indices[index + 2]];
  15275. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15276. if (currentIntersectInfo) {
  15277. if (currentIntersectInfo.distance < 0) {
  15278. continue;
  15279. }
  15280. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15281. intersectInfo = currentIntersectInfo;
  15282. intersectInfo.faceId = index / 3;
  15283. if (fastCheck) {
  15284. break;
  15285. }
  15286. }
  15287. }
  15288. }
  15289. return intersectInfo;
  15290. };
  15291. // Clone
  15292. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15293. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15294. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15295. return result;
  15296. };
  15297. // Dispose
  15298. SubMesh.prototype.dispose = function () {
  15299. if (this._linesIndexBuffer) {
  15300. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15301. this._linesIndexBuffer = null;
  15302. }
  15303. // Remove from mesh
  15304. var index = this._mesh.subMeshes.indexOf(this);
  15305. this._mesh.subMeshes.splice(index, 1);
  15306. };
  15307. // Statics
  15308. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15309. var minVertexIndex = Number.MAX_VALUE;
  15310. var maxVertexIndex = -Number.MAX_VALUE;
  15311. renderingMesh = renderingMesh || mesh;
  15312. var indices = renderingMesh.getIndices();
  15313. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15314. var vertexIndex = indices[index];
  15315. if (vertexIndex < minVertexIndex)
  15316. minVertexIndex = vertexIndex;
  15317. if (vertexIndex > maxVertexIndex)
  15318. maxVertexIndex = vertexIndex;
  15319. }
  15320. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15321. };
  15322. return SubMesh;
  15323. })();
  15324. BABYLON.SubMesh = SubMesh;
  15325. })(BABYLON || (BABYLON = {}));
  15326. var BABYLON;
  15327. (function (BABYLON) {
  15328. var MeshBuilder = (function () {
  15329. function MeshBuilder() {
  15330. }
  15331. MeshBuilder.CreateBox = function (name, options, scene) {
  15332. var box = new BABYLON.Mesh(name, scene);
  15333. var vertexData = BABYLON.VertexData.CreateBox(options);
  15334. vertexData.applyToMesh(box, options.updatable);
  15335. return box;
  15336. };
  15337. MeshBuilder.CreateSphere = function (name, options, scene) {
  15338. var sphere = new BABYLON.Mesh(name, scene);
  15339. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15340. vertexData.applyToMesh(sphere, options.updatable);
  15341. return sphere;
  15342. };
  15343. MeshBuilder.CreateDisc = function (name, options, scene) {
  15344. var disc = new BABYLON.Mesh(name, scene);
  15345. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15346. vertexData.applyToMesh(disc, options.updatable);
  15347. return disc;
  15348. };
  15349. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15350. var pathArray = options.pathArray;
  15351. var closeArray = options.closeArray;
  15352. var closePath = options.closePath;
  15353. var offset = options.offset;
  15354. var sideOrientation = options.sideOrientation;
  15355. var instance = options.instance;
  15356. var updatable = options.updatable;
  15357. if (instance) {
  15358. // positionFunction : ribbon case
  15359. // only pathArray and sideOrientation parameters are taken into account for positions update
  15360. var positionFunction = function (positions) {
  15361. var minlg = pathArray[0].length;
  15362. var i = 0;
  15363. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15364. for (var si = 1; si <= ns; si++) {
  15365. for (var p = 0; p < pathArray.length; p++) {
  15366. var path = pathArray[p];
  15367. var l = path.length;
  15368. minlg = (minlg < l) ? minlg : l;
  15369. var j = 0;
  15370. while (j < minlg) {
  15371. positions[i] = path[j].x;
  15372. positions[i + 1] = path[j].y;
  15373. positions[i + 2] = path[j].z;
  15374. j++;
  15375. i += 3;
  15376. }
  15377. if (instance._closePath) {
  15378. positions[i] = path[0].x;
  15379. positions[i + 1] = path[0].y;
  15380. positions[i + 2] = path[0].z;
  15381. i += 3;
  15382. }
  15383. }
  15384. }
  15385. };
  15386. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15387. positionFunction(positions);
  15388. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15389. if (!(instance.areNormalsFrozen)) {
  15390. var indices = instance.getIndices();
  15391. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15392. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15393. if (instance._closePath) {
  15394. var indexFirst = 0;
  15395. var indexLast = 0;
  15396. for (var p = 0; p < pathArray.length; p++) {
  15397. indexFirst = instance._idx[p] * 3;
  15398. if (p + 1 < pathArray.length) {
  15399. indexLast = (instance._idx[p + 1] - 1) * 3;
  15400. }
  15401. else {
  15402. indexLast = normals.length - 3;
  15403. }
  15404. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15405. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15406. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15407. normals[indexLast] = normals[indexFirst];
  15408. normals[indexLast + 1] = normals[indexFirst + 1];
  15409. normals[indexLast + 2] = normals[indexFirst + 2];
  15410. }
  15411. }
  15412. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15413. }
  15414. return instance;
  15415. }
  15416. else {
  15417. var ribbon = new BABYLON.Mesh(name, scene);
  15418. ribbon.sideOrientation = sideOrientation;
  15419. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15420. if (closePath) {
  15421. ribbon._idx = vertexData._idx;
  15422. }
  15423. ribbon._closePath = closePath;
  15424. ribbon._closeArray = closeArray;
  15425. vertexData.applyToMesh(ribbon, updatable);
  15426. return ribbon;
  15427. }
  15428. };
  15429. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15430. var cylinder = new BABYLON.Mesh(name, scene);
  15431. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15432. vertexData.applyToMesh(cylinder, options.updatable);
  15433. return cylinder;
  15434. };
  15435. MeshBuilder.CreateTorus = function (name, options, scene) {
  15436. var torus = new BABYLON.Mesh(name, scene);
  15437. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15438. vertexData.applyToMesh(torus, options.updatable);
  15439. return torus;
  15440. };
  15441. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15442. var torusKnot = new BABYLON.Mesh(name, scene);
  15443. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15444. vertexData.applyToMesh(torusKnot, options.updatable);
  15445. return torusKnot;
  15446. };
  15447. MeshBuilder.CreateLines = function (name, options, scene) {
  15448. var instance = options.instance;
  15449. var points = options.points;
  15450. if (instance) {
  15451. var positionFunction = function (positions) {
  15452. var i = 0;
  15453. for (var p = 0; p < points.length; p++) {
  15454. positions[i] = points[p].x;
  15455. positions[i + 1] = points[p].y;
  15456. positions[i + 2] = points[p].z;
  15457. i += 3;
  15458. }
  15459. };
  15460. instance.updateMeshPositions(positionFunction, false);
  15461. return instance;
  15462. }
  15463. // lines creation
  15464. var lines = new BABYLON.LinesMesh(name, scene);
  15465. var vertexData = BABYLON.VertexData.CreateLines(options);
  15466. vertexData.applyToMesh(lines, options.updatable);
  15467. return lines;
  15468. };
  15469. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15470. var points = options.points;
  15471. var instance = options.instance;
  15472. var gapSize = options.gapSize;
  15473. var dashNb = options.dashNb;
  15474. var dashSize = options.dashSize;
  15475. if (instance) {
  15476. var positionFunction = function (positions) {
  15477. var curvect = BABYLON.Vector3.Zero();
  15478. var nbSeg = positions.length / 6;
  15479. var lg = 0;
  15480. var nb = 0;
  15481. var shft = 0;
  15482. var dashshft = 0;
  15483. var curshft = 0;
  15484. var p = 0;
  15485. var i = 0;
  15486. var j = 0;
  15487. for (i = 0; i < points.length - 1; i++) {
  15488. points[i + 1].subtractToRef(points[i], curvect);
  15489. lg += curvect.length();
  15490. }
  15491. shft = lg / nbSeg;
  15492. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15493. for (i = 0; i < points.length - 1; i++) {
  15494. points[i + 1].subtractToRef(points[i], curvect);
  15495. nb = Math.floor(curvect.length() / shft);
  15496. curvect.normalize();
  15497. j = 0;
  15498. while (j < nb && p < positions.length) {
  15499. curshft = shft * j;
  15500. positions[p] = points[i].x + curshft * curvect.x;
  15501. positions[p + 1] = points[i].y + curshft * curvect.y;
  15502. positions[p + 2] = points[i].z + curshft * curvect.z;
  15503. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15504. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15505. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15506. p += 6;
  15507. j++;
  15508. }
  15509. }
  15510. while (p < positions.length) {
  15511. positions[p] = points[i].x;
  15512. positions[p + 1] = points[i].y;
  15513. positions[p + 2] = points[i].z;
  15514. p += 3;
  15515. }
  15516. };
  15517. instance.updateMeshPositions(positionFunction, false);
  15518. return instance;
  15519. }
  15520. // dashed lines creation
  15521. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15522. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15523. vertexData.applyToMesh(dashedLines, options.updatable);
  15524. dashedLines.dashSize = dashSize;
  15525. dashedLines.gapSize = gapSize;
  15526. return dashedLines;
  15527. };
  15528. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15529. var path = options.path;
  15530. var shape = options.shape;
  15531. var scale = options.scale || 1;
  15532. var rotation = options.rotation || 0;
  15533. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15534. var updatable = options.updatable;
  15535. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15536. var instance = options.instance;
  15537. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15538. };
  15539. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15540. var path = options.path;
  15541. var shape = options.shape;
  15542. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15543. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15544. var ribbonCloseArray = options.ribbonCloseArray || false;
  15545. var ribbonClosePath = options.ribbonClosePath || false;
  15546. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15547. var updatable = options.updatable;
  15548. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15549. var instance = options.instance;
  15550. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15551. };
  15552. MeshBuilder.CreateLathe = function (name, options, scene) {
  15553. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15554. var closed = (options.closed === undefined) ? true : options.closed;
  15555. var shape = options.shape;
  15556. var radius = options.radius || 1;
  15557. var tessellation = options.tessellation || 64;
  15558. var updatable = options.updatable;
  15559. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15560. var pi2 = Math.PI * 2;
  15561. var shapeLathe = new Array();
  15562. // first rotatable point
  15563. var i = 0;
  15564. while (shape[i].x === 0) {
  15565. i++;
  15566. }
  15567. var pt = shape[i];
  15568. for (i = 0; i < shape.length; i++) {
  15569. shapeLathe.push(shape[i].subtract(pt));
  15570. }
  15571. // circle path
  15572. var step = pi2 / tessellation * arc;
  15573. var rotated;
  15574. var path = new Array();
  15575. ;
  15576. for (i = 0; i <= tessellation; i++) {
  15577. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15578. path.push(rotated);
  15579. }
  15580. if (closed) {
  15581. path.push(path[0]);
  15582. }
  15583. // extrusion
  15584. var scaleFunction = function () { return 1; };
  15585. var rotateFunction = function () { return 0; };
  15586. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15587. return lathe;
  15588. };
  15589. MeshBuilder.CreatePlane = function (name, options, scene) {
  15590. var plane = new BABYLON.Mesh(name, scene);
  15591. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15592. vertexData.applyToMesh(plane, options.updatable);
  15593. if (options.sourcePlane) {
  15594. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15595. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15596. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15597. plane.rotate(vectorProduct, product);
  15598. }
  15599. return plane;
  15600. };
  15601. MeshBuilder.CreateGround = function (name, options, scene) {
  15602. var ground = new BABYLON.GroundMesh(name, scene);
  15603. ground._setReady(false);
  15604. ground._subdivisions = options.subdivisions || 1;
  15605. var vertexData = BABYLON.VertexData.CreateGround(options);
  15606. vertexData.applyToMesh(ground, options.updatable);
  15607. ground._setReady(true);
  15608. return ground;
  15609. };
  15610. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15611. var tiledGround = new BABYLON.Mesh(name, scene);
  15612. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15613. vertexData.applyToMesh(tiledGround, options.updatable);
  15614. return tiledGround;
  15615. };
  15616. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15617. var width = options.width || 10;
  15618. var height = options.height || 10;
  15619. var subdivisions = options.subdivisions || 1;
  15620. var minHeight = options.minHeight;
  15621. var maxHeight = options.maxHeight || 10;
  15622. var updatable = options.updatable;
  15623. var onReady = options.onReady;
  15624. var ground = new BABYLON.GroundMesh(name, scene);
  15625. ground._subdivisions = subdivisions;
  15626. ground._setReady(false);
  15627. var onload = function (img) {
  15628. // Getting height map data
  15629. var canvas = document.createElement("canvas");
  15630. var context = canvas.getContext("2d");
  15631. var bufferWidth = img.width;
  15632. var bufferHeight = img.height;
  15633. canvas.width = bufferWidth;
  15634. canvas.height = bufferHeight;
  15635. context.drawImage(img, 0, 0);
  15636. // Create VertexData from map data
  15637. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15638. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15639. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15640. width: width, height: height,
  15641. subdivisions: subdivisions,
  15642. minHeight: minHeight, maxHeight: maxHeight,
  15643. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15644. });
  15645. vertexData.applyToMesh(ground, updatable);
  15646. ground._setReady(true);
  15647. //execute ready callback, if set
  15648. if (onReady) {
  15649. onReady(ground);
  15650. }
  15651. };
  15652. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15653. return ground;
  15654. };
  15655. MeshBuilder.CreateTube = function (name, options, scene) {
  15656. var path = options.path;
  15657. var radius = options.radius || 1;
  15658. var tessellation = options.tessellation || 64;
  15659. var radiusFunction = options.radiusFunction;
  15660. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15661. var updatable = options.updatable;
  15662. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15663. var instance = options.instance;
  15664. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15665. // tube geometry
  15666. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15667. var tangents = path3D.getTangents();
  15668. var normals = path3D.getNormals();
  15669. var distances = path3D.getDistances();
  15670. var pi2 = Math.PI * 2;
  15671. var step = pi2 / tessellation * arc;
  15672. var returnRadius = function () { return radius; };
  15673. var radiusFunctionFinal = radiusFunction || returnRadius;
  15674. var circlePath;
  15675. var rad;
  15676. var normal;
  15677. var rotated;
  15678. var rotationMatrix = BABYLON.Matrix.Zero();
  15679. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15680. for (var i = 0; i < path.length; i++) {
  15681. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15682. circlePath = Array(); // current circle array
  15683. normal = normals[i]; // current normal
  15684. for (var t = 0; t < tessellation; t++) {
  15685. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15686. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15687. circlePath.push(rotated);
  15688. }
  15689. circlePaths[index] = circlePath;
  15690. index++;
  15691. }
  15692. // cap
  15693. var capPath = function (nbPoints, pathIndex) {
  15694. var pointCap = Array();
  15695. for (var i = 0; i < nbPoints; i++) {
  15696. pointCap.push(path[pathIndex]);
  15697. }
  15698. return pointCap;
  15699. };
  15700. switch (cap) {
  15701. case BABYLON.Mesh.NO_CAP:
  15702. break;
  15703. case BABYLON.Mesh.CAP_START:
  15704. circlePaths[0] = capPath(tessellation, 0);
  15705. circlePaths[1] = circlePaths[2].slice(0);
  15706. break;
  15707. case BABYLON.Mesh.CAP_END:
  15708. circlePaths[index] = circlePaths[index - 1].slice(0);
  15709. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15710. break;
  15711. case BABYLON.Mesh.CAP_ALL:
  15712. circlePaths[0] = capPath(tessellation, 0);
  15713. circlePaths[1] = circlePaths[2].slice(0);
  15714. circlePaths[index] = circlePaths[index - 1].slice(0);
  15715. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15716. break;
  15717. default:
  15718. break;
  15719. }
  15720. return circlePaths;
  15721. };
  15722. var path3D;
  15723. var pathArray;
  15724. if (instance) {
  15725. var arc = options.arc || instance.arc;
  15726. path3D = (instance.path3D).update(path);
  15727. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15728. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15729. instance.path3D = path3D;
  15730. instance.pathArray = pathArray;
  15731. instance.arc = arc;
  15732. return instance;
  15733. }
  15734. // tube creation
  15735. path3D = new BABYLON.Path3D(path);
  15736. var newPathArray = new Array();
  15737. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15738. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15739. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15740. tube.pathArray = pathArray;
  15741. tube.path3D = path3D;
  15742. tube.tessellation = tessellation;
  15743. tube.cap = cap;
  15744. tube.arc = options.arc;
  15745. return tube;
  15746. };
  15747. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15748. var polyhedron = new BABYLON.Mesh(name, scene);
  15749. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15750. vertexData.applyToMesh(polyhedron, options.updatable);
  15751. return polyhedron;
  15752. };
  15753. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15754. var indices = sourceMesh.getIndices();
  15755. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15756. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15757. var position = options.position || BABYLON.Vector3.Zero();
  15758. var normal = options.normal || BABYLON.Vector3.Up();
  15759. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15760. var angle = options.angle || 0;
  15761. // Getting correct rotation
  15762. if (!normal) {
  15763. var target = new BABYLON.Vector3(0, 0, 1);
  15764. var camera = sourceMesh.getScene().activeCamera;
  15765. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15766. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15767. }
  15768. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15769. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15770. var pitch = Math.atan2(normal.y, len);
  15771. // Matrix
  15772. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15773. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15774. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15775. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15776. var vertexData = new BABYLON.VertexData();
  15777. vertexData.indices = [];
  15778. vertexData.positions = [];
  15779. vertexData.normals = [];
  15780. vertexData.uvs = [];
  15781. var currentVertexDataIndex = 0;
  15782. var extractDecalVector3 = function (indexId) {
  15783. var vertexId = indices[indexId];
  15784. var result = new BABYLON.PositionNormalVertex();
  15785. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15786. // Send vector to decal local world
  15787. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15788. // Get normal
  15789. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15790. return result;
  15791. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15792. var clip = function (vertices, axis) {
  15793. if (vertices.length === 0) {
  15794. return vertices;
  15795. }
  15796. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15797. var clipVertices = function (v0, v1) {
  15798. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15799. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15800. };
  15801. var result = new Array();
  15802. for (var index = 0; index < vertices.length; index += 3) {
  15803. var v1Out;
  15804. var v2Out;
  15805. var v3Out;
  15806. var total = 0;
  15807. var nV1, nV2, nV3, nV4;
  15808. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15809. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15810. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15811. v1Out = d1 > 0;
  15812. v2Out = d2 > 0;
  15813. v3Out = d3 > 0;
  15814. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15815. switch (total) {
  15816. case 0:
  15817. result.push(vertices[index]);
  15818. result.push(vertices[index + 1]);
  15819. result.push(vertices[index + 2]);
  15820. break;
  15821. case 1:
  15822. if (v1Out) {
  15823. nV1 = vertices[index + 1];
  15824. nV2 = vertices[index + 2];
  15825. nV3 = clipVertices(vertices[index], nV1);
  15826. nV4 = clipVertices(vertices[index], nV2);
  15827. }
  15828. if (v2Out) {
  15829. nV1 = vertices[index];
  15830. nV2 = vertices[index + 2];
  15831. nV3 = clipVertices(vertices[index + 1], nV1);
  15832. nV4 = clipVertices(vertices[index + 1], nV2);
  15833. result.push(nV3);
  15834. result.push(nV2.clone());
  15835. result.push(nV1.clone());
  15836. result.push(nV2.clone());
  15837. result.push(nV3.clone());
  15838. result.push(nV4);
  15839. break;
  15840. }
  15841. if (v3Out) {
  15842. nV1 = vertices[index];
  15843. nV2 = vertices[index + 1];
  15844. nV3 = clipVertices(vertices[index + 2], nV1);
  15845. nV4 = clipVertices(vertices[index + 2], nV2);
  15846. }
  15847. result.push(nV1.clone());
  15848. result.push(nV2.clone());
  15849. result.push(nV3);
  15850. result.push(nV4);
  15851. result.push(nV3.clone());
  15852. result.push(nV2.clone());
  15853. break;
  15854. case 2:
  15855. if (!v1Out) {
  15856. nV1 = vertices[index].clone();
  15857. nV2 = clipVertices(nV1, vertices[index + 1]);
  15858. nV3 = clipVertices(nV1, vertices[index + 2]);
  15859. result.push(nV1);
  15860. result.push(nV2);
  15861. result.push(nV3);
  15862. }
  15863. if (!v2Out) {
  15864. nV1 = vertices[index + 1].clone();
  15865. nV2 = clipVertices(nV1, vertices[index + 2]);
  15866. nV3 = clipVertices(nV1, vertices[index]);
  15867. result.push(nV1);
  15868. result.push(nV2);
  15869. result.push(nV3);
  15870. }
  15871. if (!v3Out) {
  15872. nV1 = vertices[index + 2].clone();
  15873. nV2 = clipVertices(nV1, vertices[index]);
  15874. nV3 = clipVertices(nV1, vertices[index + 1]);
  15875. result.push(nV1);
  15876. result.push(nV2);
  15877. result.push(nV3);
  15878. }
  15879. break;
  15880. case 3:
  15881. break;
  15882. }
  15883. }
  15884. return result;
  15885. };
  15886. for (var index = 0; index < indices.length; index += 3) {
  15887. var faceVertices = new Array();
  15888. faceVertices.push(extractDecalVector3(index));
  15889. faceVertices.push(extractDecalVector3(index + 1));
  15890. faceVertices.push(extractDecalVector3(index + 2));
  15891. // Clip
  15892. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15893. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15894. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15895. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15896. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15897. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15898. if (faceVertices.length === 0) {
  15899. continue;
  15900. }
  15901. // Add UVs and get back to world
  15902. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15903. var vertex = faceVertices[vIndex];
  15904. vertexData.indices.push(currentVertexDataIndex);
  15905. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15906. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15907. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15908. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15909. currentVertexDataIndex++;
  15910. }
  15911. }
  15912. // Return mesh
  15913. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  15914. vertexData.applyToMesh(decal);
  15915. decal.position = position.clone();
  15916. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15917. return decal;
  15918. };
  15919. // Privates
  15920. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15921. // extrusion geometry
  15922. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15923. var tangents = path3D.getTangents();
  15924. var normals = path3D.getNormals();
  15925. var binormals = path3D.getBinormals();
  15926. var distances = path3D.getDistances();
  15927. var angle = 0;
  15928. var returnScale = function () { return scale; };
  15929. var returnRotation = function () { return rotation; };
  15930. var rotate = custom ? rotateFunction : returnRotation;
  15931. var scl = custom ? scaleFunction : returnScale;
  15932. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15933. var rotationMatrix = BABYLON.Matrix.Zero();
  15934. for (var i = 0; i < curve.length; i++) {
  15935. var shapePath = new Array();
  15936. var angleStep = rotate(i, distances[i]);
  15937. var scaleRatio = scl(i, distances[i]);
  15938. for (var p = 0; p < shape.length; p++) {
  15939. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  15940. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15941. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15942. shapePath.push(rotated);
  15943. }
  15944. shapePaths[index] = shapePath;
  15945. angle += angleStep;
  15946. index++;
  15947. }
  15948. // cap
  15949. var capPath = function (shapePath) {
  15950. var pointCap = Array();
  15951. var barycenter = BABYLON.Vector3.Zero();
  15952. var i;
  15953. for (i = 0; i < shapePath.length; i++) {
  15954. barycenter.addInPlace(shapePath[i]);
  15955. }
  15956. barycenter.scaleInPlace(1 / shapePath.length);
  15957. for (i = 0; i < shapePath.length; i++) {
  15958. pointCap.push(barycenter);
  15959. }
  15960. return pointCap;
  15961. };
  15962. switch (cap) {
  15963. case BABYLON.Mesh.NO_CAP:
  15964. break;
  15965. case BABYLON.Mesh.CAP_START:
  15966. shapePaths[0] = capPath(shapePaths[2]);
  15967. shapePaths[1] = shapePaths[2].slice(0);
  15968. break;
  15969. case BABYLON.Mesh.CAP_END:
  15970. shapePaths[index] = shapePaths[index - 1];
  15971. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15972. break;
  15973. case BABYLON.Mesh.CAP_ALL:
  15974. shapePaths[0] = capPath(shapePaths[2]);
  15975. shapePaths[1] = shapePaths[2].slice(0);
  15976. shapePaths[index] = shapePaths[index - 1];
  15977. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15978. break;
  15979. default:
  15980. break;
  15981. }
  15982. return shapePaths;
  15983. };
  15984. var path3D;
  15985. var pathArray;
  15986. if (instance) {
  15987. path3D = (instance.path3D).update(curve);
  15988. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15989. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15990. return instance;
  15991. }
  15992. // extruded shape creation
  15993. path3D = new BABYLON.Path3D(curve);
  15994. var newShapePaths = new Array();
  15995. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15996. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15997. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15998. extrudedGeneric.pathArray = pathArray;
  15999. extrudedGeneric.path3D = path3D;
  16000. extrudedGeneric.cap = cap;
  16001. return extrudedGeneric;
  16002. };
  16003. return MeshBuilder;
  16004. })();
  16005. BABYLON.MeshBuilder = MeshBuilder;
  16006. })(BABYLON || (BABYLON = {}));
  16007. var BABYLON;
  16008. (function (BABYLON) {
  16009. var BaseTexture = (function () {
  16010. function BaseTexture(scene) {
  16011. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16012. this.hasAlpha = false;
  16013. this.getAlphaFromRGB = false;
  16014. this.level = 1;
  16015. this.isCube = false;
  16016. this.isRenderTarget = false;
  16017. this.animations = new Array();
  16018. this.coordinatesIndex = 0;
  16019. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16020. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16021. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16022. this.anisotropicFilteringLevel = 4;
  16023. this._scene = scene;
  16024. this._scene.textures.push(this);
  16025. }
  16026. BaseTexture.prototype.getScene = function () {
  16027. return this._scene;
  16028. };
  16029. BaseTexture.prototype.getTextureMatrix = function () {
  16030. return null;
  16031. };
  16032. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16033. return null;
  16034. };
  16035. BaseTexture.prototype.getInternalTexture = function () {
  16036. return this._texture;
  16037. };
  16038. BaseTexture.prototype.isReady = function () {
  16039. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16040. return true;
  16041. }
  16042. if (this._texture) {
  16043. return this._texture.isReady;
  16044. }
  16045. return false;
  16046. };
  16047. BaseTexture.prototype.getSize = function () {
  16048. if (this._texture._width) {
  16049. return { width: this._texture._width, height: this._texture._height };
  16050. }
  16051. if (this._texture._size) {
  16052. return { width: this._texture._size, height: this._texture._size };
  16053. }
  16054. return { width: 0, height: 0 };
  16055. };
  16056. BaseTexture.prototype.getBaseSize = function () {
  16057. if (!this.isReady())
  16058. return { width: 0, height: 0 };
  16059. if (this._texture._size) {
  16060. return { width: this._texture._size, height: this._texture._size };
  16061. }
  16062. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16063. };
  16064. BaseTexture.prototype.scale = function (ratio) {
  16065. };
  16066. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16067. get: function () {
  16068. return false;
  16069. },
  16070. enumerable: true,
  16071. configurable: true
  16072. });
  16073. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16074. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16075. for (var index = 0; index < texturesCache.length; index++) {
  16076. var texturesCacheEntry = texturesCache[index];
  16077. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16078. texturesCache.splice(index, 1);
  16079. return;
  16080. }
  16081. }
  16082. };
  16083. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16084. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16085. for (var index = 0; index < texturesCache.length; index++) {
  16086. var texturesCacheEntry = texturesCache[index];
  16087. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16088. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16089. texturesCacheEntry.references++;
  16090. return texturesCacheEntry;
  16091. }
  16092. }
  16093. }
  16094. return null;
  16095. };
  16096. BaseTexture.prototype.delayLoad = function () {
  16097. };
  16098. BaseTexture.prototype.clone = function () {
  16099. return null;
  16100. };
  16101. BaseTexture.prototype.releaseInternalTexture = function () {
  16102. if (this._texture) {
  16103. this._scene.getEngine().releaseInternalTexture(this._texture);
  16104. delete this._texture;
  16105. }
  16106. };
  16107. BaseTexture.prototype.dispose = function () {
  16108. // Animations
  16109. this.getScene().stopAnimation(this);
  16110. // Remove from scene
  16111. var index = this._scene.textures.indexOf(this);
  16112. if (index >= 0) {
  16113. this._scene.textures.splice(index, 1);
  16114. }
  16115. if (this._texture === undefined) {
  16116. return;
  16117. }
  16118. // Callback
  16119. if (this.onDispose) {
  16120. this.onDispose();
  16121. }
  16122. };
  16123. return BaseTexture;
  16124. })();
  16125. BABYLON.BaseTexture = BaseTexture;
  16126. })(BABYLON || (BABYLON = {}));
  16127. var BABYLON;
  16128. (function (BABYLON) {
  16129. var Texture = (function (_super) {
  16130. __extends(Texture, _super);
  16131. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16132. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16133. if (onLoad === void 0) { onLoad = null; }
  16134. if (onError === void 0) { onError = null; }
  16135. if (buffer === void 0) { buffer = null; }
  16136. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16137. _super.call(this, scene);
  16138. this.uOffset = 0;
  16139. this.vOffset = 0;
  16140. this.uScale = 1.0;
  16141. this.vScale = 1.0;
  16142. this.uAng = 0;
  16143. this.vAng = 0;
  16144. this.wAng = 0;
  16145. this.name = url;
  16146. this.url = url;
  16147. this._noMipmap = noMipmap;
  16148. this._invertY = invertY;
  16149. this._samplingMode = samplingMode;
  16150. this._buffer = buffer;
  16151. this._deleteBuffer = deleteBuffer;
  16152. if (!url) {
  16153. return;
  16154. }
  16155. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16156. if (!this._texture) {
  16157. if (!scene.useDelayedTextureLoading) {
  16158. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16159. if (deleteBuffer) {
  16160. delete this._buffer;
  16161. }
  16162. }
  16163. else {
  16164. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16165. }
  16166. }
  16167. else {
  16168. BABYLON.Tools.SetImmediate(function () {
  16169. if (onLoad) {
  16170. onLoad();
  16171. }
  16172. });
  16173. }
  16174. }
  16175. Texture.prototype.delayLoad = function () {
  16176. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16177. return;
  16178. }
  16179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16180. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16181. if (!this._texture) {
  16182. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16183. if (this._deleteBuffer) {
  16184. delete this._buffer;
  16185. }
  16186. }
  16187. };
  16188. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16189. if (!this._texture) {
  16190. return;
  16191. }
  16192. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16193. };
  16194. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16195. x *= this.uScale;
  16196. y *= this.vScale;
  16197. x -= 0.5 * this.uScale;
  16198. y -= 0.5 * this.vScale;
  16199. z -= 0.5;
  16200. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16201. t.x += 0.5 * this.uScale + this.uOffset;
  16202. t.y += 0.5 * this.vScale + this.vOffset;
  16203. t.z += 0.5;
  16204. };
  16205. Texture.prototype.getTextureMatrix = function () {
  16206. if (this.uOffset === this._cachedUOffset &&
  16207. this.vOffset === this._cachedVOffset &&
  16208. this.uScale === this._cachedUScale &&
  16209. this.vScale === this._cachedVScale &&
  16210. this.uAng === this._cachedUAng &&
  16211. this.vAng === this._cachedVAng &&
  16212. this.wAng === this._cachedWAng) {
  16213. return this._cachedTextureMatrix;
  16214. }
  16215. this._cachedUOffset = this.uOffset;
  16216. this._cachedVOffset = this.vOffset;
  16217. this._cachedUScale = this.uScale;
  16218. this._cachedVScale = this.vScale;
  16219. this._cachedUAng = this.uAng;
  16220. this._cachedVAng = this.vAng;
  16221. this._cachedWAng = this.wAng;
  16222. if (!this._cachedTextureMatrix) {
  16223. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16224. this._rowGenerationMatrix = new BABYLON.Matrix();
  16225. this._t0 = BABYLON.Vector3.Zero();
  16226. this._t1 = BABYLON.Vector3.Zero();
  16227. this._t2 = BABYLON.Vector3.Zero();
  16228. }
  16229. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16230. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16231. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16232. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16233. this._t1.subtractInPlace(this._t0);
  16234. this._t2.subtractInPlace(this._t0);
  16235. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16236. this._cachedTextureMatrix.m[0] = this._t1.x;
  16237. this._cachedTextureMatrix.m[1] = this._t1.y;
  16238. this._cachedTextureMatrix.m[2] = this._t1.z;
  16239. this._cachedTextureMatrix.m[4] = this._t2.x;
  16240. this._cachedTextureMatrix.m[5] = this._t2.y;
  16241. this._cachedTextureMatrix.m[6] = this._t2.z;
  16242. this._cachedTextureMatrix.m[8] = this._t0.x;
  16243. this._cachedTextureMatrix.m[9] = this._t0.y;
  16244. this._cachedTextureMatrix.m[10] = this._t0.z;
  16245. return this._cachedTextureMatrix;
  16246. };
  16247. Texture.prototype.getReflectionTextureMatrix = function () {
  16248. if (this.uOffset === this._cachedUOffset &&
  16249. this.vOffset === this._cachedVOffset &&
  16250. this.uScale === this._cachedUScale &&
  16251. this.vScale === this._cachedVScale &&
  16252. this.coordinatesMode === this._cachedCoordinatesMode) {
  16253. return this._cachedTextureMatrix;
  16254. }
  16255. if (!this._cachedTextureMatrix) {
  16256. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16257. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16258. }
  16259. this._cachedCoordinatesMode = this.coordinatesMode;
  16260. switch (this.coordinatesMode) {
  16261. case Texture.PLANAR_MODE:
  16262. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16263. this._cachedTextureMatrix[0] = this.uScale;
  16264. this._cachedTextureMatrix[5] = this.vScale;
  16265. this._cachedTextureMatrix[12] = this.uOffset;
  16266. this._cachedTextureMatrix[13] = this.vOffset;
  16267. break;
  16268. case Texture.PROJECTION_MODE:
  16269. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16270. this._projectionModeMatrix.m[0] = 0.5;
  16271. this._projectionModeMatrix.m[5] = -0.5;
  16272. this._projectionModeMatrix.m[10] = 0.0;
  16273. this._projectionModeMatrix.m[12] = 0.5;
  16274. this._projectionModeMatrix.m[13] = 0.5;
  16275. this._projectionModeMatrix.m[14] = 1.0;
  16276. this._projectionModeMatrix.m[15] = 1.0;
  16277. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16278. break;
  16279. default:
  16280. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16281. break;
  16282. }
  16283. return this._cachedTextureMatrix;
  16284. };
  16285. Texture.prototype.clone = function () {
  16286. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16287. // Base texture
  16288. newTexture.hasAlpha = this.hasAlpha;
  16289. newTexture.level = this.level;
  16290. newTexture.wrapU = this.wrapU;
  16291. newTexture.wrapV = this.wrapV;
  16292. newTexture.coordinatesIndex = this.coordinatesIndex;
  16293. newTexture.coordinatesMode = this.coordinatesMode;
  16294. // Texture
  16295. newTexture.uOffset = this.uOffset;
  16296. newTexture.vOffset = this.vOffset;
  16297. newTexture.uScale = this.uScale;
  16298. newTexture.vScale = this.vScale;
  16299. newTexture.uAng = this.uAng;
  16300. newTexture.vAng = this.vAng;
  16301. newTexture.wAng = this.wAng;
  16302. return newTexture;
  16303. };
  16304. // Statics
  16305. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16306. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16307. if (onLoad === void 0) { onLoad = null; }
  16308. if (onError === void 0) { onError = null; }
  16309. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16310. };
  16311. // Constants
  16312. Texture.NEAREST_SAMPLINGMODE = 1;
  16313. Texture.BILINEAR_SAMPLINGMODE = 2;
  16314. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16315. Texture.EXPLICIT_MODE = 0;
  16316. Texture.SPHERICAL_MODE = 1;
  16317. Texture.PLANAR_MODE = 2;
  16318. Texture.CUBIC_MODE = 3;
  16319. Texture.PROJECTION_MODE = 4;
  16320. Texture.SKYBOX_MODE = 5;
  16321. Texture.INVCUBIC_MODE = 6;
  16322. Texture.EQUIRECTANGULAR_MODE = 7;
  16323. Texture.CLAMP_ADDRESSMODE = 0;
  16324. Texture.WRAP_ADDRESSMODE = 1;
  16325. Texture.MIRROR_ADDRESSMODE = 2;
  16326. return Texture;
  16327. })(BABYLON.BaseTexture);
  16328. BABYLON.Texture = Texture;
  16329. })(BABYLON || (BABYLON = {}));
  16330. var BABYLON;
  16331. (function (BABYLON) {
  16332. var CubeTexture = (function (_super) {
  16333. __extends(CubeTexture, _super);
  16334. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16335. _super.call(this, scene);
  16336. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16337. this.name = rootUrl;
  16338. this.url = rootUrl;
  16339. this._noMipmap = noMipmap;
  16340. this.hasAlpha = false;
  16341. if (!rootUrl) {
  16342. return;
  16343. }
  16344. this._texture = this._getFromCache(rootUrl, noMipmap);
  16345. if (!extensions) {
  16346. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16347. }
  16348. this._extensions = extensions;
  16349. if (!this._texture) {
  16350. if (!scene.useDelayedTextureLoading) {
  16351. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16352. }
  16353. else {
  16354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16355. }
  16356. }
  16357. this.isCube = true;
  16358. this._textureMatrix = BABYLON.Matrix.Identity();
  16359. }
  16360. CubeTexture.prototype.clone = function () {
  16361. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16362. // Base texture
  16363. newTexture.level = this.level;
  16364. newTexture.wrapU = this.wrapU;
  16365. newTexture.wrapV = this.wrapV;
  16366. newTexture.coordinatesIndex = this.coordinatesIndex;
  16367. newTexture.coordinatesMode = this.coordinatesMode;
  16368. return newTexture;
  16369. };
  16370. // Methods
  16371. CubeTexture.prototype.delayLoad = function () {
  16372. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16373. return;
  16374. }
  16375. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16376. this._texture = this._getFromCache(this.url, this._noMipmap);
  16377. if (!this._texture) {
  16378. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16379. }
  16380. };
  16381. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16382. return this._textureMatrix;
  16383. };
  16384. return CubeTexture;
  16385. })(BABYLON.BaseTexture);
  16386. BABYLON.CubeTexture = CubeTexture;
  16387. })(BABYLON || (BABYLON = {}));
  16388. var BABYLON;
  16389. (function (BABYLON) {
  16390. var RenderTargetTexture = (function (_super) {
  16391. __extends(RenderTargetTexture, _super);
  16392. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16393. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16394. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16395. if (isCube === void 0) { isCube = false; }
  16396. _super.call(this, null, scene, !generateMipMaps);
  16397. this.isCube = isCube;
  16398. this.renderList = new Array();
  16399. this.renderParticles = true;
  16400. this.renderSprites = false;
  16401. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16402. this._currentRefreshId = -1;
  16403. this._refreshRate = 1;
  16404. this.name = name;
  16405. this.isRenderTarget = true;
  16406. this._size = size;
  16407. this._generateMipMaps = generateMipMaps;
  16408. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16409. if (isCube) {
  16410. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16411. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16412. this._textureMatrix = BABYLON.Matrix.Identity();
  16413. }
  16414. else {
  16415. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16416. }
  16417. // Rendering groups
  16418. this._renderingManager = new BABYLON.RenderingManager(scene);
  16419. }
  16420. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16421. get: function () {
  16422. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16423. },
  16424. enumerable: true,
  16425. configurable: true
  16426. });
  16427. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16428. get: function () {
  16429. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16430. },
  16431. enumerable: true,
  16432. configurable: true
  16433. });
  16434. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16435. get: function () {
  16436. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16442. this._currentRefreshId = -1;
  16443. };
  16444. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16445. get: function () {
  16446. return this._refreshRate;
  16447. },
  16448. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16449. set: function (value) {
  16450. this._refreshRate = value;
  16451. this.resetRefreshCounter();
  16452. },
  16453. enumerable: true,
  16454. configurable: true
  16455. });
  16456. RenderTargetTexture.prototype._shouldRender = function () {
  16457. if (this._currentRefreshId === -1) {
  16458. this._currentRefreshId = 1;
  16459. return true;
  16460. }
  16461. if (this.refreshRate === this._currentRefreshId) {
  16462. this._currentRefreshId = 1;
  16463. return true;
  16464. }
  16465. this._currentRefreshId++;
  16466. return false;
  16467. };
  16468. RenderTargetTexture.prototype.isReady = function () {
  16469. if (!this.getScene().renderTargetsEnabled) {
  16470. return false;
  16471. }
  16472. return _super.prototype.isReady.call(this);
  16473. };
  16474. RenderTargetTexture.prototype.getRenderSize = function () {
  16475. return this._size;
  16476. };
  16477. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16478. get: function () {
  16479. return true;
  16480. },
  16481. enumerable: true,
  16482. configurable: true
  16483. });
  16484. RenderTargetTexture.prototype.scale = function (ratio) {
  16485. var newSize = this._size * ratio;
  16486. this.resize(newSize, this._generateMipMaps);
  16487. };
  16488. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16489. if (this.isCube) {
  16490. return this._textureMatrix;
  16491. }
  16492. return _super.prototype.getReflectionTextureMatrix.call(this);
  16493. };
  16494. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16495. this.releaseInternalTexture();
  16496. if (this.isCube) {
  16497. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16498. }
  16499. else {
  16500. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16501. }
  16502. };
  16503. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16504. var scene = this.getScene();
  16505. if (this._waitingRenderList) {
  16506. this.renderList = [];
  16507. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16508. var id = this._waitingRenderList[index];
  16509. this.renderList.push(scene.getMeshByID(id));
  16510. }
  16511. delete this._waitingRenderList;
  16512. }
  16513. if (this.renderList && this.renderList.length === 0) {
  16514. return;
  16515. }
  16516. // Prepare renderingManager
  16517. this._renderingManager.reset();
  16518. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16519. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16520. var mesh = currentRenderList[meshIndex];
  16521. if (mesh) {
  16522. if (!mesh.isReady()) {
  16523. // Reset _currentRefreshId
  16524. this.resetRefreshCounter();
  16525. continue;
  16526. }
  16527. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16528. mesh._activate(scene.getRenderId());
  16529. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16530. var subMesh = mesh.subMeshes[subIndex];
  16531. scene._activeIndices += subMesh.indexCount;
  16532. this._renderingManager.dispatch(subMesh);
  16533. }
  16534. }
  16535. }
  16536. }
  16537. if (this.isCube) {
  16538. for (var face = 0; face < 6; face++) {
  16539. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16540. }
  16541. }
  16542. else {
  16543. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16544. }
  16545. if (this.onAfterUnbind) {
  16546. this.onAfterUnbind();
  16547. }
  16548. scene.resetCachedMaterial();
  16549. };
  16550. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16551. var scene = this.getScene();
  16552. var engine = scene.getEngine();
  16553. // Bind
  16554. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16555. if (this.isCube) {
  16556. engine.bindFramebuffer(this._texture, faceIndex);
  16557. }
  16558. else {
  16559. engine.bindFramebuffer(this._texture);
  16560. }
  16561. }
  16562. if (this.onBeforeRender) {
  16563. this.onBeforeRender(faceIndex);
  16564. }
  16565. // Clear
  16566. if (this.onClear) {
  16567. this.onClear(engine);
  16568. }
  16569. else {
  16570. engine.clear(scene.clearColor, true, true);
  16571. }
  16572. if (!this._doNotChangeAspectRatio) {
  16573. scene.updateTransformMatrix(true);
  16574. }
  16575. // Render
  16576. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16577. if (useCameraPostProcess) {
  16578. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16579. }
  16580. if (!this._doNotChangeAspectRatio) {
  16581. scene.updateTransformMatrix(true);
  16582. }
  16583. if (this.onAfterRender) {
  16584. this.onAfterRender(faceIndex);
  16585. }
  16586. // Dump ?
  16587. if (dumpForDebug) {
  16588. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16589. }
  16590. // Unbind
  16591. if (!this.isCube || faceIndex === 5) {
  16592. if (this.isCube) {
  16593. if (faceIndex === 5) {
  16594. engine.generateMipMapsForCubemap(this._texture);
  16595. }
  16596. }
  16597. engine.unBindFramebuffer(this._texture, this.isCube);
  16598. }
  16599. };
  16600. RenderTargetTexture.prototype.clone = function () {
  16601. var textureSize = this.getSize();
  16602. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16603. // Base texture
  16604. newTexture.hasAlpha = this.hasAlpha;
  16605. newTexture.level = this.level;
  16606. // RenderTarget Texture
  16607. newTexture.coordinatesMode = this.coordinatesMode;
  16608. newTexture.renderList = this.renderList.slice(0);
  16609. return newTexture;
  16610. };
  16611. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16612. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16613. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16614. return RenderTargetTexture;
  16615. })(BABYLON.Texture);
  16616. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16617. })(BABYLON || (BABYLON = {}));
  16618. var BABYLON;
  16619. (function (BABYLON) {
  16620. var ProceduralTexture = (function (_super) {
  16621. __extends(ProceduralTexture, _super);
  16622. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16624. _super.call(this, null, scene, !generateMipMaps);
  16625. this.isEnabled = true;
  16626. this._currentRefreshId = -1;
  16627. this._refreshRate = 1;
  16628. this._vertexDeclaration = [2];
  16629. this._vertexStrideSize = 2 * 4;
  16630. this._uniforms = new Array();
  16631. this._samplers = new Array();
  16632. this._textures = new Array();
  16633. this._floats = new Array();
  16634. this._floatsArrays = {};
  16635. this._colors3 = new Array();
  16636. this._colors4 = new Array();
  16637. this._vectors2 = new Array();
  16638. this._vectors3 = new Array();
  16639. this._matrices = new Array();
  16640. this._fallbackTextureUsed = false;
  16641. scene._proceduralTextures.push(this);
  16642. this.name = name;
  16643. this.isRenderTarget = true;
  16644. this._size = size;
  16645. this._generateMipMaps = generateMipMaps;
  16646. this.setFragment(fragment);
  16647. this._fallbackTexture = fallbackTexture;
  16648. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16649. // VBO
  16650. var vertices = [];
  16651. vertices.push(1, 1);
  16652. vertices.push(-1, 1);
  16653. vertices.push(-1, -1);
  16654. vertices.push(1, -1);
  16655. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16656. // Indices
  16657. var indices = [];
  16658. indices.push(0);
  16659. indices.push(1);
  16660. indices.push(2);
  16661. indices.push(0);
  16662. indices.push(2);
  16663. indices.push(3);
  16664. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16665. }
  16666. ProceduralTexture.prototype.reset = function () {
  16667. if (this._effect === undefined) {
  16668. return;
  16669. }
  16670. var engine = this.getScene().getEngine();
  16671. engine._releaseEffect(this._effect);
  16672. };
  16673. ProceduralTexture.prototype.isReady = function () {
  16674. var _this = this;
  16675. var engine = this.getScene().getEngine();
  16676. var shaders;
  16677. if (!this._fragment) {
  16678. return false;
  16679. }
  16680. if (this._fallbackTextureUsed) {
  16681. return true;
  16682. }
  16683. if (this._fragment.fragmentElement !== undefined) {
  16684. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16685. }
  16686. else {
  16687. shaders = { vertex: "procedural", fragment: this._fragment };
  16688. }
  16689. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16690. _this.releaseInternalTexture();
  16691. if (_this._fallbackTexture) {
  16692. _this._texture = _this._fallbackTexture._texture;
  16693. _this._texture.references++;
  16694. }
  16695. _this._fallbackTextureUsed = true;
  16696. });
  16697. return this._effect.isReady();
  16698. };
  16699. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16700. this._currentRefreshId = -1;
  16701. };
  16702. ProceduralTexture.prototype.setFragment = function (fragment) {
  16703. this._fragment = fragment;
  16704. };
  16705. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16706. get: function () {
  16707. return this._refreshRate;
  16708. },
  16709. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16710. set: function (value) {
  16711. this._refreshRate = value;
  16712. this.resetRefreshCounter();
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. ProceduralTexture.prototype._shouldRender = function () {
  16718. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16719. return false;
  16720. }
  16721. if (this._fallbackTextureUsed) {
  16722. return false;
  16723. }
  16724. if (this._currentRefreshId === -1) {
  16725. this._currentRefreshId = 1;
  16726. return true;
  16727. }
  16728. if (this.refreshRate === this._currentRefreshId) {
  16729. this._currentRefreshId = 1;
  16730. return true;
  16731. }
  16732. this._currentRefreshId++;
  16733. return false;
  16734. };
  16735. ProceduralTexture.prototype.getRenderSize = function () {
  16736. return this._size;
  16737. };
  16738. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16739. if (this._fallbackTextureUsed) {
  16740. return;
  16741. }
  16742. this.releaseInternalTexture();
  16743. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16744. };
  16745. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16746. if (this._uniforms.indexOf(uniformName) === -1) {
  16747. this._uniforms.push(uniformName);
  16748. }
  16749. };
  16750. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16751. if (this._samplers.indexOf(name) === -1) {
  16752. this._samplers.push(name);
  16753. }
  16754. this._textures[name] = texture;
  16755. return this;
  16756. };
  16757. ProceduralTexture.prototype.setFloat = function (name, value) {
  16758. this._checkUniform(name);
  16759. this._floats[name] = value;
  16760. return this;
  16761. };
  16762. ProceduralTexture.prototype.setFloats = function (name, value) {
  16763. this._checkUniform(name);
  16764. this._floatsArrays[name] = value;
  16765. return this;
  16766. };
  16767. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16768. this._checkUniform(name);
  16769. this._colors3[name] = value;
  16770. return this;
  16771. };
  16772. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16773. this._checkUniform(name);
  16774. this._colors4[name] = value;
  16775. return this;
  16776. };
  16777. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16778. this._checkUniform(name);
  16779. this._vectors2[name] = value;
  16780. return this;
  16781. };
  16782. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16783. this._checkUniform(name);
  16784. this._vectors3[name] = value;
  16785. return this;
  16786. };
  16787. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16788. this._checkUniform(name);
  16789. this._matrices[name] = value;
  16790. return this;
  16791. };
  16792. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16793. var scene = this.getScene();
  16794. var engine = scene.getEngine();
  16795. engine.bindFramebuffer(this._texture);
  16796. // Clear
  16797. engine.clear(scene.clearColor, true, true);
  16798. // Render
  16799. engine.enableEffect(this._effect);
  16800. engine.setState(false);
  16801. // Texture
  16802. for (var name in this._textures) {
  16803. this._effect.setTexture(name, this._textures[name]);
  16804. }
  16805. // Float
  16806. for (name in this._floats) {
  16807. this._effect.setFloat(name, this._floats[name]);
  16808. }
  16809. // Floats
  16810. for (name in this._floatsArrays) {
  16811. this._effect.setArray(name, this._floatsArrays[name]);
  16812. }
  16813. // Color3
  16814. for (name in this._colors3) {
  16815. this._effect.setColor3(name, this._colors3[name]);
  16816. }
  16817. // Color4
  16818. for (name in this._colors4) {
  16819. var color = this._colors4[name];
  16820. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16821. }
  16822. // Vector2
  16823. for (name in this._vectors2) {
  16824. this._effect.setVector2(name, this._vectors2[name]);
  16825. }
  16826. // Vector3
  16827. for (name in this._vectors3) {
  16828. this._effect.setVector3(name, this._vectors3[name]);
  16829. }
  16830. // Matrix
  16831. for (name in this._matrices) {
  16832. this._effect.setMatrix(name, this._matrices[name]);
  16833. }
  16834. // VBOs
  16835. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16836. // Draw order
  16837. engine.draw(true, 0, 6);
  16838. // Unbind
  16839. engine.unBindFramebuffer(this._texture);
  16840. };
  16841. ProceduralTexture.prototype.clone = function () {
  16842. var textureSize = this.getSize();
  16843. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16844. // Base texture
  16845. newTexture.hasAlpha = this.hasAlpha;
  16846. newTexture.level = this.level;
  16847. // RenderTarget Texture
  16848. newTexture.coordinatesMode = this.coordinatesMode;
  16849. return newTexture;
  16850. };
  16851. ProceduralTexture.prototype.dispose = function () {
  16852. var index = this.getScene()._proceduralTextures.indexOf(this);
  16853. if (index >= 0) {
  16854. this.getScene()._proceduralTextures.splice(index, 1);
  16855. }
  16856. _super.prototype.dispose.call(this);
  16857. };
  16858. return ProceduralTexture;
  16859. })(BABYLON.Texture);
  16860. BABYLON.ProceduralTexture = ProceduralTexture;
  16861. })(BABYLON || (BABYLON = {}));
  16862. var BABYLON;
  16863. (function (BABYLON) {
  16864. var MirrorTexture = (function (_super) {
  16865. __extends(MirrorTexture, _super);
  16866. function MirrorTexture(name, size, scene, generateMipMaps) {
  16867. var _this = this;
  16868. _super.call(this, name, size, scene, generateMipMaps, true);
  16869. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16870. this._transformMatrix = BABYLON.Matrix.Zero();
  16871. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16872. this.onBeforeRender = function () {
  16873. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16874. _this._savedViewMatrix = scene.getViewMatrix();
  16875. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16876. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16877. scene.clipPlane = _this.mirrorPlane;
  16878. scene.getEngine().cullBackFaces = false;
  16879. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  16880. };
  16881. this.onAfterRender = function () {
  16882. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16883. scene.getEngine().cullBackFaces = true;
  16884. scene._mirroredCameraPosition = null;
  16885. delete scene.clipPlane;
  16886. };
  16887. }
  16888. MirrorTexture.prototype.clone = function () {
  16889. var textureSize = this.getSize();
  16890. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16891. // Base texture
  16892. newTexture.hasAlpha = this.hasAlpha;
  16893. newTexture.level = this.level;
  16894. // Mirror Texture
  16895. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16896. newTexture.renderList = this.renderList.slice(0);
  16897. return newTexture;
  16898. };
  16899. return MirrorTexture;
  16900. })(BABYLON.RenderTargetTexture);
  16901. BABYLON.MirrorTexture = MirrorTexture;
  16902. })(BABYLON || (BABYLON = {}));
  16903. var BABYLON;
  16904. (function (BABYLON) {
  16905. var DynamicTexture = (function (_super) {
  16906. __extends(DynamicTexture, _super);
  16907. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16909. _super.call(this, null, scene, !generateMipMaps);
  16910. this.name = name;
  16911. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16912. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16913. this._generateMipMaps = generateMipMaps;
  16914. if (options.getContext) {
  16915. this._canvas = options;
  16916. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16917. }
  16918. else {
  16919. this._canvas = document.createElement("canvas");
  16920. if (options.width) {
  16921. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16922. }
  16923. else {
  16924. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16925. }
  16926. }
  16927. var textureSize = this.getSize();
  16928. this._canvas.width = textureSize.width;
  16929. this._canvas.height = textureSize.height;
  16930. this._context = this._canvas.getContext("2d");
  16931. }
  16932. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16933. get: function () {
  16934. return true;
  16935. },
  16936. enumerable: true,
  16937. configurable: true
  16938. });
  16939. DynamicTexture.prototype.scale = function (ratio) {
  16940. var textureSize = this.getSize();
  16941. textureSize.width *= ratio;
  16942. textureSize.height *= ratio;
  16943. this._canvas.width = textureSize.width;
  16944. this._canvas.height = textureSize.height;
  16945. this.releaseInternalTexture();
  16946. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16947. };
  16948. DynamicTexture.prototype.getContext = function () {
  16949. return this._context;
  16950. };
  16951. DynamicTexture.prototype.clear = function () {
  16952. var size = this.getSize();
  16953. this._context.fillRect(0, 0, size.width, size.height);
  16954. };
  16955. DynamicTexture.prototype.update = function (invertY) {
  16956. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16957. };
  16958. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16959. if (update === void 0) { update = true; }
  16960. var size = this.getSize();
  16961. if (clearColor) {
  16962. this._context.fillStyle = clearColor;
  16963. this._context.fillRect(0, 0, size.width, size.height);
  16964. }
  16965. this._context.font = font;
  16966. if (x === null) {
  16967. var textSize = this._context.measureText(text);
  16968. x = (size.width - textSize.width) / 2;
  16969. }
  16970. this._context.fillStyle = color;
  16971. this._context.fillText(text, x, y);
  16972. if (update) {
  16973. this.update(invertY);
  16974. }
  16975. };
  16976. DynamicTexture.prototype.clone = function () {
  16977. var textureSize = this.getSize();
  16978. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16979. // Base texture
  16980. newTexture.hasAlpha = this.hasAlpha;
  16981. newTexture.level = this.level;
  16982. // Dynamic Texture
  16983. newTexture.wrapU = this.wrapU;
  16984. newTexture.wrapV = this.wrapV;
  16985. return newTexture;
  16986. };
  16987. return DynamicTexture;
  16988. })(BABYLON.Texture);
  16989. BABYLON.DynamicTexture = DynamicTexture;
  16990. })(BABYLON || (BABYLON = {}));
  16991. var BABYLON;
  16992. (function (BABYLON) {
  16993. var VideoTexture = (function (_super) {
  16994. __extends(VideoTexture, _super);
  16995. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16996. var _this = this;
  16997. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16998. if (invertY === void 0) { invertY = false; }
  16999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17000. _super.call(this, null, scene, !generateMipMaps, invertY);
  17001. this._autoLaunch = true;
  17002. this.name = name;
  17003. this.video = document.createElement("video");
  17004. this.video.autoplay = false;
  17005. this.video.loop = true;
  17006. this.video.addEventListener("canplaythrough", function () {
  17007. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17008. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17009. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17010. }
  17011. else {
  17012. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17013. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17014. generateMipMaps = false;
  17015. }
  17016. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17017. _this._texture.isReady = true;
  17018. });
  17019. urls.forEach(function (url) {
  17020. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17021. var source = document.createElement("source");
  17022. source.src = url;
  17023. _this.video.appendChild(source);
  17024. });
  17025. this._lastUpdate = BABYLON.Tools.Now;
  17026. }
  17027. VideoTexture.prototype.update = function () {
  17028. if (this._autoLaunch) {
  17029. this._autoLaunch = false;
  17030. this.video.play();
  17031. }
  17032. var now = BABYLON.Tools.Now;
  17033. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17034. return false;
  17035. }
  17036. this._lastUpdate = now;
  17037. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17038. return true;
  17039. };
  17040. return VideoTexture;
  17041. })(BABYLON.Texture);
  17042. BABYLON.VideoTexture = VideoTexture;
  17043. })(BABYLON || (BABYLON = {}));
  17044. var BABYLON;
  17045. (function (BABYLON) {
  17046. var CustomProceduralTexture = (function (_super) {
  17047. __extends(CustomProceduralTexture, _super);
  17048. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17049. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17050. this._animate = true;
  17051. this._time = 0;
  17052. this._texturePath = texturePath;
  17053. //Try to load json
  17054. this.loadJson(texturePath);
  17055. this.refreshRate = 1;
  17056. }
  17057. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17058. var _this = this;
  17059. var that = this;
  17060. function noConfigFile() {
  17061. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17062. try {
  17063. that.setFragment(that._texturePath);
  17064. }
  17065. catch (ex) {
  17066. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17067. }
  17068. }
  17069. var configFileUrl = jsonUrl + "/config.json";
  17070. var xhr = new XMLHttpRequest();
  17071. xhr.open("GET", configFileUrl, true);
  17072. xhr.addEventListener("load", function () {
  17073. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17074. try {
  17075. _this._config = JSON.parse(xhr.response);
  17076. _this.updateShaderUniforms();
  17077. _this.updateTextures();
  17078. _this.setFragment(_this._texturePath + "/custom");
  17079. _this._animate = _this._config.animate;
  17080. _this.refreshRate = _this._config.refreshrate;
  17081. }
  17082. catch (ex) {
  17083. noConfigFile();
  17084. }
  17085. }
  17086. else {
  17087. noConfigFile();
  17088. }
  17089. }, false);
  17090. xhr.addEventListener("error", function () {
  17091. noConfigFile();
  17092. }, false);
  17093. try {
  17094. xhr.send();
  17095. }
  17096. catch (ex) {
  17097. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17098. }
  17099. };
  17100. CustomProceduralTexture.prototype.isReady = function () {
  17101. if (!_super.prototype.isReady.call(this)) {
  17102. return false;
  17103. }
  17104. for (var name in this._textures) {
  17105. var texture = this._textures[name];
  17106. if (!texture.isReady()) {
  17107. return false;
  17108. }
  17109. }
  17110. return true;
  17111. };
  17112. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17113. if (this._animate) {
  17114. this._time += this.getScene().getAnimationRatio() * 0.03;
  17115. this.updateShaderUniforms();
  17116. }
  17117. _super.prototype.render.call(this, useCameraPostProcess);
  17118. };
  17119. CustomProceduralTexture.prototype.updateTextures = function () {
  17120. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17121. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17122. }
  17123. };
  17124. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17125. if (this._config) {
  17126. for (var j = 0; j < this._config.uniforms.length; j++) {
  17127. var uniform = this._config.uniforms[j];
  17128. switch (uniform.type) {
  17129. case "float":
  17130. this.setFloat(uniform.name, uniform.value);
  17131. break;
  17132. case "color3":
  17133. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17134. break;
  17135. case "color4":
  17136. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17137. break;
  17138. case "vector2":
  17139. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17140. break;
  17141. case "vector3":
  17142. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17143. break;
  17144. }
  17145. }
  17146. }
  17147. this.setFloat("time", this._time);
  17148. };
  17149. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17150. get: function () {
  17151. return this._animate;
  17152. },
  17153. set: function (value) {
  17154. this._animate = value;
  17155. },
  17156. enumerable: true,
  17157. configurable: true
  17158. });
  17159. return CustomProceduralTexture;
  17160. })(BABYLON.ProceduralTexture);
  17161. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17162. })(BABYLON || (BABYLON = {}));
  17163. var BABYLON;
  17164. (function (BABYLON) {
  17165. var WoodProceduralTexture = (function (_super) {
  17166. __extends(WoodProceduralTexture, _super);
  17167. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17168. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17169. this._ampScale = 100.0;
  17170. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17171. this.updateShaderUniforms();
  17172. this.refreshRate = 0;
  17173. }
  17174. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17175. this.setFloat("ampScale", this._ampScale);
  17176. this.setColor3("woodColor", this._woodColor);
  17177. };
  17178. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17179. get: function () {
  17180. return this._ampScale;
  17181. },
  17182. set: function (value) {
  17183. this._ampScale = value;
  17184. this.updateShaderUniforms();
  17185. },
  17186. enumerable: true,
  17187. configurable: true
  17188. });
  17189. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17190. get: function () {
  17191. return this._woodColor;
  17192. },
  17193. set: function (value) {
  17194. this._woodColor = value;
  17195. this.updateShaderUniforms();
  17196. },
  17197. enumerable: true,
  17198. configurable: true
  17199. });
  17200. return WoodProceduralTexture;
  17201. })(BABYLON.ProceduralTexture);
  17202. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17203. var FireProceduralTexture = (function (_super) {
  17204. __extends(FireProceduralTexture, _super);
  17205. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17206. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17207. this._time = 0.0;
  17208. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17209. this._autoGenerateTime = true;
  17210. this._alphaThreshold = 0.5;
  17211. this._fireColors = FireProceduralTexture.RedFireColors;
  17212. this.updateShaderUniforms();
  17213. this.refreshRate = 1;
  17214. }
  17215. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17216. this.setFloat("time", this._time);
  17217. this.setVector2("speed", this._speed);
  17218. this.setColor3("c1", this._fireColors[0]);
  17219. this.setColor3("c2", this._fireColors[1]);
  17220. this.setColor3("c3", this._fireColors[2]);
  17221. this.setColor3("c4", this._fireColors[3]);
  17222. this.setColor3("c5", this._fireColors[4]);
  17223. this.setColor3("c6", this._fireColors[5]);
  17224. this.setFloat("alphaThreshold", this._alphaThreshold);
  17225. };
  17226. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17227. if (this._autoGenerateTime) {
  17228. this._time += this.getScene().getAnimationRatio() * 0.03;
  17229. this.updateShaderUniforms();
  17230. }
  17231. _super.prototype.render.call(this, useCameraPostProcess);
  17232. };
  17233. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17234. get: function () {
  17235. return [
  17236. new BABYLON.Color3(0.5, 0.0, 1.0),
  17237. new BABYLON.Color3(0.9, 0.0, 1.0),
  17238. new BABYLON.Color3(0.2, 0.0, 1.0),
  17239. new BABYLON.Color3(1.0, 0.9, 1.0),
  17240. new BABYLON.Color3(0.1, 0.1, 1.0),
  17241. new BABYLON.Color3(0.9, 0.9, 1.0)
  17242. ];
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17248. get: function () {
  17249. return [
  17250. new BABYLON.Color3(0.5, 1.0, 0.0),
  17251. new BABYLON.Color3(0.5, 1.0, 0.0),
  17252. new BABYLON.Color3(0.3, 0.4, 0.0),
  17253. new BABYLON.Color3(0.5, 1.0, 0.0),
  17254. new BABYLON.Color3(0.2, 0.0, 0.0),
  17255. new BABYLON.Color3(0.5, 1.0, 0.0)
  17256. ];
  17257. },
  17258. enumerable: true,
  17259. configurable: true
  17260. });
  17261. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17262. get: function () {
  17263. return [
  17264. new BABYLON.Color3(0.5, 0.0, 0.1),
  17265. new BABYLON.Color3(0.9, 0.0, 0.0),
  17266. new BABYLON.Color3(0.2, 0.0, 0.0),
  17267. new BABYLON.Color3(1.0, 0.9, 0.0),
  17268. new BABYLON.Color3(0.1, 0.1, 0.1),
  17269. new BABYLON.Color3(0.9, 0.9, 0.9)
  17270. ];
  17271. },
  17272. enumerable: true,
  17273. configurable: true
  17274. });
  17275. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17276. get: function () {
  17277. return [
  17278. new BABYLON.Color3(0.1, 0.0, 0.5),
  17279. new BABYLON.Color3(0.0, 0.0, 0.5),
  17280. new BABYLON.Color3(0.1, 0.0, 0.2),
  17281. new BABYLON.Color3(0.0, 0.0, 1.0),
  17282. new BABYLON.Color3(0.1, 0.2, 0.3),
  17283. new BABYLON.Color3(0.0, 0.2, 0.9)
  17284. ];
  17285. },
  17286. enumerable: true,
  17287. configurable: true
  17288. });
  17289. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17290. get: function () {
  17291. return this._fireColors;
  17292. },
  17293. set: function (value) {
  17294. this._fireColors = value;
  17295. this.updateShaderUniforms();
  17296. },
  17297. enumerable: true,
  17298. configurable: true
  17299. });
  17300. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17301. get: function () {
  17302. return this._time;
  17303. },
  17304. set: function (value) {
  17305. this._time = value;
  17306. this.updateShaderUniforms();
  17307. },
  17308. enumerable: true,
  17309. configurable: true
  17310. });
  17311. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17312. get: function () {
  17313. return this._speed;
  17314. },
  17315. set: function (value) {
  17316. this._speed = value;
  17317. this.updateShaderUniforms();
  17318. },
  17319. enumerable: true,
  17320. configurable: true
  17321. });
  17322. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17323. get: function () {
  17324. return this._alphaThreshold;
  17325. },
  17326. set: function (value) {
  17327. this._alphaThreshold = value;
  17328. this.updateShaderUniforms();
  17329. },
  17330. enumerable: true,
  17331. configurable: true
  17332. });
  17333. return FireProceduralTexture;
  17334. })(BABYLON.ProceduralTexture);
  17335. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17336. var CloudProceduralTexture = (function (_super) {
  17337. __extends(CloudProceduralTexture, _super);
  17338. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17339. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17340. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17341. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17342. this.updateShaderUniforms();
  17343. this.refreshRate = 0;
  17344. }
  17345. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17346. this.setColor4("skyColor", this._skyColor);
  17347. this.setColor4("cloudColor", this._cloudColor);
  17348. };
  17349. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17350. get: function () {
  17351. return this._skyColor;
  17352. },
  17353. set: function (value) {
  17354. this._skyColor = value;
  17355. this.updateShaderUniforms();
  17356. },
  17357. enumerable: true,
  17358. configurable: true
  17359. });
  17360. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17361. get: function () {
  17362. return this._cloudColor;
  17363. },
  17364. set: function (value) {
  17365. this._cloudColor = value;
  17366. this.updateShaderUniforms();
  17367. },
  17368. enumerable: true,
  17369. configurable: true
  17370. });
  17371. return CloudProceduralTexture;
  17372. })(BABYLON.ProceduralTexture);
  17373. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17374. var GrassProceduralTexture = (function (_super) {
  17375. __extends(GrassProceduralTexture, _super);
  17376. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17377. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17378. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17379. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17380. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17381. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17382. this._grassColors = [
  17383. new BABYLON.Color3(0.29, 0.38, 0.02),
  17384. new BABYLON.Color3(0.36, 0.49, 0.09),
  17385. new BABYLON.Color3(0.51, 0.6, 0.28)
  17386. ];
  17387. this.updateShaderUniforms();
  17388. this.refreshRate = 0;
  17389. }
  17390. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17391. this.setColor3("herb1Color", this._grassColors[0]);
  17392. this.setColor3("herb2Color", this._grassColors[1]);
  17393. this.setColor3("herb3Color", this._grassColors[2]);
  17394. this.setColor3("groundColor", this._groundColor);
  17395. };
  17396. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17397. get: function () {
  17398. return this._grassColors;
  17399. },
  17400. set: function (value) {
  17401. this._grassColors = value;
  17402. this.updateShaderUniforms();
  17403. },
  17404. enumerable: true,
  17405. configurable: true
  17406. });
  17407. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17408. get: function () {
  17409. return this._groundColor;
  17410. },
  17411. set: function (value) {
  17412. this.groundColor = value;
  17413. this.updateShaderUniforms();
  17414. },
  17415. enumerable: true,
  17416. configurable: true
  17417. });
  17418. return GrassProceduralTexture;
  17419. })(BABYLON.ProceduralTexture);
  17420. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17421. var RoadProceduralTexture = (function (_super) {
  17422. __extends(RoadProceduralTexture, _super);
  17423. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17424. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17425. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17426. this.updateShaderUniforms();
  17427. this.refreshRate = 0;
  17428. }
  17429. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17430. this.setColor3("roadColor", this._roadColor);
  17431. };
  17432. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17433. get: function () {
  17434. return this._roadColor;
  17435. },
  17436. set: function (value) {
  17437. this._roadColor = value;
  17438. this.updateShaderUniforms();
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. return RoadProceduralTexture;
  17444. })(BABYLON.ProceduralTexture);
  17445. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17446. var BrickProceduralTexture = (function (_super) {
  17447. __extends(BrickProceduralTexture, _super);
  17448. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17449. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17450. this._numberOfBricksHeight = 15;
  17451. this._numberOfBricksWidth = 5;
  17452. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17453. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17454. this.updateShaderUniforms();
  17455. this.refreshRate = 0;
  17456. }
  17457. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17458. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17459. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17460. this.setColor3("brickColor", this._brickColor);
  17461. this.setColor3("jointColor", this._jointColor);
  17462. };
  17463. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17464. get: function () {
  17465. return this._numberOfBricksHeight;
  17466. },
  17467. set: function (value) {
  17468. this._numberOfBricksHeight = value;
  17469. this.updateShaderUniforms();
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17475. get: function () {
  17476. return this._numberOfBricksWidth;
  17477. },
  17478. set: function (value) {
  17479. this._numberOfBricksWidth = value;
  17480. this.updateShaderUniforms();
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17486. get: function () {
  17487. return this._jointColor;
  17488. },
  17489. set: function (value) {
  17490. this._jointColor = value;
  17491. this.updateShaderUniforms();
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17497. get: function () {
  17498. return this._brickColor;
  17499. },
  17500. set: function (value) {
  17501. this._brickColor = value;
  17502. this.updateShaderUniforms();
  17503. },
  17504. enumerable: true,
  17505. configurable: true
  17506. });
  17507. return BrickProceduralTexture;
  17508. })(BABYLON.ProceduralTexture);
  17509. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17510. var MarbleProceduralTexture = (function (_super) {
  17511. __extends(MarbleProceduralTexture, _super);
  17512. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17513. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17514. this._numberOfTilesHeight = 3;
  17515. this._numberOfTilesWidth = 3;
  17516. this._amplitude = 9.0;
  17517. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17518. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17519. this.updateShaderUniforms();
  17520. this.refreshRate = 0;
  17521. }
  17522. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17523. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17524. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17525. this.setFloat("amplitude", this._amplitude);
  17526. this.setColor3("marbleColor", this._marbleColor);
  17527. this.setColor3("jointColor", this._jointColor);
  17528. };
  17529. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17530. get: function () {
  17531. return this._numberOfTilesHeight;
  17532. },
  17533. set: function (value) {
  17534. this._numberOfTilesHeight = value;
  17535. this.updateShaderUniforms();
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17541. get: function () {
  17542. return this._numberOfTilesWidth;
  17543. },
  17544. set: function (value) {
  17545. this._numberOfTilesWidth = value;
  17546. this.updateShaderUniforms();
  17547. },
  17548. enumerable: true,
  17549. configurable: true
  17550. });
  17551. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17552. get: function () {
  17553. return this._jointColor;
  17554. },
  17555. set: function (value) {
  17556. this._jointColor = value;
  17557. this.updateShaderUniforms();
  17558. },
  17559. enumerable: true,
  17560. configurable: true
  17561. });
  17562. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17563. get: function () {
  17564. return this._marbleColor;
  17565. },
  17566. set: function (value) {
  17567. this._marbleColor = value;
  17568. this.updateShaderUniforms();
  17569. },
  17570. enumerable: true,
  17571. configurable: true
  17572. });
  17573. return MarbleProceduralTexture;
  17574. })(BABYLON.ProceduralTexture);
  17575. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17576. })(BABYLON || (BABYLON = {}));
  17577. var BABYLON;
  17578. (function (BABYLON) {
  17579. var EffectFallbacks = (function () {
  17580. function EffectFallbacks() {
  17581. this._defines = {};
  17582. this._currentRank = 32;
  17583. this._maxRank = -1;
  17584. }
  17585. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17586. if (!this._defines[rank]) {
  17587. if (rank < this._currentRank) {
  17588. this._currentRank = rank;
  17589. }
  17590. if (rank > this._maxRank) {
  17591. this._maxRank = rank;
  17592. }
  17593. this._defines[rank] = new Array();
  17594. }
  17595. this._defines[rank].push(define);
  17596. };
  17597. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17598. get: function () {
  17599. return this._currentRank <= this._maxRank;
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17605. var currentFallbacks = this._defines[this._currentRank];
  17606. for (var index = 0; index < currentFallbacks.length; index++) {
  17607. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17608. }
  17609. this._currentRank++;
  17610. return currentDefines;
  17611. };
  17612. return EffectFallbacks;
  17613. })();
  17614. BABYLON.EffectFallbacks = EffectFallbacks;
  17615. var Effect = (function () {
  17616. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17617. var _this = this;
  17618. this._isReady = false;
  17619. this._compilationError = "";
  17620. this._valueCache = [];
  17621. this._engine = engine;
  17622. this.name = baseName;
  17623. this.defines = defines;
  17624. this._uniformsNames = uniformsNames.concat(samplers);
  17625. this._samplers = samplers;
  17626. this._attributesNames = attributesNames;
  17627. this.onError = onError;
  17628. this.onCompiled = onCompiled;
  17629. var vertexSource;
  17630. var fragmentSource;
  17631. if (baseName.vertexElement) {
  17632. vertexSource = document.getElementById(baseName.vertexElement);
  17633. if (!vertexSource) {
  17634. vertexSource = baseName.vertexElement;
  17635. }
  17636. }
  17637. else {
  17638. vertexSource = baseName.vertex || baseName;
  17639. }
  17640. if (baseName.fragmentElement) {
  17641. fragmentSource = document.getElementById(baseName.fragmentElement);
  17642. if (!fragmentSource) {
  17643. fragmentSource = baseName.fragmentElement;
  17644. }
  17645. }
  17646. else {
  17647. fragmentSource = baseName.fragment || baseName;
  17648. }
  17649. this._loadVertexShader(vertexSource, function (vertexCode) {
  17650. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17651. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17652. });
  17653. });
  17654. }
  17655. // Properties
  17656. Effect.prototype.isReady = function () {
  17657. return this._isReady;
  17658. };
  17659. Effect.prototype.getProgram = function () {
  17660. return this._program;
  17661. };
  17662. Effect.prototype.getAttributesNames = function () {
  17663. return this._attributesNames;
  17664. };
  17665. Effect.prototype.getAttributeLocation = function (index) {
  17666. return this._attributes[index];
  17667. };
  17668. Effect.prototype.getAttributeLocationByName = function (name) {
  17669. var index = this._attributesNames.indexOf(name);
  17670. return this._attributes[index];
  17671. };
  17672. Effect.prototype.getAttributesCount = function () {
  17673. return this._attributes.length;
  17674. };
  17675. Effect.prototype.getUniformIndex = function (uniformName) {
  17676. return this._uniformsNames.indexOf(uniformName);
  17677. };
  17678. Effect.prototype.getUniform = function (uniformName) {
  17679. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17680. };
  17681. Effect.prototype.getSamplers = function () {
  17682. return this._samplers;
  17683. };
  17684. Effect.prototype.getCompilationError = function () {
  17685. return this._compilationError;
  17686. };
  17687. // Methods
  17688. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17689. // DOM element ?
  17690. if (vertex instanceof HTMLElement) {
  17691. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17692. callback(vertexCode);
  17693. return;
  17694. }
  17695. // Is in local store ?
  17696. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17697. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17698. return;
  17699. }
  17700. var vertexShaderUrl;
  17701. if (vertex[0] === "." || vertex[0] === "/") {
  17702. vertexShaderUrl = vertex;
  17703. }
  17704. else {
  17705. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17706. }
  17707. // Vertex shader
  17708. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17709. };
  17710. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17711. // DOM element ?
  17712. if (fragment instanceof HTMLElement) {
  17713. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17714. callback(fragmentCode);
  17715. return;
  17716. }
  17717. // Is in local store ?
  17718. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17719. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17720. return;
  17721. }
  17722. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17723. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17724. return;
  17725. }
  17726. var fragmentShaderUrl;
  17727. if (fragment[0] === "." || fragment[0] === "/") {
  17728. fragmentShaderUrl = fragment;
  17729. }
  17730. else {
  17731. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17732. }
  17733. // Fragment shader
  17734. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17735. };
  17736. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17737. try {
  17738. var engine = this._engine;
  17739. if (!engine.getCaps().highPrecisionShaderSupported) {
  17740. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17741. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17742. }
  17743. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17744. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17745. this._attributes = engine.getAttributes(this._program, attributesNames);
  17746. for (var index = 0; index < this._samplers.length; index++) {
  17747. var sampler = this.getUniform(this._samplers[index]);
  17748. if (sampler == null) {
  17749. this._samplers.splice(index, 1);
  17750. index--;
  17751. }
  17752. }
  17753. engine.bindSamplers(this);
  17754. this._isReady = true;
  17755. if (this.onCompiled) {
  17756. this.onCompiled(this);
  17757. }
  17758. }
  17759. catch (e) {
  17760. // Is it a problem with precision?
  17761. if (e.message.indexOf("highp") !== -1) {
  17762. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17763. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17764. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17765. return;
  17766. }
  17767. // Let's go through fallbacks then
  17768. if (fallbacks && fallbacks.isMoreFallbacks) {
  17769. defines = fallbacks.reduce(defines);
  17770. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17771. }
  17772. else {
  17773. BABYLON.Tools.Error("Unable to compile effect: ");
  17774. if (this.name.vertexElement) {
  17775. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17776. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17777. }
  17778. else if (this.name.vertex) {
  17779. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17780. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17781. }
  17782. else {
  17783. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17784. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17785. }
  17786. BABYLON.Tools.Error("Defines: " + defines);
  17787. BABYLON.Tools.Error("Error: " + e.message);
  17788. this._compilationError = e.message;
  17789. if (this.onError) {
  17790. this.onError(this, this._compilationError);
  17791. }
  17792. }
  17793. }
  17794. };
  17795. Object.defineProperty(Effect.prototype, "isSupported", {
  17796. get: function () {
  17797. return this._compilationError === "";
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Effect.prototype._bindTexture = function (channel, texture) {
  17803. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17804. };
  17805. Effect.prototype.setTexture = function (channel, texture) {
  17806. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17807. };
  17808. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17809. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17810. };
  17811. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17812. if (!this._valueCache[uniformName]) {
  17813. this._valueCache[uniformName] = new BABYLON.Matrix();
  17814. }
  17815. for (var index = 0; index < 16; index++) {
  17816. this._valueCache[uniformName].m[index] = matrix.m[index];
  17817. }
  17818. };
  17819. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17820. if (!this._valueCache[uniformName]) {
  17821. this._valueCache[uniformName] = [x, y];
  17822. return;
  17823. }
  17824. this._valueCache[uniformName][0] = x;
  17825. this._valueCache[uniformName][1] = y;
  17826. };
  17827. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17828. if (!this._valueCache[uniformName]) {
  17829. this._valueCache[uniformName] = [x, y, z];
  17830. return;
  17831. }
  17832. this._valueCache[uniformName][0] = x;
  17833. this._valueCache[uniformName][1] = y;
  17834. this._valueCache[uniformName][2] = z;
  17835. };
  17836. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17837. if (!this._valueCache[uniformName]) {
  17838. this._valueCache[uniformName] = [x, y, z, w];
  17839. return;
  17840. }
  17841. this._valueCache[uniformName][0] = x;
  17842. this._valueCache[uniformName][1] = y;
  17843. this._valueCache[uniformName][2] = z;
  17844. this._valueCache[uniformName][3] = w;
  17845. };
  17846. Effect.prototype.setArray = function (uniformName, array) {
  17847. this._engine.setArray(this.getUniform(uniformName), array);
  17848. return this;
  17849. };
  17850. Effect.prototype.setArray2 = function (uniformName, array) {
  17851. this._engine.setArray2(this.getUniform(uniformName), array);
  17852. return this;
  17853. };
  17854. Effect.prototype.setArray3 = function (uniformName, array) {
  17855. this._engine.setArray3(this.getUniform(uniformName), array);
  17856. return this;
  17857. };
  17858. Effect.prototype.setArray4 = function (uniformName, array) {
  17859. this._engine.setArray4(this.getUniform(uniformName), array);
  17860. return this;
  17861. };
  17862. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17863. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17864. return this;
  17865. };
  17866. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17867. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17868. return this;
  17869. this._cacheMatrix(uniformName, matrix);
  17870. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17871. return this;
  17872. };
  17873. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  17874. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  17875. return this;
  17876. };
  17877. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  17878. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  17879. return this;
  17880. };
  17881. Effect.prototype.setFloat = function (uniformName, value) {
  17882. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17883. return this;
  17884. this._valueCache[uniformName] = value;
  17885. this._engine.setFloat(this.getUniform(uniformName), value);
  17886. return this;
  17887. };
  17888. Effect.prototype.setBool = function (uniformName, bool) {
  17889. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17890. return this;
  17891. this._valueCache[uniformName] = bool;
  17892. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17893. return this;
  17894. };
  17895. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17896. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17897. return this;
  17898. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17899. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17900. return this;
  17901. };
  17902. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17903. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17904. return this;
  17905. this._cacheFloat2(uniformName, x, y);
  17906. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17907. return this;
  17908. };
  17909. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17910. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17911. return this;
  17912. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17913. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17914. return this;
  17915. };
  17916. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17917. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17918. return this;
  17919. this._cacheFloat3(uniformName, x, y, z);
  17920. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17921. return this;
  17922. };
  17923. Effect.prototype.setVector4 = function (uniformName, vector4) {
  17924. 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)
  17925. return this;
  17926. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  17927. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  17928. return this;
  17929. };
  17930. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17931. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17932. return this;
  17933. this._cacheFloat4(uniformName, x, y, z, w);
  17934. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17935. return this;
  17936. };
  17937. Effect.prototype.setColor3 = function (uniformName, color3) {
  17938. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17939. return this;
  17940. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17941. this._engine.setColor3(this.getUniform(uniformName), color3);
  17942. return this;
  17943. };
  17944. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17945. 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)
  17946. return this;
  17947. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17948. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17949. return this;
  17950. };
  17951. // Statics
  17952. Effect.ShadersStore = {};
  17953. return Effect;
  17954. })();
  17955. BABYLON.Effect = Effect;
  17956. })(BABYLON || (BABYLON = {}));
  17957. var BABYLON;
  17958. (function (BABYLON) {
  17959. var MaterialDefines = (function () {
  17960. function MaterialDefines() {
  17961. }
  17962. MaterialDefines.prototype.isEqual = function (other) {
  17963. for (var index = 0; index < this._keys.length; index++) {
  17964. var prop = this._keys[index];
  17965. if (this[prop] !== other[prop]) {
  17966. return false;
  17967. }
  17968. }
  17969. return true;
  17970. };
  17971. MaterialDefines.prototype.cloneTo = function (other) {
  17972. for (var index = 0; index < this._keys.length; index++) {
  17973. var prop = this._keys[index];
  17974. other[prop] = this[prop];
  17975. }
  17976. };
  17977. MaterialDefines.prototype.reset = function () {
  17978. for (var index = 0; index < this._keys.length; index++) {
  17979. var prop = this._keys[index];
  17980. if (prop === "BonesPerMesh") {
  17981. this[prop] = 0;
  17982. continue;
  17983. }
  17984. this[prop] = false;
  17985. }
  17986. };
  17987. MaterialDefines.prototype.toString = function () {
  17988. var result = "";
  17989. for (var index = 0; index < this._keys.length; index++) {
  17990. var prop = this._keys[index];
  17991. if (prop === "BonesPerMesh" && this[prop] > 0) {
  17992. result += "#define BonesPerMesh " + this[prop] + "\n";
  17993. continue;
  17994. }
  17995. if (this[prop]) {
  17996. result += "#define " + prop + "\n";
  17997. }
  17998. }
  17999. return result;
  18000. };
  18001. return MaterialDefines;
  18002. })();
  18003. BABYLON.MaterialDefines = MaterialDefines;
  18004. var Material = (function () {
  18005. function Material(name, scene, doNotAdd) {
  18006. this.name = name;
  18007. this.checkReadyOnEveryCall = false;
  18008. this.checkReadyOnlyOnce = false;
  18009. this.state = "";
  18010. this.alpha = 1.0;
  18011. this.backFaceCulling = true;
  18012. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18013. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18014. this.disableDepthWrite = false;
  18015. this.fogEnabled = true;
  18016. this._wasPreviouslyReady = false;
  18017. this._fillMode = Material.TriangleFillMode;
  18018. this.pointSize = 1.0;
  18019. this.zOffset = 0;
  18020. this.id = name;
  18021. this._scene = scene;
  18022. if (!doNotAdd) {
  18023. scene.materials.push(this);
  18024. }
  18025. }
  18026. Object.defineProperty(Material, "TriangleFillMode", {
  18027. get: function () {
  18028. return Material._TriangleFillMode;
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. Object.defineProperty(Material, "WireFrameFillMode", {
  18034. get: function () {
  18035. return Material._WireFrameFillMode;
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Object.defineProperty(Material, "PointFillMode", {
  18041. get: function () {
  18042. return Material._PointFillMode;
  18043. },
  18044. enumerable: true,
  18045. configurable: true
  18046. });
  18047. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18048. get: function () {
  18049. return Material._ClockWiseSideOrientation;
  18050. },
  18051. enumerable: true,
  18052. configurable: true
  18053. });
  18054. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18055. get: function () {
  18056. return Material._CounterClockWiseSideOrientation;
  18057. },
  18058. enumerable: true,
  18059. configurable: true
  18060. });
  18061. Object.defineProperty(Material.prototype, "wireframe", {
  18062. get: function () {
  18063. return this._fillMode === Material.WireFrameFillMode;
  18064. },
  18065. set: function (value) {
  18066. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18067. },
  18068. enumerable: true,
  18069. configurable: true
  18070. });
  18071. Object.defineProperty(Material.prototype, "pointsCloud", {
  18072. get: function () {
  18073. return this._fillMode === Material.PointFillMode;
  18074. },
  18075. set: function (value) {
  18076. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18077. },
  18078. enumerable: true,
  18079. configurable: true
  18080. });
  18081. Object.defineProperty(Material.prototype, "fillMode", {
  18082. get: function () {
  18083. return this._fillMode;
  18084. },
  18085. set: function (value) {
  18086. this._fillMode = value;
  18087. },
  18088. enumerable: true,
  18089. configurable: true
  18090. });
  18091. Material.prototype.isReady = function (mesh, useInstances) {
  18092. return true;
  18093. };
  18094. Material.prototype.getEffect = function () {
  18095. return this._effect;
  18096. };
  18097. Material.prototype.getScene = function () {
  18098. return this._scene;
  18099. };
  18100. Material.prototype.needAlphaBlending = function () {
  18101. return (this.alpha < 1.0);
  18102. };
  18103. Material.prototype.needAlphaTesting = function () {
  18104. return false;
  18105. };
  18106. Material.prototype.getAlphaTestTexture = function () {
  18107. return null;
  18108. };
  18109. Material.prototype.trackCreation = function (onCompiled, onError) {
  18110. };
  18111. Material.prototype._preBind = function () {
  18112. var engine = this._scene.getEngine();
  18113. engine.enableEffect(this._effect);
  18114. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18115. };
  18116. Material.prototype.bind = function (world, mesh) {
  18117. this._scene._cachedMaterial = this;
  18118. if (this.onBind) {
  18119. this.onBind(this, mesh);
  18120. }
  18121. if (this.disableDepthWrite) {
  18122. var engine = this._scene.getEngine();
  18123. this._cachedDepthWriteState = engine.getDepthWrite();
  18124. engine.setDepthWrite(false);
  18125. }
  18126. };
  18127. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18128. };
  18129. Material.prototype.unbind = function () {
  18130. if (this.disableDepthWrite) {
  18131. var engine = this._scene.getEngine();
  18132. engine.setDepthWrite(this._cachedDepthWriteState);
  18133. }
  18134. };
  18135. Material.prototype.clone = function (name) {
  18136. return null;
  18137. };
  18138. Material.prototype.getBindedMeshes = function () {
  18139. var result = new Array();
  18140. for (var index = 0; index < this._scene.meshes.length; index++) {
  18141. var mesh = this._scene.meshes[index];
  18142. if (mesh.material === this) {
  18143. result.push(mesh);
  18144. }
  18145. }
  18146. return result;
  18147. };
  18148. Material.prototype.dispose = function (forceDisposeEffect) {
  18149. // Animations
  18150. this.getScene().stopAnimation(this);
  18151. // Remove from scene
  18152. var index = this._scene.materials.indexOf(this);
  18153. if (index >= 0) {
  18154. this._scene.materials.splice(index, 1);
  18155. }
  18156. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18157. if (forceDisposeEffect && this._effect) {
  18158. this._scene.getEngine()._releaseEffect(this._effect);
  18159. this._effect = null;
  18160. }
  18161. // Remove from meshes
  18162. for (index = 0; index < this._scene.meshes.length; index++) {
  18163. var mesh = this._scene.meshes[index];
  18164. if (mesh.material === this) {
  18165. mesh.material = null;
  18166. }
  18167. }
  18168. // Callback
  18169. if (this.onDispose) {
  18170. this.onDispose();
  18171. }
  18172. };
  18173. Material.prototype.copyTo = function (other) {
  18174. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18175. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18176. other.alpha = this.alpha;
  18177. other.fillMode = this.fillMode;
  18178. other.backFaceCulling = this.backFaceCulling;
  18179. other.wireframe = this.wireframe;
  18180. other.fogEnabled = this.fogEnabled;
  18181. other.wireframe = this.wireframe;
  18182. other.zOffset = this.zOffset;
  18183. other.alphaMode = this.alphaMode;
  18184. other.sideOrientation = this.sideOrientation;
  18185. other.disableDepthWrite = this.disableDepthWrite;
  18186. other.pointSize = this.pointSize;
  18187. other.pointsCloud = this.pointsCloud;
  18188. };
  18189. Material._TriangleFillMode = 0;
  18190. Material._WireFrameFillMode = 1;
  18191. Material._PointFillMode = 2;
  18192. Material._ClockWiseSideOrientation = 0;
  18193. Material._CounterClockWiseSideOrientation = 1;
  18194. return Material;
  18195. })();
  18196. BABYLON.Material = Material;
  18197. })(BABYLON || (BABYLON = {}));
  18198. var BABYLON;
  18199. (function (BABYLON) {
  18200. var maxSimultaneousLights = 4;
  18201. var FresnelParameters = (function () {
  18202. function FresnelParameters() {
  18203. this.isEnabled = true;
  18204. this.leftColor = BABYLON.Color3.White();
  18205. this.rightColor = BABYLON.Color3.Black();
  18206. this.bias = 0;
  18207. this.power = 1;
  18208. }
  18209. FresnelParameters.prototype.clone = function () {
  18210. var newFresnelParameters = new FresnelParameters();
  18211. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18212. return new FresnelParameters;
  18213. };
  18214. return FresnelParameters;
  18215. })();
  18216. BABYLON.FresnelParameters = FresnelParameters;
  18217. var StandardMaterialDefines = (function (_super) {
  18218. __extends(StandardMaterialDefines, _super);
  18219. function StandardMaterialDefines() {
  18220. _super.call(this);
  18221. this.DIFFUSE = false;
  18222. this.AMBIENT = false;
  18223. this.OPACITY = false;
  18224. this.OPACITYRGB = false;
  18225. this.REFLECTION = false;
  18226. this.EMISSIVE = false;
  18227. this.SPECULAR = false;
  18228. this.BUMP = false;
  18229. this.SPECULAROVERALPHA = false;
  18230. this.CLIPPLANE = false;
  18231. this.ALPHATEST = false;
  18232. this.ALPHAFROMDIFFUSE = false;
  18233. this.POINTSIZE = false;
  18234. this.FOG = false;
  18235. this.LIGHT0 = false;
  18236. this.LIGHT1 = false;
  18237. this.LIGHT2 = false;
  18238. this.LIGHT3 = false;
  18239. this.SPOTLIGHT0 = false;
  18240. this.SPOTLIGHT1 = false;
  18241. this.SPOTLIGHT2 = false;
  18242. this.SPOTLIGHT3 = false;
  18243. this.HEMILIGHT0 = false;
  18244. this.HEMILIGHT1 = false;
  18245. this.HEMILIGHT2 = false;
  18246. this.HEMILIGHT3 = false;
  18247. this.POINTLIGHT0 = false;
  18248. this.POINTLIGHT1 = false;
  18249. this.POINTLIGHT2 = false;
  18250. this.POINTLIGHT3 = false;
  18251. this.DIRLIGHT0 = false;
  18252. this.DIRLIGHT1 = false;
  18253. this.DIRLIGHT2 = false;
  18254. this.DIRLIGHT3 = false;
  18255. this.SPECULARTERM = false;
  18256. this.SHADOW0 = false;
  18257. this.SHADOW1 = false;
  18258. this.SHADOW2 = false;
  18259. this.SHADOW3 = false;
  18260. this.SHADOWS = false;
  18261. this.SHADOWVSM0 = false;
  18262. this.SHADOWVSM1 = false;
  18263. this.SHADOWVSM2 = false;
  18264. this.SHADOWVSM3 = false;
  18265. this.SHADOWPCF0 = false;
  18266. this.SHADOWPCF1 = false;
  18267. this.SHADOWPCF2 = false;
  18268. this.SHADOWPCF3 = false;
  18269. this.DIFFUSEFRESNEL = false;
  18270. this.OPACITYFRESNEL = false;
  18271. this.REFLECTIONFRESNEL = false;
  18272. this.EMISSIVEFRESNEL = false;
  18273. this.FRESNEL = false;
  18274. this.NORMAL = false;
  18275. this.UV1 = false;
  18276. this.UV2 = false;
  18277. this.VERTEXCOLOR = false;
  18278. this.VERTEXALPHA = false;
  18279. this.BONES = false;
  18280. this.BONES4 = false;
  18281. this.BonesPerMesh = 0;
  18282. this.INSTANCES = false;
  18283. this.GLOSSINESS = false;
  18284. this.ROUGHNESS = false;
  18285. this.EMISSIVEASILLUMINATION = false;
  18286. this.LINKEMISSIVEWITHDIFFUSE = false;
  18287. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18288. this.LIGHTMAP = false;
  18289. this.USELIGHTMAPASSHADOWMAP = false;
  18290. this.REFLECTIONMAP_3D = false;
  18291. this.REFLECTIONMAP_SPHERICAL = false;
  18292. this.REFLECTIONMAP_PLANAR = false;
  18293. this.REFLECTIONMAP_CUBIC = false;
  18294. this.REFLECTIONMAP_PROJECTION = false;
  18295. this.REFLECTIONMAP_SKYBOX = false;
  18296. this.REFLECTIONMAP_EXPLICIT = false;
  18297. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18298. this.INVERTCUBICMAP = false;
  18299. this._keys = Object.keys(this);
  18300. }
  18301. return StandardMaterialDefines;
  18302. })(BABYLON.MaterialDefines);
  18303. var StandardMaterial = (function (_super) {
  18304. __extends(StandardMaterial, _super);
  18305. function StandardMaterial(name, scene) {
  18306. var _this = this;
  18307. _super.call(this, name, scene);
  18308. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18309. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18310. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18311. this.specularPower = 64;
  18312. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18313. this.useAlphaFromDiffuseTexture = false;
  18314. this.useEmissiveAsIllumination = false;
  18315. this.linkEmissiveWithDiffuse = false;
  18316. this.useReflectionFresnelFromSpecular = false;
  18317. this.useSpecularOverAlpha = true;
  18318. this.disableLighting = false;
  18319. this.roughness = 0;
  18320. this.useLightmapAsShadowmap = false;
  18321. this.useGlossinessFromSpecularMapAlpha = false;
  18322. this._renderTargets = new BABYLON.SmartArray(16);
  18323. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18324. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18325. this._scaledDiffuse = new BABYLON.Color3();
  18326. this._scaledSpecular = new BABYLON.Color3();
  18327. this._defines = new StandardMaterialDefines();
  18328. this._cachedDefines = new StandardMaterialDefines();
  18329. this._cachedDefines.BonesPerMesh = -1;
  18330. this.getRenderTargetTextures = function () {
  18331. _this._renderTargets.reset();
  18332. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18333. _this._renderTargets.push(_this.reflectionTexture);
  18334. }
  18335. return _this._renderTargets;
  18336. };
  18337. }
  18338. StandardMaterial.prototype.needAlphaBlending = function () {
  18339. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18340. };
  18341. StandardMaterial.prototype.needAlphaTesting = function () {
  18342. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18343. };
  18344. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18345. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18346. };
  18347. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18348. return this.diffuseTexture;
  18349. };
  18350. // Methods
  18351. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18352. if (!mesh) {
  18353. return true;
  18354. }
  18355. if (this._defines.INSTANCES !== useInstances) {
  18356. return false;
  18357. }
  18358. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18359. return true;
  18360. }
  18361. return false;
  18362. };
  18363. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18364. if (this.checkReadyOnlyOnce) {
  18365. if (this._wasPreviouslyReady) {
  18366. return true;
  18367. }
  18368. }
  18369. var scene = this.getScene();
  18370. if (!this.checkReadyOnEveryCall) {
  18371. if (this._renderId === scene.getRenderId()) {
  18372. if (this._checkCache(scene, mesh, useInstances)) {
  18373. return true;
  18374. }
  18375. }
  18376. }
  18377. var engine = scene.getEngine();
  18378. var needNormals = false;
  18379. var needUVs = false;
  18380. this._defines.reset();
  18381. // Textures
  18382. if (scene.texturesEnabled) {
  18383. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18384. if (!this.diffuseTexture.isReady()) {
  18385. return false;
  18386. }
  18387. else {
  18388. needUVs = true;
  18389. this._defines.DIFFUSE = true;
  18390. }
  18391. }
  18392. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18393. if (!this.ambientTexture.isReady()) {
  18394. return false;
  18395. }
  18396. else {
  18397. needUVs = true;
  18398. this._defines.AMBIENT = true;
  18399. }
  18400. }
  18401. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18402. if (!this.opacityTexture.isReady()) {
  18403. return false;
  18404. }
  18405. else {
  18406. needUVs = true;
  18407. this._defines.OPACITY = true;
  18408. if (this.opacityTexture.getAlphaFromRGB) {
  18409. this._defines.OPACITYRGB = true;
  18410. }
  18411. }
  18412. }
  18413. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18414. if (!this.reflectionTexture.isReady()) {
  18415. return false;
  18416. }
  18417. else {
  18418. needNormals = true;
  18419. this._defines.REFLECTION = true;
  18420. if (this.roughness > 0) {
  18421. this._defines.ROUGHNESS = true;
  18422. }
  18423. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18424. this._defines.INVERTCUBICMAP = true;
  18425. }
  18426. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18427. switch (this.reflectionTexture.coordinatesMode) {
  18428. case BABYLON.Texture.CUBIC_MODE:
  18429. case BABYLON.Texture.INVCUBIC_MODE:
  18430. this._defines.REFLECTIONMAP_CUBIC = true;
  18431. break;
  18432. case BABYLON.Texture.EXPLICIT_MODE:
  18433. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18434. break;
  18435. case BABYLON.Texture.PLANAR_MODE:
  18436. this._defines.REFLECTIONMAP_PLANAR = true;
  18437. break;
  18438. case BABYLON.Texture.PROJECTION_MODE:
  18439. this._defines.REFLECTIONMAP_PROJECTION = true;
  18440. break;
  18441. case BABYLON.Texture.SKYBOX_MODE:
  18442. this._defines.REFLECTIONMAP_SKYBOX = true;
  18443. break;
  18444. case BABYLON.Texture.SPHERICAL_MODE:
  18445. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18446. break;
  18447. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18448. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18449. break;
  18450. }
  18451. }
  18452. }
  18453. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18454. if (!this.emissiveTexture.isReady()) {
  18455. return false;
  18456. }
  18457. else {
  18458. needUVs = true;
  18459. this._defines.EMISSIVE = true;
  18460. }
  18461. }
  18462. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18463. if (!this.lightmapTexture.isReady()) {
  18464. return false;
  18465. }
  18466. else {
  18467. needUVs = true;
  18468. this._defines.LIGHTMAP = true;
  18469. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18470. }
  18471. }
  18472. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18473. if (!this.specularTexture.isReady()) {
  18474. return false;
  18475. }
  18476. else {
  18477. needUVs = true;
  18478. this._defines.SPECULAR = true;
  18479. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18480. }
  18481. }
  18482. }
  18483. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18484. if (!this.bumpTexture.isReady()) {
  18485. return false;
  18486. }
  18487. else {
  18488. needUVs = true;
  18489. this._defines.BUMP = true;
  18490. }
  18491. }
  18492. // Effect
  18493. if (scene.clipPlane) {
  18494. this._defines.CLIPPLANE = true;
  18495. }
  18496. if (engine.getAlphaTesting()) {
  18497. this._defines.ALPHATEST = true;
  18498. }
  18499. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18500. this._defines.ALPHAFROMDIFFUSE = true;
  18501. }
  18502. if (this.useEmissiveAsIllumination) {
  18503. this._defines.EMISSIVEASILLUMINATION = true;
  18504. }
  18505. if (this.linkEmissiveWithDiffuse) {
  18506. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18507. }
  18508. if (this.useReflectionFresnelFromSpecular) {
  18509. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18510. }
  18511. // Point size
  18512. if (this.pointsCloud || scene.forcePointsCloud) {
  18513. this._defines.POINTSIZE = true;
  18514. }
  18515. // Fog
  18516. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18517. this._defines.FOG = true;
  18518. }
  18519. var lightIndex = 0;
  18520. if (scene.lightsEnabled && !this.disableLighting) {
  18521. for (var index = 0; index < scene.lights.length; index++) {
  18522. var light = scene.lights[index];
  18523. if (!light.isEnabled()) {
  18524. continue;
  18525. }
  18526. // Excluded check
  18527. if (light._excludedMeshesIds.length > 0) {
  18528. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18529. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18530. if (excludedMesh) {
  18531. light.excludedMeshes.push(excludedMesh);
  18532. }
  18533. }
  18534. light._excludedMeshesIds = [];
  18535. }
  18536. // Included check
  18537. if (light._includedOnlyMeshesIds.length > 0) {
  18538. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18539. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18540. if (includedOnlyMesh) {
  18541. light.includedOnlyMeshes.push(includedOnlyMesh);
  18542. }
  18543. }
  18544. light._includedOnlyMeshesIds = [];
  18545. }
  18546. if (!light.canAffectMesh(mesh)) {
  18547. continue;
  18548. }
  18549. needNormals = true;
  18550. this._defines["LIGHT" + lightIndex] = true;
  18551. var type;
  18552. if (light instanceof BABYLON.SpotLight) {
  18553. type = "SPOTLIGHT" + lightIndex;
  18554. }
  18555. else if (light instanceof BABYLON.HemisphericLight) {
  18556. type = "HEMILIGHT" + lightIndex;
  18557. }
  18558. else if (light instanceof BABYLON.PointLight) {
  18559. type = "POINTLIGHT" + lightIndex;
  18560. }
  18561. else {
  18562. type = "DIRLIGHT" + lightIndex;
  18563. }
  18564. this._defines[type] = true;
  18565. // Specular
  18566. if (!light.specular.equalsFloats(0, 0, 0)) {
  18567. this._defines.SPECULARTERM = true;
  18568. }
  18569. // Shadows
  18570. if (scene.shadowsEnabled) {
  18571. var shadowGenerator = light.getShadowGenerator();
  18572. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18573. this._defines["SHADOW" + lightIndex] = true;
  18574. this._defines.SHADOWS = true;
  18575. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18576. this._defines["SHADOWVSM" + lightIndex] = true;
  18577. }
  18578. if (shadowGenerator.usePoissonSampling) {
  18579. this._defines["SHADOWPCF" + lightIndex] = true;
  18580. }
  18581. }
  18582. }
  18583. lightIndex++;
  18584. if (lightIndex === maxSimultaneousLights)
  18585. break;
  18586. }
  18587. }
  18588. if (StandardMaterial.FresnelEnabled) {
  18589. // Fresnel
  18590. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18591. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18592. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18593. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18594. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18595. this._defines.DIFFUSEFRESNEL = true;
  18596. }
  18597. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18598. this._defines.OPACITYFRESNEL = true;
  18599. }
  18600. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18601. this._defines.REFLECTIONFRESNEL = true;
  18602. }
  18603. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18604. this._defines.EMISSIVEFRESNEL = true;
  18605. }
  18606. needNormals = true;
  18607. this._defines.FRESNEL = true;
  18608. }
  18609. }
  18610. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18611. this._defines.SPECULAROVERALPHA = true;
  18612. }
  18613. // Attribs
  18614. if (mesh) {
  18615. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18616. this._defines.NORMAL = true;
  18617. }
  18618. if (needUVs) {
  18619. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18620. this._defines.UV1 = true;
  18621. }
  18622. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18623. this._defines.UV2 = true;
  18624. }
  18625. }
  18626. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18627. this._defines.VERTEXCOLOR = true;
  18628. if (mesh.hasVertexAlpha) {
  18629. this._defines.VERTEXALPHA = true;
  18630. }
  18631. }
  18632. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18633. this._defines.BONES = true;
  18634. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18635. this._defines.BONES4 = true;
  18636. }
  18637. // Instances
  18638. if (useInstances) {
  18639. this._defines.INSTANCES = true;
  18640. }
  18641. }
  18642. // Get correct effect
  18643. if (!this._defines.isEqual(this._cachedDefines)) {
  18644. this._defines.cloneTo(this._cachedDefines);
  18645. scene.resetCachedMaterial();
  18646. // Fallbacks
  18647. var fallbacks = new BABYLON.EffectFallbacks();
  18648. if (this._defines.REFLECTION) {
  18649. fallbacks.addFallback(0, "REFLECTION");
  18650. }
  18651. if (this._defines.SPECULAR) {
  18652. fallbacks.addFallback(0, "SPECULAR");
  18653. }
  18654. if (this._defines.BUMP) {
  18655. fallbacks.addFallback(0, "BUMP");
  18656. }
  18657. if (this._defines.SPECULAROVERALPHA) {
  18658. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18659. }
  18660. if (this._defines.FOG) {
  18661. fallbacks.addFallback(1, "FOG");
  18662. }
  18663. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18664. if (!this._defines["LIGHT" + lightIndex]) {
  18665. continue;
  18666. }
  18667. if (lightIndex > 0) {
  18668. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18669. }
  18670. if (this._defines["SHADOW" + lightIndex]) {
  18671. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18672. }
  18673. if (this._defines["SHADOWPCF" + lightIndex]) {
  18674. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18675. }
  18676. if (this._defines["SHADOWVSM" + lightIndex]) {
  18677. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18678. }
  18679. }
  18680. if (this._defines.SPECULARTERM) {
  18681. fallbacks.addFallback(0, "SPECULARTERM");
  18682. }
  18683. if (this._defines.DIFFUSEFRESNEL) {
  18684. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18685. }
  18686. if (this._defines.OPACITYFRESNEL) {
  18687. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18688. }
  18689. if (this._defines.REFLECTIONFRESNEL) {
  18690. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18691. }
  18692. if (this._defines.EMISSIVEFRESNEL) {
  18693. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18694. }
  18695. if (this._defines.FRESNEL) {
  18696. fallbacks.addFallback(4, "FRESNEL");
  18697. }
  18698. if (this._defines.BONES4) {
  18699. fallbacks.addFallback(0, "BONES4");
  18700. }
  18701. //Attributes
  18702. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18703. if (this._defines.NORMAL) {
  18704. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18705. }
  18706. if (this._defines.UV1) {
  18707. attribs.push(BABYLON.VertexBuffer.UVKind);
  18708. }
  18709. if (this._defines.UV2) {
  18710. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18711. }
  18712. if (this._defines.VERTEXCOLOR) {
  18713. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18714. }
  18715. if (this._defines.BONES) {
  18716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18718. }
  18719. if (this._defines.INSTANCES) {
  18720. attribs.push("world0");
  18721. attribs.push("world1");
  18722. attribs.push("world2");
  18723. attribs.push("world3");
  18724. }
  18725. // Legacy browser patch
  18726. var shaderName = "default";
  18727. if (!scene.getEngine().getCaps().standardDerivatives) {
  18728. shaderName = "legacydefault";
  18729. }
  18730. var join = this._defines.toString();
  18731. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18732. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18733. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18734. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18735. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18736. "vFogInfos", "vFogColor", "pointSize",
  18737. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18738. "mBones",
  18739. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18740. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18741. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18742. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18743. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18744. ], join, fallbacks, this.onCompiled, this.onError);
  18745. }
  18746. if (!this._effect.isReady()) {
  18747. return false;
  18748. }
  18749. this._renderId = scene.getRenderId();
  18750. this._wasPreviouslyReady = true;
  18751. if (mesh) {
  18752. if (!mesh._materialDefines) {
  18753. mesh._materialDefines = new StandardMaterialDefines();
  18754. }
  18755. this._defines.cloneTo(mesh._materialDefines);
  18756. }
  18757. return true;
  18758. };
  18759. StandardMaterial.prototype.unbind = function () {
  18760. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18761. this._effect.setTexture("reflection2DSampler", null);
  18762. }
  18763. _super.prototype.unbind.call(this);
  18764. };
  18765. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18766. this._effect.setMatrix("world", world);
  18767. };
  18768. StandardMaterial.prototype.bind = function (world, mesh) {
  18769. var scene = this.getScene();
  18770. // Matrices
  18771. this.bindOnlyWorldMatrix(world);
  18772. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18773. // Bones
  18774. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18775. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18776. }
  18777. if (scene.getCachedMaterial() !== this) {
  18778. if (StandardMaterial.FresnelEnabled) {
  18779. // Fresnel
  18780. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18781. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18782. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18783. }
  18784. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18785. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18786. }
  18787. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18788. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18789. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18790. }
  18791. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18792. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18793. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18794. }
  18795. }
  18796. // Textures
  18797. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18798. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18799. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18800. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18801. }
  18802. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18803. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18804. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18805. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18806. }
  18807. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18808. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18809. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18810. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18811. }
  18812. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18813. if (this.reflectionTexture.isCube) {
  18814. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18815. }
  18816. else {
  18817. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18818. }
  18819. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18820. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18821. }
  18822. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18823. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18824. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18825. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18826. }
  18827. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18828. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  18829. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  18830. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  18831. }
  18832. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18833. this._effect.setTexture("specularSampler", this.specularTexture);
  18834. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18835. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18836. }
  18837. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18838. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18839. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18840. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18841. }
  18842. // Clip plane
  18843. if (scene.clipPlane) {
  18844. var clipPlane = scene.clipPlane;
  18845. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18846. }
  18847. // Point size
  18848. if (this.pointsCloud) {
  18849. this._effect.setFloat("pointSize", this.pointSize);
  18850. }
  18851. // Colors
  18852. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18853. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  18854. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18855. if (this._defines.SPECULARTERM) {
  18856. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  18857. }
  18858. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18859. }
  18860. // Diffuse
  18861. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  18862. // Lights
  18863. if (scene.lightsEnabled && !this.disableLighting) {
  18864. var lightIndex = 0;
  18865. for (var index = 0; index < scene.lights.length; index++) {
  18866. var light = scene.lights[index];
  18867. if (!light.isEnabled()) {
  18868. continue;
  18869. }
  18870. if (!light.canAffectMesh(mesh)) {
  18871. continue;
  18872. }
  18873. if (light instanceof BABYLON.PointLight) {
  18874. // Point Light
  18875. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18876. }
  18877. else if (light instanceof BABYLON.DirectionalLight) {
  18878. // Directional Light
  18879. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18880. }
  18881. else if (light instanceof BABYLON.SpotLight) {
  18882. // Spot Light
  18883. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18884. }
  18885. else if (light instanceof BABYLON.HemisphericLight) {
  18886. // Hemispheric Light
  18887. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18888. }
  18889. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18890. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18891. if (this._defines.SPECULARTERM) {
  18892. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18893. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18894. }
  18895. // Shadows
  18896. if (scene.shadowsEnabled) {
  18897. var shadowGenerator = light.getShadowGenerator();
  18898. if (mesh.receiveShadows && shadowGenerator) {
  18899. if (!light.needCube()) {
  18900. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18901. }
  18902. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18903. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18904. }
  18905. }
  18906. lightIndex++;
  18907. if (lightIndex === maxSimultaneousLights)
  18908. break;
  18909. }
  18910. }
  18911. // View
  18912. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18913. this._effect.setMatrix("view", scene.getViewMatrix());
  18914. }
  18915. // Fog
  18916. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18917. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18918. this._effect.setColor3("vFogColor", scene.fogColor);
  18919. }
  18920. _super.prototype.bind.call(this, world, mesh);
  18921. };
  18922. StandardMaterial.prototype.getAnimatables = function () {
  18923. var results = [];
  18924. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18925. results.push(this.diffuseTexture);
  18926. }
  18927. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18928. results.push(this.ambientTexture);
  18929. }
  18930. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18931. results.push(this.opacityTexture);
  18932. }
  18933. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18934. results.push(this.reflectionTexture);
  18935. }
  18936. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18937. results.push(this.emissiveTexture);
  18938. }
  18939. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18940. results.push(this.specularTexture);
  18941. }
  18942. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18943. results.push(this.bumpTexture);
  18944. }
  18945. return results;
  18946. };
  18947. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18948. if (this.diffuseTexture) {
  18949. this.diffuseTexture.dispose();
  18950. }
  18951. if (this.ambientTexture) {
  18952. this.ambientTexture.dispose();
  18953. }
  18954. if (this.opacityTexture) {
  18955. this.opacityTexture.dispose();
  18956. }
  18957. if (this.reflectionTexture) {
  18958. this.reflectionTexture.dispose();
  18959. }
  18960. if (this.emissiveTexture) {
  18961. this.emissiveTexture.dispose();
  18962. }
  18963. if (this.specularTexture) {
  18964. this.specularTexture.dispose();
  18965. }
  18966. if (this.bumpTexture) {
  18967. this.bumpTexture.dispose();
  18968. }
  18969. _super.prototype.dispose.call(this, forceDisposeEffect);
  18970. };
  18971. StandardMaterial.prototype.clone = function (name) {
  18972. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18973. // Base material
  18974. this.copyTo(newStandardMaterial);
  18975. // Standard material
  18976. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18977. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18978. }
  18979. if (this.ambientTexture && this.ambientTexture.clone) {
  18980. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18981. }
  18982. if (this.opacityTexture && this.opacityTexture.clone) {
  18983. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18984. }
  18985. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18986. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18987. }
  18988. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18989. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18990. }
  18991. if (this.specularTexture && this.specularTexture.clone) {
  18992. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18993. }
  18994. if (this.bumpTexture && this.bumpTexture.clone) {
  18995. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18996. }
  18997. if (this.lightmapTexture && this.lightmapTexture.clone) {
  18998. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  18999. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19000. }
  19001. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19002. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19003. newStandardMaterial.specularColor = this.specularColor.clone();
  19004. newStandardMaterial.specularPower = this.specularPower;
  19005. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19006. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19007. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19008. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19009. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19010. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19011. newStandardMaterial.roughness = this.roughness;
  19012. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19013. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19014. }
  19015. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19016. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19017. }
  19018. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19019. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19020. }
  19021. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19022. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19023. }
  19024. return newStandardMaterial;
  19025. };
  19026. // Statics
  19027. // Flags used to enable or disable a type of texture for all Standard Materials
  19028. StandardMaterial.DiffuseTextureEnabled = true;
  19029. StandardMaterial.AmbientTextureEnabled = true;
  19030. StandardMaterial.OpacityTextureEnabled = true;
  19031. StandardMaterial.ReflectionTextureEnabled = true;
  19032. StandardMaterial.EmissiveTextureEnabled = true;
  19033. StandardMaterial.SpecularTextureEnabled = true;
  19034. StandardMaterial.BumpTextureEnabled = true;
  19035. StandardMaterial.FresnelEnabled = true;
  19036. StandardMaterial.LightmapEnabled = true;
  19037. return StandardMaterial;
  19038. })(BABYLON.Material);
  19039. BABYLON.StandardMaterial = StandardMaterial;
  19040. })(BABYLON || (BABYLON = {}));
  19041. var BABYLON;
  19042. (function (BABYLON) {
  19043. var MultiMaterial = (function (_super) {
  19044. __extends(MultiMaterial, _super);
  19045. function MultiMaterial(name, scene) {
  19046. _super.call(this, name, scene, true);
  19047. this.subMaterials = new Array();
  19048. scene.multiMaterials.push(this);
  19049. }
  19050. // Properties
  19051. MultiMaterial.prototype.getSubMaterial = function (index) {
  19052. if (index < 0 || index >= this.subMaterials.length) {
  19053. return this.getScene().defaultMaterial;
  19054. }
  19055. return this.subMaterials[index];
  19056. };
  19057. // Methods
  19058. MultiMaterial.prototype.isReady = function (mesh) {
  19059. for (var index = 0; index < this.subMaterials.length; index++) {
  19060. var subMaterial = this.subMaterials[index];
  19061. if (subMaterial) {
  19062. if (!this.subMaterials[index].isReady(mesh)) {
  19063. return false;
  19064. }
  19065. }
  19066. }
  19067. return true;
  19068. };
  19069. MultiMaterial.prototype.clone = function (name) {
  19070. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19071. for (var index = 0; index < this.subMaterials.length; index++) {
  19072. var subMaterial = this.subMaterials[index];
  19073. newMultiMaterial.subMaterials.push(subMaterial);
  19074. }
  19075. return newMultiMaterial;
  19076. };
  19077. return MultiMaterial;
  19078. })(BABYLON.Material);
  19079. BABYLON.MultiMaterial = MultiMaterial;
  19080. })(BABYLON || (BABYLON = {}));
  19081. var BABYLON;
  19082. (function (BABYLON) {
  19083. var SceneLoader = (function () {
  19084. function SceneLoader() {
  19085. }
  19086. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19087. get: function () {
  19088. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19089. },
  19090. set: function (value) {
  19091. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19092. },
  19093. enumerable: true,
  19094. configurable: true
  19095. });
  19096. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19097. get: function () {
  19098. return SceneLoader._ShowLoadingScreen;
  19099. },
  19100. set: function (value) {
  19101. SceneLoader._ShowLoadingScreen = value;
  19102. },
  19103. enumerable: true,
  19104. configurable: true
  19105. });
  19106. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19107. var dotPosition = sceneFilename.lastIndexOf(".");
  19108. var queryStringPosition = sceneFilename.indexOf("?");
  19109. if (queryStringPosition === -1) {
  19110. queryStringPosition = sceneFilename.length;
  19111. }
  19112. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19113. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19114. var plugin = this._registeredPlugins[index];
  19115. if (plugin.extensions.indexOf(extension) !== -1) {
  19116. return plugin;
  19117. }
  19118. }
  19119. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19120. };
  19121. // Public functions
  19122. SceneLoader.RegisterPlugin = function (plugin) {
  19123. plugin.extensions = plugin.extensions.toLowerCase();
  19124. SceneLoader._registeredPlugins.push(plugin);
  19125. };
  19126. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19127. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19128. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19129. return;
  19130. }
  19131. var loadingToken = {};
  19132. scene._addPendingData(loadingToken);
  19133. var manifestChecked = function (success) {
  19134. scene.database = database;
  19135. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19136. var importMeshFromData = function (data) {
  19137. var meshes = [];
  19138. var particleSystems = [];
  19139. var skeletons = [];
  19140. try {
  19141. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19142. if (onerror) {
  19143. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19144. }
  19145. scene._removePendingData(loadingToken);
  19146. return;
  19147. }
  19148. }
  19149. catch (e) {
  19150. if (onerror) {
  19151. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19152. }
  19153. scene._removePendingData(loadingToken);
  19154. return;
  19155. }
  19156. if (onsuccess) {
  19157. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19158. onsuccess(meshes, particleSystems, skeletons);
  19159. scene._removePendingData(loadingToken);
  19160. }
  19161. };
  19162. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19163. // Direct load
  19164. importMeshFromData(sceneFilename.substr(5));
  19165. return;
  19166. }
  19167. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19168. importMeshFromData(data);
  19169. }, progressCallBack, database);
  19170. };
  19171. if (scene.getEngine().enableOfflineSupport) {
  19172. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19173. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19174. }
  19175. else {
  19176. manifestChecked(true);
  19177. }
  19178. };
  19179. /**
  19180. * Load a scene
  19181. * @param rootUrl a string that defines the root url for scene and resources
  19182. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19183. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19184. */
  19185. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19186. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19187. };
  19188. /**
  19189. * Append a scene
  19190. * @param rootUrl a string that defines the root url for scene and resources
  19191. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19192. * @param scene is the instance of BABYLON.Scene to append to
  19193. */
  19194. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19195. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19196. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19197. return;
  19198. }
  19199. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19200. var database;
  19201. var loadingToken = {};
  19202. scene._addPendingData(loadingToken);
  19203. if (SceneLoader.ShowLoadingScreen) {
  19204. scene.getEngine().displayLoadingUI();
  19205. }
  19206. var loadSceneFromData = function (data) {
  19207. scene.database = database;
  19208. if (!plugin.load(scene, data, rootUrl)) {
  19209. if (onerror) {
  19210. onerror(scene);
  19211. }
  19212. scene._removePendingData(loadingToken);
  19213. scene.getEngine().hideLoadingUI();
  19214. return;
  19215. }
  19216. if (onsuccess) {
  19217. onsuccess(scene);
  19218. }
  19219. scene._removePendingData(loadingToken);
  19220. if (SceneLoader.ShowLoadingScreen) {
  19221. scene.executeWhenReady(function () {
  19222. scene.getEngine().hideLoadingUI();
  19223. });
  19224. }
  19225. };
  19226. var manifestChecked = function (success) {
  19227. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19228. };
  19229. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19230. // Direct load
  19231. loadSceneFromData(sceneFilename.substr(5));
  19232. return;
  19233. }
  19234. if (rootUrl.indexOf("file:") === -1) {
  19235. if (scene.getEngine().enableOfflineSupport) {
  19236. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19237. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19238. }
  19239. else {
  19240. manifestChecked(true);
  19241. }
  19242. }
  19243. else {
  19244. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19245. }
  19246. };
  19247. // Flags
  19248. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19249. SceneLoader._ShowLoadingScreen = true;
  19250. // Members
  19251. SceneLoader._registeredPlugins = new Array();
  19252. return SceneLoader;
  19253. })();
  19254. BABYLON.SceneLoader = SceneLoader;
  19255. ;
  19256. })(BABYLON || (BABYLON = {}));
  19257. var BABYLON;
  19258. (function (BABYLON) {
  19259. var Internals;
  19260. (function (Internals) {
  19261. var checkColors4 = function (colors, count) {
  19262. // Check if color3 was used
  19263. if (colors.length === count * 3) {
  19264. var colors4 = [];
  19265. for (var index = 0; index < colors.length; index += 3) {
  19266. var newIndex = (index / 3) * 4;
  19267. colors4[newIndex] = colors[index];
  19268. colors4[newIndex + 1] = colors[index + 1];
  19269. colors4[newIndex + 2] = colors[index + 2];
  19270. colors4[newIndex + 3] = 1.0;
  19271. }
  19272. return colors4;
  19273. }
  19274. return colors;
  19275. };
  19276. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19277. var texture = null;
  19278. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19279. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19280. texture.name = parsedTexture.name;
  19281. texture.hasAlpha = parsedTexture.hasAlpha;
  19282. texture.level = parsedTexture.level;
  19283. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19284. }
  19285. return texture;
  19286. };
  19287. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19288. if (parsedTexture.isCube) {
  19289. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19290. }
  19291. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19292. return null;
  19293. }
  19294. var texture;
  19295. if (parsedTexture.mirrorPlane) {
  19296. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19297. texture._waitingRenderList = parsedTexture.renderList;
  19298. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19299. }
  19300. else if (parsedTexture.isRenderTarget) {
  19301. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19302. texture._waitingRenderList = parsedTexture.renderList;
  19303. }
  19304. else {
  19305. if (parsedTexture.base64String) {
  19306. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19307. }
  19308. else {
  19309. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19310. }
  19311. }
  19312. texture.name = parsedTexture.name;
  19313. texture.hasAlpha = parsedTexture.hasAlpha;
  19314. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19315. texture.level = parsedTexture.level;
  19316. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19317. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19318. texture.uOffset = parsedTexture.uOffset;
  19319. texture.vOffset = parsedTexture.vOffset;
  19320. texture.uScale = parsedTexture.uScale;
  19321. texture.vScale = parsedTexture.vScale;
  19322. texture.uAng = parsedTexture.uAng;
  19323. texture.vAng = parsedTexture.vAng;
  19324. texture.wAng = parsedTexture.wAng;
  19325. texture.wrapU = parsedTexture.wrapU;
  19326. texture.wrapV = parsedTexture.wrapV;
  19327. // Animations
  19328. if (parsedTexture.animations) {
  19329. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19330. var parsedAnimation = parsedTexture.animations[animationIndex];
  19331. texture.animations.push(parseAnimation(parsedAnimation));
  19332. }
  19333. }
  19334. return texture;
  19335. };
  19336. var parseSkeleton = function (parsedSkeleton, scene) {
  19337. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19338. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19339. var parsedBone = parsedSkeleton.bones[index];
  19340. var parentBone = null;
  19341. if (parsedBone.parentBoneIndex > -1) {
  19342. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19343. }
  19344. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19345. if (parsedBone.animation) {
  19346. bone.animations.push(parseAnimation(parsedBone.animation));
  19347. }
  19348. }
  19349. return skeleton;
  19350. };
  19351. var parseFresnelParameters = function (parsedFresnelParameters) {
  19352. var fresnelParameters = new BABYLON.FresnelParameters();
  19353. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19354. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19355. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19356. fresnelParameters.bias = parsedFresnelParameters.bias;
  19357. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19358. return fresnelParameters;
  19359. };
  19360. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19361. var material;
  19362. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19363. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19364. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19365. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19366. material.specularPower = parsedMaterial.specularPower;
  19367. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19368. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19369. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19370. material.alpha = parsedMaterial.alpha;
  19371. material.id = parsedMaterial.id;
  19372. if (parsedMaterial.disableDepthWrite) {
  19373. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19374. }
  19375. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19376. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19377. material.wireframe = parsedMaterial.wireframe;
  19378. if (parsedMaterial.diffuseTexture) {
  19379. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19380. }
  19381. if (parsedMaterial.diffuseFresnelParameters) {
  19382. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19383. }
  19384. if (parsedMaterial.ambientTexture) {
  19385. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19386. }
  19387. if (parsedMaterial.opacityTexture) {
  19388. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19389. }
  19390. if (parsedMaterial.opacityFresnelParameters) {
  19391. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19392. }
  19393. if (parsedMaterial.reflectionTexture) {
  19394. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19395. }
  19396. if (parsedMaterial.reflectionFresnelParameters) {
  19397. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19398. }
  19399. if (parsedMaterial.emissiveTexture) {
  19400. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19401. }
  19402. if (parsedMaterial.lightmapTexture) {
  19403. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19404. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19405. }
  19406. if (parsedMaterial.emissiveFresnelParameters) {
  19407. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19408. }
  19409. if (parsedMaterial.specularTexture) {
  19410. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19411. }
  19412. if (parsedMaterial.bumpTexture) {
  19413. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19414. }
  19415. if (parsedMaterial.checkReadyOnlyOnce) {
  19416. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19417. }
  19418. return material;
  19419. };
  19420. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19421. for (var index = 0; index < parsedData.materials.length; index++) {
  19422. var parsedMaterial = parsedData.materials[index];
  19423. if (parsedMaterial.id === id) {
  19424. return parseMaterial(parsedMaterial, scene, rootUrl);
  19425. }
  19426. }
  19427. return null;
  19428. };
  19429. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19430. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19431. multiMaterial.id = parsedMultiMaterial.id;
  19432. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19433. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19434. var subMatId = parsedMultiMaterial.materials[matIndex];
  19435. if (subMatId) {
  19436. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19437. }
  19438. else {
  19439. multiMaterial.subMaterials.push(null);
  19440. }
  19441. }
  19442. return multiMaterial;
  19443. };
  19444. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19445. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19446. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19447. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19448. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19449. var parsedFlare = parsedLensFlareSystem.flares[index];
  19450. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19451. }
  19452. return lensFlareSystem;
  19453. };
  19454. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19455. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19456. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19457. if (parsedParticleSystem.textureName) {
  19458. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19459. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19460. }
  19461. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19462. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19463. particleSystem.minSize = parsedParticleSystem.minSize;
  19464. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19465. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19466. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19467. particleSystem.emitter = emitter;
  19468. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19469. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19470. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19471. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19472. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19473. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19474. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19475. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19476. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19477. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19478. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19479. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19480. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19481. particleSystem.start();
  19482. return particleSystem;
  19483. };
  19484. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19485. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19486. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19487. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19488. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19489. shadowGenerator.getShadowMap().renderList.push(mesh);
  19490. }
  19491. if (parsedShadowGenerator.usePoissonSampling) {
  19492. shadowGenerator.usePoissonSampling = true;
  19493. }
  19494. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19495. shadowGenerator.useVarianceShadowMap = true;
  19496. }
  19497. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19498. shadowGenerator.useBlurVarianceShadowMap = true;
  19499. if (parsedShadowGenerator.blurScale) {
  19500. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19501. }
  19502. if (parsedShadowGenerator.blurBoxOffset) {
  19503. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19504. }
  19505. }
  19506. if (parsedShadowGenerator.bias !== undefined) {
  19507. shadowGenerator.bias = parsedShadowGenerator.bias;
  19508. }
  19509. return shadowGenerator;
  19510. };
  19511. var parseAnimation = function (parsedAnimation) {
  19512. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19513. var dataType = parsedAnimation.dataType;
  19514. var keys = [];
  19515. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19516. var key = parsedAnimation.keys[index];
  19517. var data;
  19518. switch (dataType) {
  19519. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19520. data = key.values[0];
  19521. break;
  19522. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19523. data = BABYLON.Quaternion.FromArray(key.values);
  19524. break;
  19525. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19526. data = BABYLON.Matrix.FromArray(key.values);
  19527. break;
  19528. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19529. default:
  19530. data = BABYLON.Vector3.FromArray(key.values);
  19531. break;
  19532. }
  19533. keys.push({
  19534. frame: key.frame,
  19535. value: data
  19536. });
  19537. }
  19538. animation.setKeys(keys);
  19539. return animation;
  19540. };
  19541. var parseLight = function (parsedLight, scene) {
  19542. var light;
  19543. switch (parsedLight.type) {
  19544. case 0:
  19545. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19546. break;
  19547. case 1:
  19548. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19549. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19550. break;
  19551. case 2:
  19552. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19553. break;
  19554. case 3:
  19555. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19556. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19557. break;
  19558. }
  19559. light.id = parsedLight.id;
  19560. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19561. if (parsedLight.intensity !== undefined) {
  19562. light.intensity = parsedLight.intensity;
  19563. }
  19564. if (parsedLight.range) {
  19565. light.range = parsedLight.range;
  19566. }
  19567. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19568. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19569. if (parsedLight.excludedMeshesIds) {
  19570. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19571. }
  19572. // Parent
  19573. if (parsedLight.parentId) {
  19574. light._waitingParentId = parsedLight.parentId;
  19575. }
  19576. if (parsedLight.includedOnlyMeshesIds) {
  19577. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19578. }
  19579. // Animations
  19580. if (parsedLight.animations) {
  19581. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19582. var parsedAnimation = parsedLight.animations[animationIndex];
  19583. light.animations.push(parseAnimation(parsedAnimation));
  19584. }
  19585. }
  19586. if (parsedLight.autoAnimate) {
  19587. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19588. }
  19589. };
  19590. var parseCamera = function (parsedCamera, scene) {
  19591. var camera;
  19592. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19593. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19594. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19595. var alpha = parsedCamera.alpha;
  19596. var beta = parsedCamera.beta;
  19597. var radius = parsedCamera.radius;
  19598. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19599. var interaxial_distance = parsedCamera.interaxial_distance;
  19600. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19601. }
  19602. else {
  19603. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19604. }
  19605. }
  19606. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19607. interaxial_distance = parsedCamera.interaxial_distance;
  19608. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19609. }
  19610. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19611. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19612. }
  19613. else if (parsedCamera.type === "FollowCamera") {
  19614. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19615. camera.heightOffset = parsedCamera.heightOffset;
  19616. camera.radius = parsedCamera.radius;
  19617. camera.rotationOffset = parsedCamera.rotationOffset;
  19618. if (lockedTargetMesh)
  19619. camera.target = lockedTargetMesh;
  19620. }
  19621. else if (parsedCamera.type === "GamepadCamera") {
  19622. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19623. }
  19624. else if (parsedCamera.type === "TouchCamera") {
  19625. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19626. }
  19627. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19628. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19629. }
  19630. else if (parsedCamera.type === "WebVRFreeCamera") {
  19631. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19632. }
  19633. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19634. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19635. }
  19636. else {
  19637. // Free Camera is the default value
  19638. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19639. }
  19640. // apply 3d rig, when found
  19641. if (parsedCamera.cameraRigMode) {
  19642. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19643. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19644. }
  19645. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19646. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19647. camera.lockedTarget = lockedTargetMesh;
  19648. }
  19649. camera.id = parsedCamera.id;
  19650. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19651. // Parent
  19652. if (parsedCamera.parentId) {
  19653. camera._waitingParentId = parsedCamera.parentId;
  19654. }
  19655. // Target
  19656. if (parsedCamera.target) {
  19657. if (camera.setTarget) {
  19658. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19659. }
  19660. else {
  19661. //For ArcRotate
  19662. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19663. }
  19664. }
  19665. else {
  19666. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19667. }
  19668. camera.fov = parsedCamera.fov;
  19669. camera.minZ = parsedCamera.minZ;
  19670. camera.maxZ = parsedCamera.maxZ;
  19671. camera.speed = parsedCamera.speed;
  19672. camera.inertia = parsedCamera.inertia;
  19673. camera.checkCollisions = parsedCamera.checkCollisions;
  19674. camera.applyGravity = parsedCamera.applyGravity;
  19675. if (parsedCamera.ellipsoid) {
  19676. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19677. }
  19678. // Animations
  19679. if (parsedCamera.animations) {
  19680. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19681. var parsedAnimation = parsedCamera.animations[animationIndex];
  19682. camera.animations.push(parseAnimation(parsedAnimation));
  19683. }
  19684. }
  19685. if (parsedCamera.autoAnimate) {
  19686. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19687. }
  19688. // Layer Mask
  19689. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19690. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19691. }
  19692. else {
  19693. camera.layerMask = 0x0FFFFFFF;
  19694. }
  19695. return camera;
  19696. };
  19697. var parseGeometry = function (parsedGeometry, scene) {
  19698. var id = parsedGeometry.id;
  19699. return scene.getGeometryByID(id);
  19700. };
  19701. var parseBox = function (parsedBox, scene) {
  19702. if (parseGeometry(parsedBox, scene)) {
  19703. return null; // null since geometry could be something else than a box...
  19704. }
  19705. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19706. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19707. scene.pushGeometry(box, true);
  19708. return box;
  19709. };
  19710. var parseSphere = function (parsedSphere, scene) {
  19711. if (parseGeometry(parsedSphere, scene)) {
  19712. return null; // null since geometry could be something else than a sphere...
  19713. }
  19714. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19715. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19716. scene.pushGeometry(sphere, true);
  19717. return sphere;
  19718. };
  19719. var parseCylinder = function (parsedCylinder, scene) {
  19720. if (parseGeometry(parsedCylinder, scene)) {
  19721. return null; // null since geometry could be something else than a cylinder...
  19722. }
  19723. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19724. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19725. scene.pushGeometry(cylinder, true);
  19726. return cylinder;
  19727. };
  19728. var parseTorus = function (parsedTorus, scene) {
  19729. if (parseGeometry(parsedTorus, scene)) {
  19730. return null; // null since geometry could be something else than a torus...
  19731. }
  19732. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19733. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19734. scene.pushGeometry(torus, true);
  19735. return torus;
  19736. };
  19737. var parseGround = function (parsedGround, scene) {
  19738. if (parseGeometry(parsedGround, scene)) {
  19739. return null; // null since geometry could be something else than a ground...
  19740. }
  19741. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19742. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19743. scene.pushGeometry(ground, true);
  19744. return ground;
  19745. };
  19746. var parsePlane = function (parsedPlane, scene) {
  19747. if (parseGeometry(parsedPlane, scene)) {
  19748. return null; // null since geometry could be something else than a plane...
  19749. }
  19750. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19751. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19752. scene.pushGeometry(plane, true);
  19753. return plane;
  19754. };
  19755. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19756. if (parseGeometry(parsedTorusKnot, scene)) {
  19757. return null; // null since geometry could be something else than a torusKnot...
  19758. }
  19759. 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);
  19760. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19761. scene.pushGeometry(torusKnot, true);
  19762. return torusKnot;
  19763. };
  19764. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19765. if (parseGeometry(parsedVertexData, scene)) {
  19766. return null; // null since geometry could be a primitive
  19767. }
  19768. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19769. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19770. if (parsedVertexData.delayLoadingFile) {
  19771. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19772. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19773. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19774. geometry._delayInfo = [];
  19775. if (parsedVertexData.hasUVs) {
  19776. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19777. }
  19778. if (parsedVertexData.hasUVs2) {
  19779. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19780. }
  19781. if (parsedVertexData.hasUVs3) {
  19782. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19783. }
  19784. if (parsedVertexData.hasUVs4) {
  19785. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19786. }
  19787. if (parsedVertexData.hasUVs5) {
  19788. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19789. }
  19790. if (parsedVertexData.hasUVs6) {
  19791. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19792. }
  19793. if (parsedVertexData.hasColors) {
  19794. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19795. }
  19796. if (parsedVertexData.hasMatricesIndices) {
  19797. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19798. }
  19799. if (parsedVertexData.hasMatricesWeights) {
  19800. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19801. }
  19802. geometry._delayLoadingFunction = importVertexData;
  19803. }
  19804. else {
  19805. importVertexData(parsedVertexData, geometry);
  19806. }
  19807. scene.pushGeometry(geometry, true);
  19808. return geometry;
  19809. };
  19810. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19811. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19812. mesh.id = parsedMesh.id;
  19813. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19814. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19815. if (parsedMesh.rotationQuaternion) {
  19816. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19817. }
  19818. else if (parsedMesh.rotation) {
  19819. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19820. }
  19821. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19822. if (parsedMesh.localMatrix) {
  19823. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19824. }
  19825. else if (parsedMesh.pivotMatrix) {
  19826. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19827. }
  19828. mesh.setEnabled(parsedMesh.isEnabled);
  19829. mesh.isVisible = parsedMesh.isVisible;
  19830. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19831. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19832. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19833. if (parsedMesh.applyFog !== undefined) {
  19834. mesh.applyFog = parsedMesh.applyFog;
  19835. }
  19836. if (parsedMesh.pickable !== undefined) {
  19837. mesh.isPickable = parsedMesh.pickable;
  19838. }
  19839. if (parsedMesh.alphaIndex !== undefined) {
  19840. mesh.alphaIndex = parsedMesh.alphaIndex;
  19841. }
  19842. mesh.receiveShadows = parsedMesh.receiveShadows;
  19843. mesh.billboardMode = parsedMesh.billboardMode;
  19844. if (parsedMesh.visibility !== undefined) {
  19845. mesh.visibility = parsedMesh.visibility;
  19846. }
  19847. mesh.checkCollisions = parsedMesh.checkCollisions;
  19848. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19849. // freezeWorldMatrix
  19850. if (parsedMesh.freezeWorldMatrix) {
  19851. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19852. }
  19853. // Parent
  19854. if (parsedMesh.parentId) {
  19855. mesh._waitingParentId = parsedMesh.parentId;
  19856. }
  19857. // Actions
  19858. if (parsedMesh.actions !== undefined) {
  19859. mesh._waitingActions = parsedMesh.actions;
  19860. }
  19861. // Geometry
  19862. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19863. if (parsedMesh.delayLoadingFile) {
  19864. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19865. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19866. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19867. if (parsedMesh._binaryInfo) {
  19868. mesh._binaryInfo = parsedMesh._binaryInfo;
  19869. }
  19870. mesh._delayInfo = [];
  19871. if (parsedMesh.hasUVs) {
  19872. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19873. }
  19874. if (parsedMesh.hasUVs2) {
  19875. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19876. }
  19877. if (parsedMesh.hasUVs3) {
  19878. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19879. }
  19880. if (parsedMesh.hasUVs4) {
  19881. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19882. }
  19883. if (parsedMesh.hasUVs5) {
  19884. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19885. }
  19886. if (parsedMesh.hasUVs6) {
  19887. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19888. }
  19889. if (parsedMesh.hasColors) {
  19890. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19891. }
  19892. if (parsedMesh.hasMatricesIndices) {
  19893. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19894. }
  19895. if (parsedMesh.hasMatricesWeights) {
  19896. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19897. }
  19898. mesh._delayLoadingFunction = importGeometry;
  19899. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19900. mesh._checkDelayState();
  19901. }
  19902. }
  19903. else {
  19904. importGeometry(parsedMesh, mesh);
  19905. }
  19906. // Material
  19907. if (parsedMesh.materialId) {
  19908. mesh.setMaterialByID(parsedMesh.materialId);
  19909. }
  19910. else {
  19911. mesh.material = null;
  19912. }
  19913. // Skeleton
  19914. if (parsedMesh.skeletonId > -1) {
  19915. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19916. if (parsedMesh.numBoneInfluencers) {
  19917. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19918. }
  19919. }
  19920. // Physics
  19921. if (parsedMesh.physicsImpostor) {
  19922. if (!scene.isPhysicsEnabled()) {
  19923. scene.enablePhysics();
  19924. }
  19925. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19926. }
  19927. // Animations
  19928. if (parsedMesh.animations) {
  19929. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19930. var parsedAnimation = parsedMesh.animations[animationIndex];
  19931. mesh.animations.push(parseAnimation(parsedAnimation));
  19932. }
  19933. }
  19934. if (parsedMesh.autoAnimate) {
  19935. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19936. }
  19937. // Layer Mask
  19938. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19939. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19940. }
  19941. else {
  19942. mesh.layerMask = 0x0FFFFFFF;
  19943. }
  19944. // Instances
  19945. if (parsedMesh.instances) {
  19946. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19947. var parsedInstance = parsedMesh.instances[index];
  19948. var instance = mesh.createInstance(parsedInstance.name);
  19949. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19950. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19951. if (parsedInstance.rotationQuaternion) {
  19952. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19953. }
  19954. else if (parsedInstance.rotation) {
  19955. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19956. }
  19957. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19958. instance.checkCollisions = mesh.checkCollisions;
  19959. if (parsedMesh.animations) {
  19960. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19961. parsedAnimation = parsedMesh.animations[animationIndex];
  19962. instance.animations.push(parseAnimation(parsedAnimation));
  19963. }
  19964. }
  19965. }
  19966. }
  19967. return mesh;
  19968. };
  19969. var parseActions = function (parsedActions, object, scene) {
  19970. var actionManager = new BABYLON.ActionManager(scene);
  19971. if (object === null)
  19972. scene.actionManager = actionManager;
  19973. else
  19974. object.actionManager = actionManager;
  19975. // instanciate a new object
  19976. var instanciate = function (name, params) {
  19977. var newInstance = Object.create(BABYLON[name].prototype);
  19978. newInstance.constructor.apply(newInstance, params);
  19979. return newInstance;
  19980. };
  19981. var parseParameter = function (name, value, target, propertyPath) {
  19982. if (propertyPath === null) {
  19983. // String, boolean or float
  19984. var floatValue = parseFloat(value);
  19985. if (value === "true" || value === "false")
  19986. return value === "true";
  19987. else
  19988. return isNaN(floatValue) ? value : floatValue;
  19989. }
  19990. var effectiveTarget = propertyPath.split(".");
  19991. var values = value.split(",");
  19992. // Get effective Target
  19993. for (var i = 0; i < effectiveTarget.length; i++) {
  19994. target = target[effectiveTarget[i]];
  19995. }
  19996. // Return appropriate value with its type
  19997. if (typeof (target) === "boolean")
  19998. return values[0] === "true";
  19999. if (typeof (target) === "string")
  20000. return values[0];
  20001. // Parameters with multiple values such as Vector3 etc.
  20002. var split = new Array();
  20003. for (var i = 0; i < values.length; i++)
  20004. split.push(parseFloat(values[i]));
  20005. if (target instanceof BABYLON.Vector3)
  20006. return BABYLON.Vector3.FromArray(split);
  20007. if (target instanceof BABYLON.Vector4)
  20008. return BABYLON.Vector4.FromArray(split);
  20009. if (target instanceof BABYLON.Color3)
  20010. return BABYLON.Color3.FromArray(split);
  20011. if (target instanceof BABYLON.Color4)
  20012. return BABYLON.Color4.FromArray(split);
  20013. return parseFloat(values[0]);
  20014. };
  20015. // traverse graph per trigger
  20016. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20017. if (combineArray === void 0) { combineArray = null; }
  20018. if (parsedAction.detached)
  20019. return;
  20020. var parameters = new Array();
  20021. var target = null;
  20022. var propertyPath = null;
  20023. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20024. // Parameters
  20025. if (parsedAction.type === 2)
  20026. parameters.push(actionManager);
  20027. else
  20028. parameters.push(trigger);
  20029. if (combine) {
  20030. var actions = new Array();
  20031. for (var j = 0; j < parsedAction.combine.length; j++) {
  20032. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20033. }
  20034. parameters.push(actions);
  20035. }
  20036. else {
  20037. for (var i = 0; i < parsedAction.properties.length; i++) {
  20038. var value = parsedAction.properties[i].value;
  20039. var name = parsedAction.properties[i].name;
  20040. var targetType = parsedAction.properties[i].targetType;
  20041. if (name === "target")
  20042. if (targetType !== null && targetType === "SceneProperties")
  20043. value = target = scene;
  20044. else
  20045. value = target = scene.getNodeByName(value);
  20046. else if (name === "parent")
  20047. value = scene.getNodeByName(value);
  20048. else if (name === "sound")
  20049. value = scene.getSoundByName(value);
  20050. else if (name !== "propertyPath") {
  20051. if (parsedAction.type === 2 && name === "operator")
  20052. value = BABYLON.ValueCondition[value];
  20053. else
  20054. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20055. }
  20056. else {
  20057. propertyPath = value;
  20058. }
  20059. parameters.push(value);
  20060. }
  20061. }
  20062. if (combineArray === null) {
  20063. parameters.push(condition);
  20064. }
  20065. else {
  20066. parameters.push(null);
  20067. }
  20068. // If interpolate value action
  20069. if (parsedAction.name === "InterpolateValueAction") {
  20070. var param = parameters[parameters.length - 2];
  20071. parameters[parameters.length - 1] = param;
  20072. parameters[parameters.length - 2] = condition;
  20073. }
  20074. // Action or condition(s) and not CombineAction
  20075. var newAction = instanciate(parsedAction.name, parameters);
  20076. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20077. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20078. if (action)
  20079. action.then(nothing);
  20080. else
  20081. actionManager.registerAction(nothing);
  20082. action = nothing;
  20083. }
  20084. if (combineArray === null) {
  20085. if (newAction instanceof BABYLON.Condition) {
  20086. condition = newAction;
  20087. newAction = action;
  20088. }
  20089. else {
  20090. condition = null;
  20091. if (action)
  20092. action.then(newAction);
  20093. else
  20094. actionManager.registerAction(newAction);
  20095. }
  20096. }
  20097. else {
  20098. combineArray.push(newAction);
  20099. }
  20100. for (var i = 0; i < parsedAction.children.length; i++)
  20101. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20102. };
  20103. // triggers
  20104. for (var i = 0; i < parsedActions.children.length; i++) {
  20105. var triggerParams;
  20106. var trigger = parsedActions.children[i];
  20107. if (trigger.properties.length > 0) {
  20108. var param = trigger.properties[0].value;
  20109. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20110. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20111. }
  20112. else
  20113. triggerParams = BABYLON.ActionManager[trigger.name];
  20114. for (var j = 0; j < trigger.children.length; j++) {
  20115. if (!trigger.detached)
  20116. traverse(trigger.children[j], triggerParams, null, null);
  20117. }
  20118. }
  20119. };
  20120. var parseSound = function (parsedSound, scene, rootUrl) {
  20121. var soundName = parsedSound.name;
  20122. var soundUrl = rootUrl + soundName;
  20123. var options = {
  20124. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20125. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20126. rolloffFactor: parsedSound.rolloffFactor,
  20127. refDistance: parsedSound.refDistance,
  20128. distanceModel: parsedSound.distanceModel,
  20129. playbackRate: parsedSound.playbackRate
  20130. };
  20131. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20132. scene._addPendingData(newSound);
  20133. if (parsedSound.position) {
  20134. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20135. newSound.setPosition(soundPosition);
  20136. }
  20137. if (parsedSound.isDirectional) {
  20138. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20139. if (parsedSound.localDirectionToMesh) {
  20140. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20141. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20142. }
  20143. }
  20144. if (parsedSound.connectedMeshId) {
  20145. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20146. if (connectedMesh) {
  20147. newSound.attachToMesh(connectedMesh);
  20148. }
  20149. }
  20150. };
  20151. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20152. names = (names instanceof Array) ? names : [names];
  20153. for (var i in names) {
  20154. if (mesh.name === names[i]) {
  20155. hierarchyIds.push(mesh.id);
  20156. return true;
  20157. }
  20158. }
  20159. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20160. hierarchyIds.push(mesh.id);
  20161. return true;
  20162. }
  20163. return false;
  20164. };
  20165. var importVertexData = function (parsedVertexData, geometry) {
  20166. var vertexData = new BABYLON.VertexData();
  20167. // positions
  20168. var positions = parsedVertexData.positions;
  20169. if (positions) {
  20170. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20171. }
  20172. // normals
  20173. var normals = parsedVertexData.normals;
  20174. if (normals) {
  20175. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20176. }
  20177. // uvs
  20178. var uvs = parsedVertexData.uvs;
  20179. if (uvs) {
  20180. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20181. }
  20182. // uv2s
  20183. var uv2s = parsedVertexData.uv2s;
  20184. if (uv2s) {
  20185. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20186. }
  20187. // uv3s
  20188. var uv3s = parsedVertexData.uv3s;
  20189. if (uv3s) {
  20190. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20191. }
  20192. // uv4s
  20193. var uv4s = parsedVertexData.uv4s;
  20194. if (uv4s) {
  20195. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20196. }
  20197. // uv5s
  20198. var uv5s = parsedVertexData.uv5s;
  20199. if (uv5s) {
  20200. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20201. }
  20202. // uv6s
  20203. var uv6s = parsedVertexData.uv6s;
  20204. if (uv6s) {
  20205. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20206. }
  20207. // colors
  20208. var colors = parsedVertexData.colors;
  20209. if (colors) {
  20210. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20211. }
  20212. // matricesIndices
  20213. var matricesIndices = parsedVertexData.matricesIndices;
  20214. if (matricesIndices) {
  20215. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20216. }
  20217. // matricesWeights
  20218. var matricesWeights = parsedVertexData.matricesWeights;
  20219. if (matricesWeights) {
  20220. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20221. }
  20222. // indices
  20223. var indices = parsedVertexData.indices;
  20224. if (indices) {
  20225. vertexData.indices = indices;
  20226. }
  20227. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20228. };
  20229. var importGeometry = function (parsedGeometry, mesh) {
  20230. var scene = mesh.getScene();
  20231. // Geometry
  20232. var geometryId = parsedGeometry.geometryId;
  20233. if (geometryId) {
  20234. var geometry = scene.getGeometryByID(geometryId);
  20235. if (geometry) {
  20236. geometry.applyToMesh(mesh);
  20237. }
  20238. }
  20239. else if (parsedGeometry instanceof ArrayBuffer) {
  20240. var binaryInfo = mesh._binaryInfo;
  20241. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20242. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20243. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20244. }
  20245. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20246. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20247. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20248. }
  20249. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20250. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20251. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20252. }
  20253. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20254. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20255. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20256. }
  20257. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20258. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20259. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20260. }
  20261. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20262. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20263. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20264. }
  20265. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20266. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20267. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20268. }
  20269. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20270. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20271. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20272. }
  20273. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20274. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20275. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20276. }
  20277. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20278. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20279. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20280. }
  20281. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20282. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20283. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20284. }
  20285. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20286. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20287. mesh.setIndices(indicesData);
  20288. }
  20289. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20290. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20291. mesh.subMeshes = [];
  20292. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20293. var materialIndex = subMeshesData[(i * 5) + 0];
  20294. var verticesStart = subMeshesData[(i * 5) + 1];
  20295. var verticesCount = subMeshesData[(i * 5) + 2];
  20296. var indexStart = subMeshesData[(i * 5) + 3];
  20297. var indexCount = subMeshesData[(i * 5) + 4];
  20298. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20299. }
  20300. }
  20301. }
  20302. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20303. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20304. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20305. if (parsedGeometry.uvs) {
  20306. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20307. }
  20308. if (parsedGeometry.uvs2) {
  20309. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20310. }
  20311. if (parsedGeometry.uvs3) {
  20312. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20313. }
  20314. if (parsedGeometry.uvs4) {
  20315. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20316. }
  20317. if (parsedGeometry.uvs5) {
  20318. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20319. }
  20320. if (parsedGeometry.uvs6) {
  20321. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20322. }
  20323. if (parsedGeometry.colors) {
  20324. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20325. }
  20326. if (parsedGeometry.matricesIndices) {
  20327. if (!parsedGeometry.matricesIndices._isExpanded) {
  20328. var floatIndices = [];
  20329. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20330. var matricesIndex = parsedGeometry.matricesIndices[i];
  20331. floatIndices.push(matricesIndex & 0x000000FF);
  20332. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20333. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20334. floatIndices.push(matricesIndex >> 24);
  20335. }
  20336. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20337. }
  20338. else {
  20339. delete parsedGeometry.matricesIndices._isExpanded;
  20340. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20341. }
  20342. }
  20343. if (parsedGeometry.matricesWeights) {
  20344. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20345. }
  20346. mesh.setIndices(parsedGeometry.indices);
  20347. }
  20348. // SubMeshes
  20349. if (parsedGeometry.subMeshes) {
  20350. mesh.subMeshes = [];
  20351. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20352. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20353. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20354. }
  20355. }
  20356. // Flat shading
  20357. if (mesh._shouldGenerateFlatShading) {
  20358. mesh.convertToFlatShadedMesh();
  20359. delete mesh._shouldGenerateFlatShading;
  20360. }
  20361. // Update
  20362. mesh.computeWorldMatrix(true);
  20363. // Octree
  20364. if (scene._selectionOctree) {
  20365. scene._selectionOctree.addMesh(mesh);
  20366. }
  20367. };
  20368. BABYLON.SceneLoader.RegisterPlugin({
  20369. extensions: ".babylon",
  20370. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20371. var parsedData = JSON.parse(data);
  20372. var loadedSkeletonsIds = [];
  20373. var loadedMaterialsIds = [];
  20374. var hierarchyIds = [];
  20375. for (var index = 0; index < parsedData.meshes.length; index++) {
  20376. var parsedMesh = parsedData.meshes[index];
  20377. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20378. if (meshesNames instanceof Array) {
  20379. // Remove found mesh name from list.
  20380. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20381. }
  20382. //Geometry?
  20383. if (parsedMesh.geometryId) {
  20384. //does the file contain geometries?
  20385. if (parsedData.geometries) {
  20386. //find the correct geometry and add it to the scene
  20387. var found = false;
  20388. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20389. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20390. return;
  20391. }
  20392. else {
  20393. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20394. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20395. switch (geometryType) {
  20396. case "boxes":
  20397. parseBox(parsedGeometryData, scene);
  20398. break;
  20399. case "spheres":
  20400. parseSphere(parsedGeometryData, scene);
  20401. break;
  20402. case "cylinders":
  20403. parseCylinder(parsedGeometryData, scene);
  20404. break;
  20405. case "toruses":
  20406. parseTorus(parsedGeometryData, scene);
  20407. break;
  20408. case "grounds":
  20409. parseGround(parsedGeometryData, scene);
  20410. break;
  20411. case "planes":
  20412. parsePlane(parsedGeometryData, scene);
  20413. break;
  20414. case "torusKnots":
  20415. parseTorusKnot(parsedGeometryData, scene);
  20416. break;
  20417. case "vertexData":
  20418. parseVertexData(parsedGeometryData, scene, rootUrl);
  20419. break;
  20420. }
  20421. found = true;
  20422. }
  20423. });
  20424. }
  20425. });
  20426. if (!found) {
  20427. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20428. }
  20429. }
  20430. }
  20431. // Material ?
  20432. if (parsedMesh.materialId) {
  20433. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20434. if (!materialFound && parsedData.multiMaterials) {
  20435. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20436. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20437. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20438. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20439. var subMatId = parsedMultiMaterial.materials[matIndex];
  20440. loadedMaterialsIds.push(subMatId);
  20441. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20442. }
  20443. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20444. parseMultiMaterial(parsedMultiMaterial, scene);
  20445. materialFound = true;
  20446. break;
  20447. }
  20448. }
  20449. }
  20450. if (!materialFound) {
  20451. loadedMaterialsIds.push(parsedMesh.materialId);
  20452. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20453. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20454. }
  20455. }
  20456. }
  20457. // Skeleton ?
  20458. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20459. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20460. if (!skeletonAlreadyLoaded) {
  20461. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20462. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20463. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20464. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20465. loadedSkeletonsIds.push(parsedSkeleton.id);
  20466. }
  20467. }
  20468. }
  20469. }
  20470. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20471. meshes.push(mesh);
  20472. }
  20473. }
  20474. // Connecting parents
  20475. for (index = 0; index < scene.meshes.length; index++) {
  20476. var currentMesh = scene.meshes[index];
  20477. if (currentMesh._waitingParentId) {
  20478. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20479. currentMesh._waitingParentId = undefined;
  20480. }
  20481. }
  20482. // freeze world matrix application
  20483. for (index = 0; index < scene.meshes.length; index++) {
  20484. var currentMesh = scene.meshes[index];
  20485. if (currentMesh._waitingFreezeWorldMatrix) {
  20486. currentMesh.freezeWorldMatrix();
  20487. currentMesh._waitingFreezeWorldMatrix = undefined;
  20488. }
  20489. }
  20490. // Particles
  20491. if (parsedData.particleSystems) {
  20492. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20493. var parsedParticleSystem = parsedData.particleSystems[index];
  20494. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20495. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20496. }
  20497. }
  20498. }
  20499. return true;
  20500. },
  20501. load: function (scene, data, rootUrl) {
  20502. var parsedData = JSON.parse(data);
  20503. // Scene
  20504. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20505. scene.autoClear = parsedData.autoClear;
  20506. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20507. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20508. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20509. // Fog
  20510. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20511. scene.fogMode = parsedData.fogMode;
  20512. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20513. scene.fogStart = parsedData.fogStart;
  20514. scene.fogEnd = parsedData.fogEnd;
  20515. scene.fogDensity = parsedData.fogDensity;
  20516. }
  20517. // Lights
  20518. for (var index = 0; index < parsedData.lights.length; index++) {
  20519. var parsedLight = parsedData.lights[index];
  20520. parseLight(parsedLight, scene);
  20521. }
  20522. // Materials
  20523. if (parsedData.materials) {
  20524. for (index = 0; index < parsedData.materials.length; index++) {
  20525. var parsedMaterial = parsedData.materials[index];
  20526. parseMaterial(parsedMaterial, scene, rootUrl);
  20527. }
  20528. }
  20529. if (parsedData.multiMaterials) {
  20530. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20531. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20532. parseMultiMaterial(parsedMultiMaterial, scene);
  20533. }
  20534. }
  20535. // Skeletons
  20536. if (parsedData.skeletons) {
  20537. for (index = 0; index < parsedData.skeletons.length; index++) {
  20538. var parsedSkeleton = parsedData.skeletons[index];
  20539. parseSkeleton(parsedSkeleton, scene);
  20540. }
  20541. }
  20542. // Geometries
  20543. var geometries = parsedData.geometries;
  20544. if (geometries) {
  20545. // Boxes
  20546. var boxes = geometries.boxes;
  20547. if (boxes) {
  20548. for (index = 0; index < boxes.length; index++) {
  20549. var parsedBox = boxes[index];
  20550. parseBox(parsedBox, scene);
  20551. }
  20552. }
  20553. // Spheres
  20554. var spheres = geometries.spheres;
  20555. if (spheres) {
  20556. for (index = 0; index < spheres.length; index++) {
  20557. var parsedSphere = spheres[index];
  20558. parseSphere(parsedSphere, scene);
  20559. }
  20560. }
  20561. // Cylinders
  20562. var cylinders = geometries.cylinders;
  20563. if (cylinders) {
  20564. for (index = 0; index < cylinders.length; index++) {
  20565. var parsedCylinder = cylinders[index];
  20566. parseCylinder(parsedCylinder, scene);
  20567. }
  20568. }
  20569. // Toruses
  20570. var toruses = geometries.toruses;
  20571. if (toruses) {
  20572. for (index = 0; index < toruses.length; index++) {
  20573. var parsedTorus = toruses[index];
  20574. parseTorus(parsedTorus, scene);
  20575. }
  20576. }
  20577. // Grounds
  20578. var grounds = geometries.grounds;
  20579. if (grounds) {
  20580. for (index = 0; index < grounds.length; index++) {
  20581. var parsedGround = grounds[index];
  20582. parseGround(parsedGround, scene);
  20583. }
  20584. }
  20585. // Planes
  20586. var planes = geometries.planes;
  20587. if (planes) {
  20588. for (index = 0; index < planes.length; index++) {
  20589. var parsedPlane = planes[index];
  20590. parsePlane(parsedPlane, scene);
  20591. }
  20592. }
  20593. // TorusKnots
  20594. var torusKnots = geometries.torusKnots;
  20595. if (torusKnots) {
  20596. for (index = 0; index < torusKnots.length; index++) {
  20597. var parsedTorusKnot = torusKnots[index];
  20598. parseTorusKnot(parsedTorusKnot, scene);
  20599. }
  20600. }
  20601. // VertexData
  20602. var vertexData = geometries.vertexData;
  20603. if (vertexData) {
  20604. for (index = 0; index < vertexData.length; index++) {
  20605. var parsedVertexData = vertexData[index];
  20606. parseVertexData(parsedVertexData, scene, rootUrl);
  20607. }
  20608. }
  20609. }
  20610. // Meshes
  20611. for (index = 0; index < parsedData.meshes.length; index++) {
  20612. var parsedMesh = parsedData.meshes[index];
  20613. parseMesh(parsedMesh, scene, rootUrl);
  20614. }
  20615. // Cameras
  20616. for (index = 0; index < parsedData.cameras.length; index++) {
  20617. var parsedCamera = parsedData.cameras[index];
  20618. parseCamera(parsedCamera, scene);
  20619. }
  20620. if (parsedData.activeCameraID) {
  20621. scene.setActiveCameraByID(parsedData.activeCameraID);
  20622. }
  20623. // Browsing all the graph to connect the dots
  20624. for (index = 0; index < scene.cameras.length; index++) {
  20625. var camera = scene.cameras[index];
  20626. if (camera._waitingParentId) {
  20627. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20628. camera._waitingParentId = undefined;
  20629. }
  20630. }
  20631. for (index = 0; index < scene.lights.length; index++) {
  20632. var light = scene.lights[index];
  20633. if (light._waitingParentId) {
  20634. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20635. light._waitingParentId = undefined;
  20636. }
  20637. }
  20638. // Sounds
  20639. if (BABYLON.AudioEngine && parsedData.sounds) {
  20640. for (index = 0; index < parsedData.sounds.length; index++) {
  20641. var parsedSound = parsedData.sounds[index];
  20642. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20643. parseSound(parsedSound, scene, rootUrl);
  20644. }
  20645. else {
  20646. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20647. }
  20648. }
  20649. }
  20650. // Connect parents & children and parse actions
  20651. for (index = 0; index < scene.meshes.length; index++) {
  20652. var mesh = scene.meshes[index];
  20653. if (mesh._waitingParentId) {
  20654. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20655. mesh._waitingParentId = undefined;
  20656. }
  20657. if (mesh._waitingActions) {
  20658. parseActions(mesh._waitingActions, mesh, scene);
  20659. mesh._waitingActions = undefined;
  20660. }
  20661. }
  20662. // freeze world matrix application
  20663. for (index = 0; index < scene.meshes.length; index++) {
  20664. var currentMesh = scene.meshes[index];
  20665. if (currentMesh._waitingFreezeWorldMatrix) {
  20666. currentMesh.freezeWorldMatrix();
  20667. currentMesh._waitingFreezeWorldMatrix = undefined;
  20668. }
  20669. }
  20670. // Particles Systems
  20671. if (parsedData.particleSystems) {
  20672. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20673. var parsedParticleSystem = parsedData.particleSystems[index];
  20674. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20675. }
  20676. }
  20677. // Lens flares
  20678. if (parsedData.lensFlareSystems) {
  20679. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20680. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20681. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20682. }
  20683. }
  20684. // Shadows
  20685. if (parsedData.shadowGenerators) {
  20686. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20687. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20688. parseShadowGenerator(parsedShadowGenerator, scene);
  20689. }
  20690. }
  20691. // Actions (scene)
  20692. if (parsedData.actions) {
  20693. parseActions(parsedData.actions, null, scene);
  20694. }
  20695. // Finish
  20696. return true;
  20697. }
  20698. });
  20699. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20700. })(BABYLON || (BABYLON = {}));
  20701. var BABYLON;
  20702. (function (BABYLON) {
  20703. var SpriteManager = (function () {
  20704. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20706. this.name = name;
  20707. this.cellSize = cellSize;
  20708. this.sprites = new Array();
  20709. this.renderingGroupId = 0;
  20710. this.layerMask = 0x0FFFFFFF;
  20711. this.fogEnabled = true;
  20712. this.isPickable = false;
  20713. this._vertexDeclaration = [4, 4, 4, 4];
  20714. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20715. this._capacity = capacity;
  20716. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20717. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20718. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20719. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20720. this._scene = scene;
  20721. this._scene.spriteManagers.push(this);
  20722. // VBO
  20723. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20724. var indices = [];
  20725. var index = 0;
  20726. for (var count = 0; count < capacity; count++) {
  20727. indices.push(index);
  20728. indices.push(index + 1);
  20729. indices.push(index + 2);
  20730. indices.push(index);
  20731. indices.push(index + 2);
  20732. indices.push(index + 3);
  20733. index += 4;
  20734. }
  20735. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20736. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20737. // Effects
  20738. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20739. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20740. }
  20741. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20742. var arrayOffset = index * 16;
  20743. if (offsetX === 0)
  20744. offsetX = this._epsilon;
  20745. else if (offsetX === 1)
  20746. offsetX = 1 - this._epsilon;
  20747. if (offsetY === 0)
  20748. offsetY = this._epsilon;
  20749. else if (offsetY === 1)
  20750. offsetY = 1 - this._epsilon;
  20751. this._vertices[arrayOffset] = sprite.position.x;
  20752. this._vertices[arrayOffset + 1] = sprite.position.y;
  20753. this._vertices[arrayOffset + 2] = sprite.position.z;
  20754. this._vertices[arrayOffset + 3] = sprite.angle;
  20755. this._vertices[arrayOffset + 4] = sprite.width;
  20756. this._vertices[arrayOffset + 5] = sprite.height;
  20757. this._vertices[arrayOffset + 6] = offsetX;
  20758. this._vertices[arrayOffset + 7] = offsetY;
  20759. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20760. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20761. var offset = (sprite.cellIndex / rowSize) >> 0;
  20762. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20763. this._vertices[arrayOffset + 11] = offset;
  20764. // Color
  20765. this._vertices[arrayOffset + 12] = sprite.color.r;
  20766. this._vertices[arrayOffset + 13] = sprite.color.g;
  20767. this._vertices[arrayOffset + 14] = sprite.color.b;
  20768. this._vertices[arrayOffset + 15] = sprite.color.a;
  20769. };
  20770. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20771. var count = Math.min(this._capacity, this.sprites.length);
  20772. var min = BABYLON.Vector3.Zero();
  20773. var max = BABYLON.Vector3.Zero();
  20774. var distance = Number.MAX_VALUE;
  20775. var currentSprite;
  20776. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20777. var cameraView = camera.getViewMatrix();
  20778. for (var index = 0; index < count; index++) {
  20779. var sprite = this.sprites[index];
  20780. if (!sprite) {
  20781. continue;
  20782. }
  20783. if (predicate) {
  20784. if (!predicate(sprite)) {
  20785. continue;
  20786. }
  20787. }
  20788. else if (!sprite.isPickable) {
  20789. continue;
  20790. }
  20791. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20792. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20793. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20794. if (ray.intersectsBoxMinMax(min, max)) {
  20795. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20796. if (distance > currentDistance) {
  20797. distance = currentDistance;
  20798. currentSprite = sprite;
  20799. if (fastCheck) {
  20800. break;
  20801. }
  20802. }
  20803. }
  20804. }
  20805. if (currentSprite) {
  20806. var result = new BABYLON.PickingInfo();
  20807. result.hit = true;
  20808. result.pickedSprite = currentSprite;
  20809. result.distance = distance;
  20810. return result;
  20811. }
  20812. return null;
  20813. };
  20814. SpriteManager.prototype.render = function () {
  20815. // Check
  20816. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20817. return;
  20818. var engine = this._scene.getEngine();
  20819. var baseSize = this._spriteTexture.getBaseSize();
  20820. // Sprites
  20821. var deltaTime = engine.getDeltaTime();
  20822. var max = Math.min(this._capacity, this.sprites.length);
  20823. var rowSize = baseSize.width / this.cellSize;
  20824. var offset = 0;
  20825. for (var index = 0; index < max; index++) {
  20826. var sprite = this.sprites[index];
  20827. if (!sprite) {
  20828. continue;
  20829. }
  20830. sprite._animate(deltaTime);
  20831. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20832. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20833. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20834. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20835. }
  20836. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20837. // Render
  20838. var effect = this._effectBase;
  20839. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20840. effect = this._effectFog;
  20841. }
  20842. engine.enableEffect(effect);
  20843. var viewMatrix = this._scene.getViewMatrix();
  20844. effect.setTexture("diffuseSampler", this._spriteTexture);
  20845. effect.setMatrix("view", viewMatrix);
  20846. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20847. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20848. // Fog
  20849. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20850. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20851. effect.setColor3("vFogColor", this._scene.fogColor);
  20852. }
  20853. // VBOs
  20854. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20855. // Draw order
  20856. engine.setDepthFunctionToLessOrEqual();
  20857. effect.setBool("alphaTest", true);
  20858. engine.setColorWrite(false);
  20859. engine.draw(true, 0, max * 6);
  20860. engine.setColorWrite(true);
  20861. effect.setBool("alphaTest", false);
  20862. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20863. engine.draw(true, 0, max * 6);
  20864. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20865. };
  20866. SpriteManager.prototype.dispose = function () {
  20867. if (this._vertexBuffer) {
  20868. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20869. this._vertexBuffer = null;
  20870. }
  20871. if (this._indexBuffer) {
  20872. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20873. this._indexBuffer = null;
  20874. }
  20875. if (this._spriteTexture) {
  20876. this._spriteTexture.dispose();
  20877. this._spriteTexture = null;
  20878. }
  20879. // Remove from scene
  20880. var index = this._scene.spriteManagers.indexOf(this);
  20881. this._scene.spriteManagers.splice(index, 1);
  20882. // Callback
  20883. if (this.onDispose) {
  20884. this.onDispose();
  20885. }
  20886. };
  20887. return SpriteManager;
  20888. })();
  20889. BABYLON.SpriteManager = SpriteManager;
  20890. })(BABYLON || (BABYLON = {}));
  20891. var BABYLON;
  20892. (function (BABYLON) {
  20893. var Sprite = (function () {
  20894. function Sprite(name, manager) {
  20895. this.name = name;
  20896. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20897. this.width = 1.0;
  20898. this.height = 1.0;
  20899. this.angle = 0;
  20900. this.cellIndex = 0;
  20901. this.invertU = 0;
  20902. this.invertV = 0;
  20903. this.animations = new Array();
  20904. this.isPickable = false;
  20905. this._animationStarted = false;
  20906. this._loopAnimation = false;
  20907. this._fromIndex = 0;
  20908. this._toIndex = 0;
  20909. this._delay = 0;
  20910. this._direction = 1;
  20911. this._frameCount = 0;
  20912. this._time = 0;
  20913. this._manager = manager;
  20914. this._manager.sprites.push(this);
  20915. this.position = BABYLON.Vector3.Zero();
  20916. }
  20917. Object.defineProperty(Sprite.prototype, "size", {
  20918. get: function () {
  20919. return this.width;
  20920. },
  20921. set: function (value) {
  20922. this.width = value;
  20923. this.height = value;
  20924. },
  20925. enumerable: true,
  20926. configurable: true
  20927. });
  20928. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20929. this._fromIndex = from;
  20930. this._toIndex = to;
  20931. this._loopAnimation = loop;
  20932. this._delay = delay;
  20933. this._animationStarted = true;
  20934. this._direction = from < to ? 1 : -1;
  20935. this.cellIndex = from;
  20936. this._time = 0;
  20937. };
  20938. Sprite.prototype.stopAnimation = function () {
  20939. this._animationStarted = false;
  20940. };
  20941. Sprite.prototype._animate = function (deltaTime) {
  20942. if (!this._animationStarted)
  20943. return;
  20944. this._time += deltaTime;
  20945. if (this._time > this._delay) {
  20946. this._time = this._time % this._delay;
  20947. this.cellIndex += this._direction;
  20948. if (this.cellIndex == this._toIndex) {
  20949. if (this._loopAnimation) {
  20950. this.cellIndex = this._fromIndex;
  20951. }
  20952. else {
  20953. this._animationStarted = false;
  20954. if (this.disposeWhenFinishedAnimating) {
  20955. this.dispose();
  20956. }
  20957. }
  20958. }
  20959. }
  20960. };
  20961. Sprite.prototype.dispose = function () {
  20962. for (var i = 0; i < this._manager.sprites.length; i++) {
  20963. if (this._manager.sprites[i] == this) {
  20964. this._manager.sprites.splice(i, 1);
  20965. }
  20966. }
  20967. };
  20968. return Sprite;
  20969. })();
  20970. BABYLON.Sprite = Sprite;
  20971. })(BABYLON || (BABYLON = {}));
  20972. var BABYLON;
  20973. (function (BABYLON) {
  20974. var Layer = (function () {
  20975. function Layer(name, imgUrl, scene, isBackground, color) {
  20976. this.name = name;
  20977. this._vertexDeclaration = [2];
  20978. this._vertexStrideSize = 2 * 4;
  20979. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20980. this.isBackground = isBackground === undefined ? true : isBackground;
  20981. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20982. this._scene = scene;
  20983. this._scene.layers.push(this);
  20984. // VBO
  20985. var vertices = [];
  20986. vertices.push(1, 1);
  20987. vertices.push(-1, 1);
  20988. vertices.push(-1, -1);
  20989. vertices.push(1, -1);
  20990. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20991. // Indices
  20992. var indices = [];
  20993. indices.push(0);
  20994. indices.push(1);
  20995. indices.push(2);
  20996. indices.push(0);
  20997. indices.push(2);
  20998. indices.push(3);
  20999. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21000. // Effects
  21001. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21002. }
  21003. Layer.prototype.render = function () {
  21004. // Check
  21005. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21006. return;
  21007. var engine = this._scene.getEngine();
  21008. // Render
  21009. engine.enableEffect(this._effect);
  21010. engine.setState(false);
  21011. // Texture
  21012. this._effect.setTexture("textureSampler", this.texture);
  21013. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21014. // Color
  21015. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21016. // VBOs
  21017. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21018. // Draw order
  21019. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21020. engine.draw(true, 0, 6);
  21021. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21022. };
  21023. Layer.prototype.dispose = function () {
  21024. if (this._vertexBuffer) {
  21025. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21026. this._vertexBuffer = null;
  21027. }
  21028. if (this._indexBuffer) {
  21029. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21030. this._indexBuffer = null;
  21031. }
  21032. if (this.texture) {
  21033. this.texture.dispose();
  21034. this.texture = null;
  21035. }
  21036. // Remove from scene
  21037. var index = this._scene.layers.indexOf(this);
  21038. this._scene.layers.splice(index, 1);
  21039. // Callback
  21040. if (this.onDispose) {
  21041. this.onDispose();
  21042. }
  21043. };
  21044. return Layer;
  21045. })();
  21046. BABYLON.Layer = Layer;
  21047. })(BABYLON || (BABYLON = {}));
  21048. var BABYLON;
  21049. (function (BABYLON) {
  21050. var Particle = (function () {
  21051. function Particle() {
  21052. this.position = BABYLON.Vector3.Zero();
  21053. this.direction = BABYLON.Vector3.Zero();
  21054. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21055. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21056. this.lifeTime = 1.0;
  21057. this.age = 0;
  21058. this.size = 0;
  21059. this.angle = 0;
  21060. this.angularSpeed = 0;
  21061. }
  21062. Particle.prototype.copyTo = function (other) {
  21063. other.position.copyFrom(this.position);
  21064. other.direction.copyFrom(this.direction);
  21065. other.color.copyFrom(this.color);
  21066. other.colorStep.copyFrom(this.colorStep);
  21067. other.lifeTime = this.lifeTime;
  21068. other.age = this.age;
  21069. other.size = this.size;
  21070. other.angle = this.angle;
  21071. other.angularSpeed = this.angularSpeed;
  21072. };
  21073. return Particle;
  21074. })();
  21075. BABYLON.Particle = Particle;
  21076. })(BABYLON || (BABYLON = {}));
  21077. var BABYLON;
  21078. (function (BABYLON) {
  21079. var randomNumber = function (min, max) {
  21080. if (min === max) {
  21081. return (min);
  21082. }
  21083. var random = Math.random();
  21084. return ((random * (max - min)) + min);
  21085. };
  21086. var ParticleSystem = (function () {
  21087. function ParticleSystem(name, capacity, scene, customEffect) {
  21088. var _this = this;
  21089. this.name = name;
  21090. this.renderingGroupId = 0;
  21091. this.emitter = null;
  21092. this.emitRate = 10;
  21093. this.manualEmitCount = -1;
  21094. this.updateSpeed = 0.01;
  21095. this.targetStopDuration = 0;
  21096. this.disposeOnStop = false;
  21097. this.minEmitPower = 1;
  21098. this.maxEmitPower = 1;
  21099. this.minLifeTime = 1;
  21100. this.maxLifeTime = 1;
  21101. this.minSize = 1;
  21102. this.maxSize = 1;
  21103. this.minAngularSpeed = 0;
  21104. this.maxAngularSpeed = 0;
  21105. this.layerMask = 0x0FFFFFFF;
  21106. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21107. this.forceDepthWrite = false;
  21108. this.gravity = BABYLON.Vector3.Zero();
  21109. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21110. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21111. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21112. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21113. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21114. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21115. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21116. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21117. this.particles = new Array();
  21118. this._vertexDeclaration = [3, 4, 4];
  21119. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21120. this._stockParticles = new Array();
  21121. this._newPartsExcess = 0;
  21122. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21123. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21124. this._scaledDirection = BABYLON.Vector3.Zero();
  21125. this._scaledGravity = BABYLON.Vector3.Zero();
  21126. this._currentRenderId = -1;
  21127. this._started = false;
  21128. this._stopped = false;
  21129. this._actualFrame = 0;
  21130. this.id = name;
  21131. this._capacity = capacity;
  21132. this._scene = scene;
  21133. this._customEffect = customEffect;
  21134. scene.particleSystems.push(this);
  21135. // VBO
  21136. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21137. var indices = [];
  21138. var index = 0;
  21139. for (var count = 0; count < capacity; count++) {
  21140. indices.push(index);
  21141. indices.push(index + 1);
  21142. indices.push(index + 2);
  21143. indices.push(index);
  21144. indices.push(index + 2);
  21145. indices.push(index + 3);
  21146. index += 4;
  21147. }
  21148. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21149. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21150. // Default behaviors
  21151. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21152. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21153. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21154. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21155. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21156. };
  21157. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21158. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21159. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21160. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21161. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21162. };
  21163. this.updateFunction = function (particles) {
  21164. for (var index = 0; index < particles.length; index++) {
  21165. var particle = particles[index];
  21166. particle.age += _this._scaledUpdateSpeed;
  21167. if (particle.age >= particle.lifeTime) {
  21168. _this.recycleParticle(particle);
  21169. index--;
  21170. continue;
  21171. }
  21172. else {
  21173. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21174. particle.color.addInPlace(_this._scaledColorStep);
  21175. if (particle.color.a < 0)
  21176. particle.color.a = 0;
  21177. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21178. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21179. particle.position.addInPlace(_this._scaledDirection);
  21180. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21181. particle.direction.addInPlace(_this._scaledGravity);
  21182. }
  21183. }
  21184. };
  21185. }
  21186. ParticleSystem.prototype.recycleParticle = function (particle) {
  21187. var lastParticle = this.particles.pop();
  21188. if (lastParticle !== particle) {
  21189. lastParticle.copyTo(particle);
  21190. this._stockParticles.push(lastParticle);
  21191. }
  21192. };
  21193. ParticleSystem.prototype.getCapacity = function () {
  21194. return this._capacity;
  21195. };
  21196. ParticleSystem.prototype.isAlive = function () {
  21197. return this._alive;
  21198. };
  21199. ParticleSystem.prototype.isStarted = function () {
  21200. return this._started;
  21201. };
  21202. ParticleSystem.prototype.start = function () {
  21203. this._started = true;
  21204. this._stopped = false;
  21205. this._actualFrame = 0;
  21206. };
  21207. ParticleSystem.prototype.stop = function () {
  21208. this._stopped = true;
  21209. };
  21210. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21211. var offset = index * 11;
  21212. this._vertices[offset] = particle.position.x;
  21213. this._vertices[offset + 1] = particle.position.y;
  21214. this._vertices[offset + 2] = particle.position.z;
  21215. this._vertices[offset + 3] = particle.color.r;
  21216. this._vertices[offset + 4] = particle.color.g;
  21217. this._vertices[offset + 5] = particle.color.b;
  21218. this._vertices[offset + 6] = particle.color.a;
  21219. this._vertices[offset + 7] = particle.angle;
  21220. this._vertices[offset + 8] = particle.size;
  21221. this._vertices[offset + 9] = offsetX;
  21222. this._vertices[offset + 10] = offsetY;
  21223. };
  21224. ParticleSystem.prototype._update = function (newParticles) {
  21225. // Update current
  21226. this._alive = this.particles.length > 0;
  21227. this.updateFunction(this.particles);
  21228. // Add new ones
  21229. var worldMatrix;
  21230. if (this.emitter.position) {
  21231. worldMatrix = this.emitter.getWorldMatrix();
  21232. }
  21233. else {
  21234. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21235. }
  21236. for (var index = 0; index < newParticles; index++) {
  21237. if (this.particles.length === this._capacity) {
  21238. break;
  21239. }
  21240. if (this._stockParticles.length !== 0) {
  21241. var particle = this._stockParticles.pop();
  21242. particle.age = 0;
  21243. }
  21244. else {
  21245. particle = new BABYLON.Particle();
  21246. }
  21247. this.particles.push(particle);
  21248. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21249. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21250. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21251. particle.size = randomNumber(this.minSize, this.maxSize);
  21252. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21253. this.startPositionFunction(worldMatrix, particle.position);
  21254. var step = randomNumber(0, 1.0);
  21255. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21256. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21257. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21258. }
  21259. };
  21260. ParticleSystem.prototype._getEffect = function () {
  21261. if (this._customEffect) {
  21262. return this._customEffect;
  21263. }
  21264. ;
  21265. var defines = [];
  21266. if (this._scene.clipPlane) {
  21267. defines.push("#define CLIPPLANE");
  21268. }
  21269. // Effect
  21270. var join = defines.join("\n");
  21271. if (this._cachedDefines !== join) {
  21272. this._cachedDefines = join;
  21273. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21274. }
  21275. return this._effect;
  21276. };
  21277. ParticleSystem.prototype.animate = function () {
  21278. if (!this._started)
  21279. return;
  21280. var effect = this._getEffect();
  21281. // Check
  21282. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21283. return;
  21284. if (this._currentRenderId === this._scene.getRenderId()) {
  21285. return;
  21286. }
  21287. this._currentRenderId = this._scene.getRenderId();
  21288. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21289. // determine the number of particles we need to create
  21290. var emitCout;
  21291. if (this.manualEmitCount > -1) {
  21292. emitCout = this.manualEmitCount;
  21293. this.manualEmitCount = 0;
  21294. }
  21295. else {
  21296. emitCout = this.emitRate;
  21297. }
  21298. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21299. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21300. if (this._newPartsExcess > 1.0) {
  21301. newParticles += this._newPartsExcess >> 0;
  21302. this._newPartsExcess -= this._newPartsExcess >> 0;
  21303. }
  21304. this._alive = false;
  21305. if (!this._stopped) {
  21306. this._actualFrame += this._scaledUpdateSpeed;
  21307. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21308. this.stop();
  21309. }
  21310. else {
  21311. newParticles = 0;
  21312. }
  21313. this._update(newParticles);
  21314. // Stopped?
  21315. if (this._stopped) {
  21316. if (!this._alive) {
  21317. this._started = false;
  21318. if (this.disposeOnStop) {
  21319. this._scene._toBeDisposed.push(this);
  21320. }
  21321. }
  21322. }
  21323. // Update VBO
  21324. var offset = 0;
  21325. for (var index = 0; index < this.particles.length; index++) {
  21326. var particle = this.particles[index];
  21327. this._appendParticleVertex(offset++, particle, 0, 0);
  21328. this._appendParticleVertex(offset++, particle, 1, 0);
  21329. this._appendParticleVertex(offset++, particle, 1, 1);
  21330. this._appendParticleVertex(offset++, particle, 0, 1);
  21331. }
  21332. var engine = this._scene.getEngine();
  21333. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21334. };
  21335. ParticleSystem.prototype.render = function () {
  21336. var effect = this._getEffect();
  21337. // Check
  21338. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21339. return 0;
  21340. var engine = this._scene.getEngine();
  21341. // Render
  21342. engine.enableEffect(effect);
  21343. engine.setState(false);
  21344. var viewMatrix = this._scene.getViewMatrix();
  21345. effect.setTexture("diffuseSampler", this.particleTexture);
  21346. effect.setMatrix("view", viewMatrix);
  21347. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21348. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21349. if (this._scene.clipPlane) {
  21350. var clipPlane = this._scene.clipPlane;
  21351. var invView = viewMatrix.clone();
  21352. invView.invert();
  21353. effect.setMatrix("invView", invView);
  21354. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21355. }
  21356. // VBOs
  21357. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21358. // Draw order
  21359. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21360. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21361. }
  21362. else {
  21363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21364. }
  21365. if (this.forceDepthWrite) {
  21366. engine.setDepthWrite(true);
  21367. }
  21368. engine.draw(true, 0, this.particles.length * 6);
  21369. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21370. return this.particles.length;
  21371. };
  21372. ParticleSystem.prototype.dispose = function () {
  21373. if (this._vertexBuffer) {
  21374. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21375. this._vertexBuffer = null;
  21376. }
  21377. if (this._indexBuffer) {
  21378. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21379. this._indexBuffer = null;
  21380. }
  21381. if (this.particleTexture) {
  21382. this.particleTexture.dispose();
  21383. this.particleTexture = null;
  21384. }
  21385. // Remove from scene
  21386. var index = this._scene.particleSystems.indexOf(this);
  21387. this._scene.particleSystems.splice(index, 1);
  21388. // Callback
  21389. if (this.onDispose) {
  21390. this.onDispose();
  21391. }
  21392. };
  21393. // Clone
  21394. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21395. var result = new ParticleSystem(name, this._capacity, this._scene);
  21396. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21397. if (newEmitter === undefined) {
  21398. newEmitter = this.emitter;
  21399. }
  21400. result.emitter = newEmitter;
  21401. if (this.particleTexture) {
  21402. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21403. }
  21404. result.start();
  21405. return result;
  21406. };
  21407. // Statics
  21408. ParticleSystem.BLENDMODE_ONEONE = 0;
  21409. ParticleSystem.BLENDMODE_STANDARD = 1;
  21410. return ParticleSystem;
  21411. })();
  21412. BABYLON.ParticleSystem = ParticleSystem;
  21413. })(BABYLON || (BABYLON = {}));
  21414. var BABYLON;
  21415. (function (BABYLON) {
  21416. var AnimationRange = (function () {
  21417. function AnimationRange(name, from, to) {
  21418. this.name = name;
  21419. this.from = from;
  21420. this.to = to;
  21421. }
  21422. return AnimationRange;
  21423. })();
  21424. BABYLON.AnimationRange = AnimationRange;
  21425. var Animation = (function () {
  21426. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21427. this.name = name;
  21428. this.targetProperty = targetProperty;
  21429. this.framePerSecond = framePerSecond;
  21430. this.dataType = dataType;
  21431. this.loopMode = loopMode;
  21432. this._offsetsCache = {};
  21433. this._highLimitsCache = {};
  21434. this._stopped = false;
  21435. this.allowMatricesInterpolation = false;
  21436. this._ranges = new Array();
  21437. this.targetPropertyPath = targetProperty.split(".");
  21438. this.dataType = dataType;
  21439. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21440. }
  21441. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21442. var dataType = undefined;
  21443. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21444. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21445. }
  21446. else if (from instanceof BABYLON.Quaternion) {
  21447. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21448. }
  21449. else if (from instanceof BABYLON.Vector3) {
  21450. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21451. }
  21452. else if (from instanceof BABYLON.Vector2) {
  21453. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21454. }
  21455. else if (from instanceof BABYLON.Color3) {
  21456. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21457. }
  21458. if (dataType == undefined) {
  21459. return null;
  21460. }
  21461. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21462. var keys = [];
  21463. keys.push({ frame: 0, value: from });
  21464. keys.push({ frame: totalFrame, value: to });
  21465. animation.setKeys(keys);
  21466. if (easingFunction !== undefined) {
  21467. animation.setEasingFunction(easingFunction);
  21468. }
  21469. mesh.animations.push(animation);
  21470. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21471. };
  21472. // Methods
  21473. Animation.prototype.createRange = function (name, from, to) {
  21474. this._ranges.push(new AnimationRange(name, from, to));
  21475. };
  21476. Animation.prototype.deleteRange = function (name) {
  21477. for (var index = 0; index < this._ranges.length; index++) {
  21478. if (this._ranges[index].name === name) {
  21479. this._ranges.splice(index, 1);
  21480. return;
  21481. }
  21482. }
  21483. };
  21484. Animation.prototype.getRange = function (name) {
  21485. for (var index = 0; index < this._ranges.length; index++) {
  21486. if (this._ranges[index].name === name) {
  21487. return this._ranges[index];
  21488. }
  21489. }
  21490. return null;
  21491. };
  21492. Animation.prototype.reset = function () {
  21493. this._offsetsCache = {};
  21494. this._highLimitsCache = {};
  21495. this.currentFrame = 0;
  21496. };
  21497. Animation.prototype.isStopped = function () {
  21498. return this._stopped;
  21499. };
  21500. Animation.prototype.getKeys = function () {
  21501. return this._keys;
  21502. };
  21503. Animation.prototype.getEasingFunction = function () {
  21504. return this._easingFunction;
  21505. };
  21506. Animation.prototype.setEasingFunction = function (easingFunction) {
  21507. this._easingFunction = easingFunction;
  21508. };
  21509. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21510. return startValue + (endValue - startValue) * gradient;
  21511. };
  21512. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21513. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21514. };
  21515. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21516. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21517. };
  21518. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21519. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21520. };
  21521. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21522. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21523. };
  21524. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21525. var startScale = new BABYLON.Vector3(0, 0, 0);
  21526. var startRotation = new BABYLON.Quaternion();
  21527. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21528. startValue.decompose(startScale, startRotation, startTranslation);
  21529. var endScale = new BABYLON.Vector3(0, 0, 0);
  21530. var endRotation = new BABYLON.Quaternion();
  21531. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21532. endValue.decompose(endScale, endRotation, endTranslation);
  21533. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21534. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21535. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21536. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21537. return result;
  21538. };
  21539. Animation.prototype.clone = function () {
  21540. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21541. if (this._keys) {
  21542. clone.setKeys(this._keys);
  21543. }
  21544. return clone;
  21545. };
  21546. Animation.prototype.setKeys = function (values) {
  21547. this._keys = values.slice(0);
  21548. this._offsetsCache = {};
  21549. this._highLimitsCache = {};
  21550. };
  21551. Animation.prototype._getKeyValue = function (value) {
  21552. if (typeof value === "function") {
  21553. return value();
  21554. }
  21555. return value;
  21556. };
  21557. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21558. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21559. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21560. }
  21561. this.currentFrame = currentFrame;
  21562. // Try to get a hash to find the right key
  21563. 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));
  21564. if (this._keys[startKey].frame >= currentFrame) {
  21565. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21566. startKey--;
  21567. }
  21568. }
  21569. for (var key = startKey; key < this._keys.length; key++) {
  21570. if (this._keys[key + 1].frame >= currentFrame) {
  21571. var startValue = this._getKeyValue(this._keys[key].value);
  21572. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21573. // gradient : percent of currentFrame between the frame inf and the frame sup
  21574. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21575. // check for easingFunction and correction of gradient
  21576. if (this._easingFunction != null) {
  21577. gradient = this._easingFunction.ease(gradient);
  21578. }
  21579. switch (this.dataType) {
  21580. // Float
  21581. case Animation.ANIMATIONTYPE_FLOAT:
  21582. switch (loopMode) {
  21583. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21584. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21585. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21586. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21587. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21588. }
  21589. break;
  21590. // Quaternion
  21591. case Animation.ANIMATIONTYPE_QUATERNION:
  21592. var quaternion = null;
  21593. switch (loopMode) {
  21594. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21595. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21596. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21597. break;
  21598. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21599. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21600. break;
  21601. }
  21602. return quaternion;
  21603. // Vector3
  21604. case Animation.ANIMATIONTYPE_VECTOR3:
  21605. switch (loopMode) {
  21606. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21607. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21608. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21609. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21610. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21611. }
  21612. // Vector2
  21613. case Animation.ANIMATIONTYPE_VECTOR2:
  21614. switch (loopMode) {
  21615. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21616. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21617. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21618. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21619. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21620. }
  21621. // Color3
  21622. case Animation.ANIMATIONTYPE_COLOR3:
  21623. switch (loopMode) {
  21624. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21625. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21626. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21627. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21628. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21629. }
  21630. // Matrix
  21631. case Animation.ANIMATIONTYPE_MATRIX:
  21632. switch (loopMode) {
  21633. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21634. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21635. if (this.allowMatricesInterpolation) {
  21636. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21637. }
  21638. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21639. return startValue;
  21640. }
  21641. default:
  21642. break;
  21643. }
  21644. break;
  21645. }
  21646. }
  21647. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21648. };
  21649. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21650. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21651. this._stopped = true;
  21652. return false;
  21653. }
  21654. var returnValue = true;
  21655. // Adding a start key at frame 0 if missing
  21656. if (this._keys[0].frame !== 0) {
  21657. var newKey = { frame: 0, value: this._keys[0].value };
  21658. this._keys.splice(0, 0, newKey);
  21659. }
  21660. // Check limits
  21661. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21662. from = this._keys[0].frame;
  21663. }
  21664. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21665. to = this._keys[this._keys.length - 1].frame;
  21666. }
  21667. // Compute ratio
  21668. var range = to - from;
  21669. var offsetValue;
  21670. // ratio represents the frame delta between from and to
  21671. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21672. var highLimitValue = 0;
  21673. if (ratio > range && !loop) {
  21674. returnValue = false;
  21675. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21676. }
  21677. else {
  21678. // Get max value if required
  21679. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21680. var keyOffset = to.toString() + from.toString();
  21681. if (!this._offsetsCache[keyOffset]) {
  21682. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21683. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21684. switch (this.dataType) {
  21685. // Float
  21686. case Animation.ANIMATIONTYPE_FLOAT:
  21687. this._offsetsCache[keyOffset] = toValue - fromValue;
  21688. break;
  21689. // Quaternion
  21690. case Animation.ANIMATIONTYPE_QUATERNION:
  21691. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21692. break;
  21693. // Vector3
  21694. case Animation.ANIMATIONTYPE_VECTOR3:
  21695. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21696. // Vector2
  21697. case Animation.ANIMATIONTYPE_VECTOR2:
  21698. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21699. // Color3
  21700. case Animation.ANIMATIONTYPE_COLOR3:
  21701. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21702. default:
  21703. break;
  21704. }
  21705. this._highLimitsCache[keyOffset] = toValue;
  21706. }
  21707. highLimitValue = this._highLimitsCache[keyOffset];
  21708. offsetValue = this._offsetsCache[keyOffset];
  21709. }
  21710. }
  21711. if (offsetValue === undefined) {
  21712. switch (this.dataType) {
  21713. // Float
  21714. case Animation.ANIMATIONTYPE_FLOAT:
  21715. offsetValue = 0;
  21716. break;
  21717. // Quaternion
  21718. case Animation.ANIMATIONTYPE_QUATERNION:
  21719. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21720. break;
  21721. // Vector3
  21722. case Animation.ANIMATIONTYPE_VECTOR3:
  21723. offsetValue = BABYLON.Vector3.Zero();
  21724. break;
  21725. // Vector2
  21726. case Animation.ANIMATIONTYPE_VECTOR2:
  21727. offsetValue = BABYLON.Vector2.Zero();
  21728. break;
  21729. // Color3
  21730. case Animation.ANIMATIONTYPE_COLOR3:
  21731. offsetValue = BABYLON.Color3.Black();
  21732. }
  21733. }
  21734. // Compute value
  21735. var repeatCount = (ratio / range) >> 0;
  21736. var currentFrame = returnValue ? from + ratio % range : to;
  21737. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21738. // Set value
  21739. if (this.targetPropertyPath.length > 1) {
  21740. var property = this._target[this.targetPropertyPath[0]];
  21741. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21742. property = property[this.targetPropertyPath[index]];
  21743. }
  21744. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21745. }
  21746. else {
  21747. this._target[this.targetPropertyPath[0]] = currentValue;
  21748. }
  21749. if (this._target.markAsDirty) {
  21750. this._target.markAsDirty(this.targetProperty);
  21751. }
  21752. if (!returnValue) {
  21753. this._stopped = true;
  21754. }
  21755. return returnValue;
  21756. };
  21757. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21758. get: function () {
  21759. return Animation._ANIMATIONTYPE_FLOAT;
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21765. get: function () {
  21766. return Animation._ANIMATIONTYPE_VECTOR3;
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21772. get: function () {
  21773. return Animation._ANIMATIONTYPE_VECTOR2;
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21779. get: function () {
  21780. return Animation._ANIMATIONTYPE_QUATERNION;
  21781. },
  21782. enumerable: true,
  21783. configurable: true
  21784. });
  21785. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21786. get: function () {
  21787. return Animation._ANIMATIONTYPE_MATRIX;
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21793. get: function () {
  21794. return Animation._ANIMATIONTYPE_COLOR3;
  21795. },
  21796. enumerable: true,
  21797. configurable: true
  21798. });
  21799. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21800. get: function () {
  21801. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21807. get: function () {
  21808. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21809. },
  21810. enumerable: true,
  21811. configurable: true
  21812. });
  21813. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21814. get: function () {
  21815. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. // Statics
  21821. Animation._ANIMATIONTYPE_FLOAT = 0;
  21822. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21823. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21824. Animation._ANIMATIONTYPE_MATRIX = 3;
  21825. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21826. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21827. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21828. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21829. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21830. return Animation;
  21831. })();
  21832. BABYLON.Animation = Animation;
  21833. })(BABYLON || (BABYLON = {}));
  21834. var BABYLON;
  21835. (function (BABYLON) {
  21836. var Animatable = (function () {
  21837. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21838. if (fromFrame === void 0) { fromFrame = 0; }
  21839. if (toFrame === void 0) { toFrame = 100; }
  21840. if (loopAnimation === void 0) { loopAnimation = false; }
  21841. if (speedRatio === void 0) { speedRatio = 1.0; }
  21842. this.target = target;
  21843. this.fromFrame = fromFrame;
  21844. this.toFrame = toFrame;
  21845. this.loopAnimation = loopAnimation;
  21846. this.speedRatio = speedRatio;
  21847. this.onAnimationEnd = onAnimationEnd;
  21848. this._animations = new Array();
  21849. this._paused = false;
  21850. this.animationStarted = false;
  21851. if (animations) {
  21852. this.appendAnimations(target, animations);
  21853. }
  21854. this._scene = scene;
  21855. scene._activeAnimatables.push(this);
  21856. }
  21857. // Methods
  21858. Animatable.prototype.getAnimations = function () {
  21859. return this._animations;
  21860. };
  21861. Animatable.prototype.appendAnimations = function (target, animations) {
  21862. for (var index = 0; index < animations.length; index++) {
  21863. var animation = animations[index];
  21864. animation._target = target;
  21865. this._animations.push(animation);
  21866. }
  21867. };
  21868. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21869. var animations = this._animations;
  21870. for (var index = 0; index < animations.length; index++) {
  21871. if (animations[index].targetProperty === property) {
  21872. return animations[index];
  21873. }
  21874. }
  21875. return null;
  21876. };
  21877. Animatable.prototype.reset = function () {
  21878. var animations = this._animations;
  21879. for (var index = 0; index < animations.length; index++) {
  21880. animations[index].reset();
  21881. }
  21882. this._localDelayOffset = null;
  21883. this._pausedDelay = null;
  21884. };
  21885. Animatable.prototype.pause = function () {
  21886. if (this._paused) {
  21887. return;
  21888. }
  21889. this._paused = true;
  21890. };
  21891. Animatable.prototype.restart = function () {
  21892. this._paused = false;
  21893. };
  21894. Animatable.prototype.stop = function () {
  21895. var index = this._scene._activeAnimatables.indexOf(this);
  21896. if (index > -1) {
  21897. this._scene._activeAnimatables.splice(index, 1);
  21898. }
  21899. if (this.onAnimationEnd) {
  21900. this.onAnimationEnd();
  21901. }
  21902. };
  21903. Animatable.prototype._animate = function (delay) {
  21904. if (this._paused) {
  21905. if (!this._pausedDelay) {
  21906. this._pausedDelay = delay;
  21907. }
  21908. return true;
  21909. }
  21910. if (!this._localDelayOffset) {
  21911. this._localDelayOffset = delay;
  21912. }
  21913. else if (this._pausedDelay) {
  21914. this._localDelayOffset += delay - this._pausedDelay;
  21915. this._pausedDelay = null;
  21916. }
  21917. // Animating
  21918. var running = false;
  21919. var animations = this._animations;
  21920. for (var index = 0; index < animations.length; index++) {
  21921. var animation = animations[index];
  21922. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21923. running = running || isRunning;
  21924. }
  21925. if (!running) {
  21926. // Remove from active animatables
  21927. index = this._scene._activeAnimatables.indexOf(this);
  21928. this._scene._activeAnimatables.splice(index, 1);
  21929. }
  21930. if (!running && this.onAnimationEnd) {
  21931. this.onAnimationEnd();
  21932. }
  21933. return running;
  21934. };
  21935. return Animatable;
  21936. })();
  21937. BABYLON.Animatable = Animatable;
  21938. })(BABYLON || (BABYLON = {}));
  21939. var BABYLON;
  21940. (function (BABYLON) {
  21941. var EasingFunction = (function () {
  21942. function EasingFunction() {
  21943. // Properties
  21944. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21945. }
  21946. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21947. get: function () {
  21948. return EasingFunction._EASINGMODE_EASEIN;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21954. get: function () {
  21955. return EasingFunction._EASINGMODE_EASEOUT;
  21956. },
  21957. enumerable: true,
  21958. configurable: true
  21959. });
  21960. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21961. get: function () {
  21962. return EasingFunction._EASINGMODE_EASEINOUT;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21968. var n = Math.min(Math.max(easingMode, 0), 2);
  21969. this._easingMode = n;
  21970. };
  21971. EasingFunction.prototype.getEasingMode = function () {
  21972. return this._easingMode;
  21973. };
  21974. EasingFunction.prototype.easeInCore = function (gradient) {
  21975. throw new Error('You must implement this method');
  21976. };
  21977. EasingFunction.prototype.ease = function (gradient) {
  21978. switch (this._easingMode) {
  21979. case EasingFunction.EASINGMODE_EASEIN:
  21980. return this.easeInCore(gradient);
  21981. case EasingFunction.EASINGMODE_EASEOUT:
  21982. return (1 - this.easeInCore(1 - gradient));
  21983. }
  21984. if (gradient >= 0.5) {
  21985. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21986. }
  21987. return (this.easeInCore(gradient * 2) * 0.5);
  21988. };
  21989. //Statics
  21990. EasingFunction._EASINGMODE_EASEIN = 0;
  21991. EasingFunction._EASINGMODE_EASEOUT = 1;
  21992. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21993. return EasingFunction;
  21994. })();
  21995. BABYLON.EasingFunction = EasingFunction;
  21996. var CircleEase = (function (_super) {
  21997. __extends(CircleEase, _super);
  21998. function CircleEase() {
  21999. _super.apply(this, arguments);
  22000. }
  22001. CircleEase.prototype.easeInCore = function (gradient) {
  22002. gradient = Math.max(0, Math.min(1, gradient));
  22003. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22004. };
  22005. return CircleEase;
  22006. })(EasingFunction);
  22007. BABYLON.CircleEase = CircleEase;
  22008. var BackEase = (function (_super) {
  22009. __extends(BackEase, _super);
  22010. function BackEase(amplitude) {
  22011. if (amplitude === void 0) { amplitude = 1; }
  22012. _super.call(this);
  22013. this.amplitude = amplitude;
  22014. }
  22015. BackEase.prototype.easeInCore = function (gradient) {
  22016. var num = Math.max(0, this.amplitude);
  22017. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22018. };
  22019. return BackEase;
  22020. })(EasingFunction);
  22021. BABYLON.BackEase = BackEase;
  22022. var BounceEase = (function (_super) {
  22023. __extends(BounceEase, _super);
  22024. function BounceEase(bounces, bounciness) {
  22025. if (bounces === void 0) { bounces = 3; }
  22026. if (bounciness === void 0) { bounciness = 2; }
  22027. _super.call(this);
  22028. this.bounces = bounces;
  22029. this.bounciness = bounciness;
  22030. }
  22031. BounceEase.prototype.easeInCore = function (gradient) {
  22032. var y = Math.max(0.0, this.bounces);
  22033. var bounciness = this.bounciness;
  22034. if (bounciness <= 1.0) {
  22035. bounciness = 1.001;
  22036. }
  22037. var num9 = Math.pow(bounciness, y);
  22038. var num5 = 1.0 - bounciness;
  22039. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22040. var num15 = gradient * num4;
  22041. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22042. var num3 = Math.floor(num65);
  22043. var num13 = num3 + 1.0;
  22044. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22045. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22046. var num7 = (num8 + num12) * 0.5;
  22047. var num6 = gradient - num7;
  22048. var num2 = num7 - num8;
  22049. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22050. };
  22051. return BounceEase;
  22052. })(EasingFunction);
  22053. BABYLON.BounceEase = BounceEase;
  22054. var CubicEase = (function (_super) {
  22055. __extends(CubicEase, _super);
  22056. function CubicEase() {
  22057. _super.apply(this, arguments);
  22058. }
  22059. CubicEase.prototype.easeInCore = function (gradient) {
  22060. return (gradient * gradient * gradient);
  22061. };
  22062. return CubicEase;
  22063. })(EasingFunction);
  22064. BABYLON.CubicEase = CubicEase;
  22065. var ElasticEase = (function (_super) {
  22066. __extends(ElasticEase, _super);
  22067. function ElasticEase(oscillations, springiness) {
  22068. if (oscillations === void 0) { oscillations = 3; }
  22069. if (springiness === void 0) { springiness = 3; }
  22070. _super.call(this);
  22071. this.oscillations = oscillations;
  22072. this.springiness = springiness;
  22073. }
  22074. ElasticEase.prototype.easeInCore = function (gradient) {
  22075. var num2;
  22076. var num3 = Math.max(0.0, this.oscillations);
  22077. var num = Math.max(0.0, this.springiness);
  22078. if (num == 0) {
  22079. num2 = gradient;
  22080. }
  22081. else {
  22082. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22083. }
  22084. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22085. };
  22086. return ElasticEase;
  22087. })(EasingFunction);
  22088. BABYLON.ElasticEase = ElasticEase;
  22089. var ExponentialEase = (function (_super) {
  22090. __extends(ExponentialEase, _super);
  22091. function ExponentialEase(exponent) {
  22092. if (exponent === void 0) { exponent = 2; }
  22093. _super.call(this);
  22094. this.exponent = exponent;
  22095. }
  22096. ExponentialEase.prototype.easeInCore = function (gradient) {
  22097. if (this.exponent <= 0) {
  22098. return gradient;
  22099. }
  22100. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22101. };
  22102. return ExponentialEase;
  22103. })(EasingFunction);
  22104. BABYLON.ExponentialEase = ExponentialEase;
  22105. var PowerEase = (function (_super) {
  22106. __extends(PowerEase, _super);
  22107. function PowerEase(power) {
  22108. if (power === void 0) { power = 2; }
  22109. _super.call(this);
  22110. this.power = power;
  22111. }
  22112. PowerEase.prototype.easeInCore = function (gradient) {
  22113. var y = Math.max(0.0, this.power);
  22114. return Math.pow(gradient, y);
  22115. };
  22116. return PowerEase;
  22117. })(EasingFunction);
  22118. BABYLON.PowerEase = PowerEase;
  22119. var QuadraticEase = (function (_super) {
  22120. __extends(QuadraticEase, _super);
  22121. function QuadraticEase() {
  22122. _super.apply(this, arguments);
  22123. }
  22124. QuadraticEase.prototype.easeInCore = function (gradient) {
  22125. return (gradient * gradient);
  22126. };
  22127. return QuadraticEase;
  22128. })(EasingFunction);
  22129. BABYLON.QuadraticEase = QuadraticEase;
  22130. var QuarticEase = (function (_super) {
  22131. __extends(QuarticEase, _super);
  22132. function QuarticEase() {
  22133. _super.apply(this, arguments);
  22134. }
  22135. QuarticEase.prototype.easeInCore = function (gradient) {
  22136. return (gradient * gradient * gradient * gradient);
  22137. };
  22138. return QuarticEase;
  22139. })(EasingFunction);
  22140. BABYLON.QuarticEase = QuarticEase;
  22141. var QuinticEase = (function (_super) {
  22142. __extends(QuinticEase, _super);
  22143. function QuinticEase() {
  22144. _super.apply(this, arguments);
  22145. }
  22146. QuinticEase.prototype.easeInCore = function (gradient) {
  22147. return (gradient * gradient * gradient * gradient * gradient);
  22148. };
  22149. return QuinticEase;
  22150. })(EasingFunction);
  22151. BABYLON.QuinticEase = QuinticEase;
  22152. var SineEase = (function (_super) {
  22153. __extends(SineEase, _super);
  22154. function SineEase() {
  22155. _super.apply(this, arguments);
  22156. }
  22157. SineEase.prototype.easeInCore = function (gradient) {
  22158. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22159. };
  22160. return SineEase;
  22161. })(EasingFunction);
  22162. BABYLON.SineEase = SineEase;
  22163. var BezierCurveEase = (function (_super) {
  22164. __extends(BezierCurveEase, _super);
  22165. function BezierCurveEase(x1, y1, x2, y2) {
  22166. if (x1 === void 0) { x1 = 0; }
  22167. if (y1 === void 0) { y1 = 0; }
  22168. if (x2 === void 0) { x2 = 1; }
  22169. if (y2 === void 0) { y2 = 1; }
  22170. _super.call(this);
  22171. this.x1 = x1;
  22172. this.y1 = y1;
  22173. this.x2 = x2;
  22174. this.y2 = y2;
  22175. }
  22176. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22177. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22178. };
  22179. return BezierCurveEase;
  22180. })(EasingFunction);
  22181. BABYLON.BezierCurveEase = BezierCurveEase;
  22182. })(BABYLON || (BABYLON = {}));
  22183. var BABYLON;
  22184. (function (BABYLON) {
  22185. var Bone = (function (_super) {
  22186. __extends(Bone, _super);
  22187. function Bone(name, skeleton, parentBone, matrix) {
  22188. _super.call(this, name, skeleton.getScene());
  22189. this.name = name;
  22190. this.children = new Array();
  22191. this.animations = new Array();
  22192. this._worldTransform = new BABYLON.Matrix();
  22193. this._absoluteTransform = new BABYLON.Matrix();
  22194. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22195. this._skeleton = skeleton;
  22196. this._matrix = matrix;
  22197. this._baseMatrix = matrix;
  22198. skeleton.bones.push(this);
  22199. if (parentBone) {
  22200. this._parent = parentBone;
  22201. parentBone.children.push(this);
  22202. }
  22203. else {
  22204. this._parent = null;
  22205. }
  22206. this._updateDifferenceMatrix();
  22207. }
  22208. // Members
  22209. Bone.prototype.getParent = function () {
  22210. return this._parent;
  22211. };
  22212. Bone.prototype.getLocalMatrix = function () {
  22213. return this._matrix;
  22214. };
  22215. Bone.prototype.getBaseMatrix = function () {
  22216. return this._baseMatrix;
  22217. };
  22218. Bone.prototype.getWorldMatrix = function () {
  22219. return this._worldTransform;
  22220. };
  22221. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22222. return this._invertedAbsoluteTransform;
  22223. };
  22224. Bone.prototype.getAbsoluteMatrix = function () {
  22225. var matrix = this._matrix.clone();
  22226. var parent = this._parent;
  22227. while (parent) {
  22228. matrix = matrix.multiply(parent.getLocalMatrix());
  22229. parent = parent.getParent();
  22230. }
  22231. return matrix;
  22232. };
  22233. // Methods
  22234. Bone.prototype.updateMatrix = function (matrix) {
  22235. this._matrix = matrix;
  22236. this._skeleton._markAsDirty();
  22237. this._updateDifferenceMatrix();
  22238. };
  22239. Bone.prototype._updateDifferenceMatrix = function () {
  22240. if (this._parent) {
  22241. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22242. }
  22243. else {
  22244. this._absoluteTransform.copyFrom(this._matrix);
  22245. }
  22246. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22247. for (var index = 0; index < this.children.length; index++) {
  22248. this.children[index]._updateDifferenceMatrix();
  22249. }
  22250. };
  22251. Bone.prototype.markAsDirty = function () {
  22252. this._currentRenderId++;
  22253. this._skeleton._markAsDirty();
  22254. };
  22255. return Bone;
  22256. })(BABYLON.Node);
  22257. BABYLON.Bone = Bone;
  22258. })(BABYLON || (BABYLON = {}));
  22259. var BABYLON;
  22260. (function (BABYLON) {
  22261. var Skeleton = (function () {
  22262. function Skeleton(name, id, scene) {
  22263. this.name = name;
  22264. this.id = id;
  22265. this.bones = new Array();
  22266. this._isDirty = true;
  22267. this._identity = BABYLON.Matrix.Identity();
  22268. this._ranges = new Array();
  22269. this.bones = [];
  22270. this._scene = scene;
  22271. scene.skeletons.push(this);
  22272. this.prepare();
  22273. //make sure it will recalculate the matrix next time prepare is called.
  22274. this._isDirty = true;
  22275. }
  22276. // Members
  22277. Skeleton.prototype.getTransformMatrices = function () {
  22278. return this._transformMatrices;
  22279. };
  22280. Skeleton.prototype.getScene = function () {
  22281. return this._scene;
  22282. };
  22283. // Methods
  22284. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22285. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22286. };
  22287. Skeleton.prototype.deleteAnimationRange = function (name) {
  22288. for (var index = 0; index < this._ranges.length; index++) {
  22289. if (this._ranges[index].name === name) {
  22290. this._ranges.splice(index, 1);
  22291. return;
  22292. }
  22293. }
  22294. };
  22295. Skeleton.prototype.getAnimationRange = function (name) {
  22296. for (var index = 0; index < this._ranges.length; index++) {
  22297. if (this._ranges[index].name === name) {
  22298. return this._ranges[index];
  22299. }
  22300. }
  22301. return null;
  22302. };
  22303. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22304. var range = this.getAnimationRange(name);
  22305. if (!range) {
  22306. return null;
  22307. }
  22308. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22309. };
  22310. Skeleton.prototype._markAsDirty = function () {
  22311. this._isDirty = true;
  22312. };
  22313. Skeleton.prototype.prepare = function () {
  22314. if (!this._isDirty) {
  22315. return;
  22316. }
  22317. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22318. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22319. }
  22320. for (var index = 0; index < this.bones.length; index++) {
  22321. var bone = this.bones[index];
  22322. var parentBone = bone.getParent();
  22323. if (parentBone) {
  22324. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22325. }
  22326. else {
  22327. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22328. }
  22329. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22330. }
  22331. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22332. this._isDirty = false;
  22333. this._scene._activeBones += this.bones.length;
  22334. };
  22335. Skeleton.prototype.getAnimatables = function () {
  22336. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22337. this._animatables = [];
  22338. for (var index = 0; index < this.bones.length; index++) {
  22339. this._animatables.push(this.bones[index]);
  22340. }
  22341. }
  22342. return this._animatables;
  22343. };
  22344. Skeleton.prototype.clone = function (name, id) {
  22345. var result = new Skeleton(name, id || name, this._scene);
  22346. for (var index = 0; index < this.bones.length; index++) {
  22347. var source = this.bones[index];
  22348. var parentBone = null;
  22349. if (source.getParent()) {
  22350. var parentIndex = this.bones.indexOf(source.getParent());
  22351. parentBone = result.bones[parentIndex];
  22352. }
  22353. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22354. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22355. }
  22356. return result;
  22357. };
  22358. Skeleton.prototype.dispose = function () {
  22359. // Animations
  22360. this.getScene().stopAnimation(this);
  22361. // Remove from scene
  22362. this.getScene().removeSkeleton(this);
  22363. };
  22364. return Skeleton;
  22365. })();
  22366. BABYLON.Skeleton = Skeleton;
  22367. })(BABYLON || (BABYLON = {}));
  22368. var BABYLON;
  22369. (function (BABYLON) {
  22370. var PostProcess = (function () {
  22371. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22373. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22374. this.name = name;
  22375. this.width = -1;
  22376. this.height = -1;
  22377. this._reusable = false;
  22378. this._textures = new BABYLON.SmartArray(2);
  22379. this._currentRenderTextureInd = 0;
  22380. if (camera != null) {
  22381. this._camera = camera;
  22382. this._scene = camera.getScene();
  22383. camera.attachPostProcess(this);
  22384. this._engine = this._scene.getEngine();
  22385. }
  22386. else {
  22387. this._engine = engine;
  22388. }
  22389. this._renderRatio = ratio;
  22390. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22391. this._reusable = reusable || false;
  22392. this._textureType = textureType;
  22393. samplers = samplers || [];
  22394. samplers.push("textureSampler");
  22395. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22396. }
  22397. PostProcess.prototype.isReusable = function () {
  22398. return this._reusable;
  22399. };
  22400. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22401. camera = camera || this._camera;
  22402. var scene = camera.getScene();
  22403. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22404. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22405. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22406. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22407. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22408. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22409. if (this._textures.length > 0) {
  22410. for (var i = 0; i < this._textures.length; i++) {
  22411. this._engine._releaseTexture(this._textures.data[i]);
  22412. }
  22413. this._textures.reset();
  22414. }
  22415. this.width = desiredWidth;
  22416. this.height = desiredHeight;
  22417. 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 }));
  22418. if (this._reusable) {
  22419. 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 }));
  22420. }
  22421. if (this.onSizeChanged) {
  22422. this.onSizeChanged();
  22423. }
  22424. }
  22425. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22426. if (this.onActivate) {
  22427. this.onActivate(camera);
  22428. }
  22429. // Clear
  22430. if (this.clearColor) {
  22431. this._engine.clear(this.clearColor, true, true);
  22432. }
  22433. else {
  22434. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22435. }
  22436. if (this._reusable) {
  22437. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22438. }
  22439. };
  22440. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22441. get: function () {
  22442. return this._effect.isSupported;
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. PostProcess.prototype.apply = function () {
  22448. // Check
  22449. if (!this._effect.isReady())
  22450. return null;
  22451. // States
  22452. this._engine.enableEffect(this._effect);
  22453. this._engine.setState(false);
  22454. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22455. this._engine.setDepthBuffer(false);
  22456. this._engine.setDepthWrite(false);
  22457. // Texture
  22458. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22459. // Parameters
  22460. if (this.onApply) {
  22461. this.onApply(this._effect);
  22462. }
  22463. return this._effect;
  22464. };
  22465. PostProcess.prototype.dispose = function (camera) {
  22466. camera = camera || this._camera;
  22467. if (this._textures.length > 0) {
  22468. for (var i = 0; i < this._textures.length; i++) {
  22469. this._engine._releaseTexture(this._textures.data[i]);
  22470. }
  22471. this._textures.reset();
  22472. }
  22473. if (!camera) {
  22474. return;
  22475. }
  22476. camera.detachPostProcess(this);
  22477. var index = camera._postProcesses.indexOf(this);
  22478. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22479. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22480. }
  22481. };
  22482. return PostProcess;
  22483. })();
  22484. BABYLON.PostProcess = PostProcess;
  22485. })(BABYLON || (BABYLON = {}));
  22486. var BABYLON;
  22487. (function (BABYLON) {
  22488. var PostProcessManager = (function () {
  22489. function PostProcessManager(scene) {
  22490. this._vertexDeclaration = [2];
  22491. this._vertexStrideSize = 2 * 4;
  22492. this._scene = scene;
  22493. }
  22494. PostProcessManager.prototype._prepareBuffers = function () {
  22495. if (this._vertexBuffer) {
  22496. return;
  22497. }
  22498. // VBO
  22499. var vertices = [];
  22500. vertices.push(1, 1);
  22501. vertices.push(-1, 1);
  22502. vertices.push(-1, -1);
  22503. vertices.push(1, -1);
  22504. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22505. // Indices
  22506. var indices = [];
  22507. indices.push(0);
  22508. indices.push(1);
  22509. indices.push(2);
  22510. indices.push(0);
  22511. indices.push(2);
  22512. indices.push(3);
  22513. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22514. };
  22515. // Methods
  22516. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22517. var postProcesses = this._scene.activeCamera._postProcesses;
  22518. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22519. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22520. return false;
  22521. }
  22522. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22523. return true;
  22524. };
  22525. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22526. var engine = this._scene.getEngine();
  22527. for (var index = 0; index < postProcesses.length; index++) {
  22528. if (index < postProcesses.length - 1) {
  22529. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22530. }
  22531. else {
  22532. if (targetTexture) {
  22533. engine.bindFramebuffer(targetTexture);
  22534. }
  22535. else {
  22536. engine.restoreDefaultFramebuffer();
  22537. }
  22538. }
  22539. var pp = postProcesses[index];
  22540. var effect = pp.apply();
  22541. if (effect) {
  22542. if (pp.onBeforeRender) {
  22543. pp.onBeforeRender(effect);
  22544. }
  22545. // VBOs
  22546. this._prepareBuffers();
  22547. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22548. // Draw order
  22549. engine.draw(true, 0, 6);
  22550. if (pp.onAfterRender) {
  22551. pp.onAfterRender(effect);
  22552. }
  22553. }
  22554. }
  22555. // Restore depth buffer
  22556. engine.setDepthBuffer(true);
  22557. engine.setDepthWrite(true);
  22558. };
  22559. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22560. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22561. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22562. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22563. return;
  22564. }
  22565. var engine = this._scene.getEngine();
  22566. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22567. if (index < postProcessesTakenIndices.length - 1) {
  22568. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22569. }
  22570. else {
  22571. if (targetTexture) {
  22572. engine.bindFramebuffer(targetTexture, faceIndex);
  22573. }
  22574. else {
  22575. engine.restoreDefaultFramebuffer();
  22576. }
  22577. }
  22578. if (doNotPresent) {
  22579. break;
  22580. }
  22581. var pp = postProcesses[postProcessesTakenIndices[index]];
  22582. var effect = pp.apply();
  22583. if (effect) {
  22584. if (pp.onBeforeRender) {
  22585. pp.onBeforeRender(effect);
  22586. }
  22587. // VBOs
  22588. this._prepareBuffers();
  22589. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22590. // Draw order
  22591. engine.draw(true, 0, 6);
  22592. if (pp.onAfterRender) {
  22593. pp.onAfterRender(effect);
  22594. }
  22595. }
  22596. }
  22597. // Restore depth buffer
  22598. engine.setDepthBuffer(true);
  22599. engine.setDepthWrite(true);
  22600. };
  22601. PostProcessManager.prototype.dispose = function () {
  22602. if (this._vertexBuffer) {
  22603. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22604. this._vertexBuffer = null;
  22605. }
  22606. if (this._indexBuffer) {
  22607. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22608. this._indexBuffer = null;
  22609. }
  22610. };
  22611. return PostProcessManager;
  22612. })();
  22613. BABYLON.PostProcessManager = PostProcessManager;
  22614. })(BABYLON || (BABYLON = {}));
  22615. var BABYLON;
  22616. (function (BABYLON) {
  22617. var PassPostProcess = (function (_super) {
  22618. __extends(PassPostProcess, _super);
  22619. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22620. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22621. }
  22622. return PassPostProcess;
  22623. })(BABYLON.PostProcess);
  22624. BABYLON.PassPostProcess = PassPostProcess;
  22625. })(BABYLON || (BABYLON = {}));
  22626. var BABYLON;
  22627. (function (BABYLON) {
  22628. var PhysicsEngine = (function () {
  22629. function PhysicsEngine(plugin) {
  22630. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22631. }
  22632. PhysicsEngine.prototype._initialize = function (gravity) {
  22633. this._currentPlugin.initialize();
  22634. this._setGravity(gravity);
  22635. };
  22636. PhysicsEngine.prototype._runOneStep = function (delta) {
  22637. if (delta > 0.1) {
  22638. delta = 0.1;
  22639. }
  22640. else if (delta <= 0) {
  22641. delta = 1.0 / 60.0;
  22642. }
  22643. this._currentPlugin.runOneStep(delta);
  22644. };
  22645. PhysicsEngine.prototype._setGravity = function (gravity) {
  22646. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22647. this._currentPlugin.setGravity(this.gravity);
  22648. };
  22649. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22650. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22651. };
  22652. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22653. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22654. };
  22655. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22656. this._currentPlugin.unregisterMesh(mesh);
  22657. };
  22658. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22659. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22660. };
  22661. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22662. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22663. };
  22664. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22665. this._currentPlugin.updateBodyPosition(mesh);
  22666. };
  22667. PhysicsEngine.prototype.dispose = function () {
  22668. this._currentPlugin.dispose();
  22669. };
  22670. PhysicsEngine.prototype.isSupported = function () {
  22671. return this._currentPlugin.isSupported();
  22672. };
  22673. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22674. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22675. };
  22676. // Statics
  22677. PhysicsEngine.NoImpostor = 0;
  22678. PhysicsEngine.SphereImpostor = 1;
  22679. PhysicsEngine.BoxImpostor = 2;
  22680. PhysicsEngine.PlaneImpostor = 3;
  22681. PhysicsEngine.MeshImpostor = 4;
  22682. PhysicsEngine.CapsuleImpostor = 5;
  22683. PhysicsEngine.ConeImpostor = 6;
  22684. PhysicsEngine.CylinderImpostor = 7;
  22685. PhysicsEngine.ConvexHullImpostor = 8;
  22686. PhysicsEngine.HeightmapImpostor = 9;
  22687. PhysicsEngine.Epsilon = 0.001;
  22688. return PhysicsEngine;
  22689. })();
  22690. BABYLON.PhysicsEngine = PhysicsEngine;
  22691. })(BABYLON || (BABYLON = {}));
  22692. var BABYLON;
  22693. (function (BABYLON) {
  22694. var VertexData = (function () {
  22695. function VertexData() {
  22696. }
  22697. VertexData.prototype.set = function (data, kind) {
  22698. switch (kind) {
  22699. case BABYLON.VertexBuffer.PositionKind:
  22700. this.positions = data;
  22701. break;
  22702. case BABYLON.VertexBuffer.NormalKind:
  22703. this.normals = data;
  22704. break;
  22705. case BABYLON.VertexBuffer.UVKind:
  22706. this.uvs = data;
  22707. break;
  22708. case BABYLON.VertexBuffer.UV2Kind:
  22709. this.uvs2 = data;
  22710. break;
  22711. case BABYLON.VertexBuffer.UV3Kind:
  22712. this.uvs3 = data;
  22713. break;
  22714. case BABYLON.VertexBuffer.UV4Kind:
  22715. this.uvs4 = data;
  22716. break;
  22717. case BABYLON.VertexBuffer.UV5Kind:
  22718. this.uvs5 = data;
  22719. break;
  22720. case BABYLON.VertexBuffer.UV6Kind:
  22721. this.uvs6 = data;
  22722. break;
  22723. case BABYLON.VertexBuffer.ColorKind:
  22724. this.colors = data;
  22725. break;
  22726. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22727. this.matricesIndices = data;
  22728. break;
  22729. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22730. this.matricesWeights = data;
  22731. break;
  22732. }
  22733. };
  22734. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22735. this._applyTo(mesh, updatable);
  22736. };
  22737. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22738. this._applyTo(geometry, updatable);
  22739. };
  22740. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22741. this._update(mesh);
  22742. };
  22743. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22744. this._update(geometry);
  22745. };
  22746. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22747. if (this.positions) {
  22748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22749. }
  22750. if (this.normals) {
  22751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22752. }
  22753. if (this.uvs) {
  22754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22755. }
  22756. if (this.uvs2) {
  22757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22758. }
  22759. if (this.uvs3) {
  22760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22761. }
  22762. if (this.uvs4) {
  22763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22764. }
  22765. if (this.uvs5) {
  22766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22767. }
  22768. if (this.uvs6) {
  22769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22770. }
  22771. if (this.colors) {
  22772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22773. }
  22774. if (this.matricesIndices) {
  22775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22776. }
  22777. if (this.matricesWeights) {
  22778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22779. }
  22780. if (this.indices) {
  22781. meshOrGeometry.setIndices(this.indices);
  22782. }
  22783. };
  22784. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22785. if (this.positions) {
  22786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22787. }
  22788. if (this.normals) {
  22789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22790. }
  22791. if (this.uvs) {
  22792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22793. }
  22794. if (this.uvs2) {
  22795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22796. }
  22797. if (this.uvs3) {
  22798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22799. }
  22800. if (this.uvs4) {
  22801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22802. }
  22803. if (this.uvs5) {
  22804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22805. }
  22806. if (this.uvs6) {
  22807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22808. }
  22809. if (this.colors) {
  22810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22811. }
  22812. if (this.matricesIndices) {
  22813. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22814. }
  22815. if (this.matricesWeights) {
  22816. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22817. }
  22818. if (this.indices) {
  22819. meshOrGeometry.setIndices(this.indices);
  22820. }
  22821. };
  22822. VertexData.prototype.transform = function (matrix) {
  22823. var transformed = BABYLON.Vector3.Zero();
  22824. var index;
  22825. if (this.positions) {
  22826. var position = BABYLON.Vector3.Zero();
  22827. for (index = 0; index < this.positions.length; index += 3) {
  22828. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22829. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22830. this.positions[index] = transformed.x;
  22831. this.positions[index + 1] = transformed.y;
  22832. this.positions[index + 2] = transformed.z;
  22833. }
  22834. }
  22835. if (this.normals) {
  22836. var normal = BABYLON.Vector3.Zero();
  22837. for (index = 0; index < this.normals.length; index += 3) {
  22838. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22839. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22840. this.normals[index] = transformed.x;
  22841. this.normals[index + 1] = transformed.y;
  22842. this.normals[index + 2] = transformed.z;
  22843. }
  22844. }
  22845. };
  22846. VertexData.prototype.merge = function (other) {
  22847. var index;
  22848. if (other.indices) {
  22849. if (!this.indices) {
  22850. this.indices = [];
  22851. }
  22852. var offset = this.positions ? this.positions.length / 3 : 0;
  22853. for (index = 0; index < other.indices.length; index++) {
  22854. this.indices.push(other.indices[index] + offset);
  22855. }
  22856. }
  22857. if (other.positions) {
  22858. if (!this.positions) {
  22859. this.positions = [];
  22860. }
  22861. for (index = 0; index < other.positions.length; index++) {
  22862. this.positions.push(other.positions[index]);
  22863. }
  22864. }
  22865. if (other.normals) {
  22866. if (!this.normals) {
  22867. this.normals = [];
  22868. }
  22869. for (index = 0; index < other.normals.length; index++) {
  22870. this.normals.push(other.normals[index]);
  22871. }
  22872. }
  22873. if (other.uvs) {
  22874. if (!this.uvs) {
  22875. this.uvs = [];
  22876. }
  22877. for (index = 0; index < other.uvs.length; index++) {
  22878. this.uvs.push(other.uvs[index]);
  22879. }
  22880. }
  22881. if (other.uvs2) {
  22882. if (!this.uvs2) {
  22883. this.uvs2 = [];
  22884. }
  22885. for (index = 0; index < other.uvs2.length; index++) {
  22886. this.uvs2.push(other.uvs2[index]);
  22887. }
  22888. }
  22889. if (other.uvs3) {
  22890. if (!this.uvs3) {
  22891. this.uvs3 = [];
  22892. }
  22893. for (index = 0; index < other.uvs3.length; index++) {
  22894. this.uvs3.push(other.uvs3[index]);
  22895. }
  22896. }
  22897. if (other.uvs4) {
  22898. if (!this.uvs4) {
  22899. this.uvs4 = [];
  22900. }
  22901. for (index = 0; index < other.uvs4.length; index++) {
  22902. this.uvs4.push(other.uvs4[index]);
  22903. }
  22904. }
  22905. if (other.uvs5) {
  22906. if (!this.uvs5) {
  22907. this.uvs5 = [];
  22908. }
  22909. for (index = 0; index < other.uvs5.length; index++) {
  22910. this.uvs5.push(other.uvs5[index]);
  22911. }
  22912. }
  22913. if (other.uvs6) {
  22914. if (!this.uvs6) {
  22915. this.uvs6 = [];
  22916. }
  22917. for (index = 0; index < other.uvs6.length; index++) {
  22918. this.uvs6.push(other.uvs6[index]);
  22919. }
  22920. }
  22921. if (other.matricesIndices) {
  22922. if (!this.matricesIndices) {
  22923. this.matricesIndices = [];
  22924. }
  22925. for (index = 0; index < other.matricesIndices.length; index++) {
  22926. this.matricesIndices.push(other.matricesIndices[index]);
  22927. }
  22928. }
  22929. if (other.matricesWeights) {
  22930. if (!this.matricesWeights) {
  22931. this.matricesWeights = [];
  22932. }
  22933. for (index = 0; index < other.matricesWeights.length; index++) {
  22934. this.matricesWeights.push(other.matricesWeights[index]);
  22935. }
  22936. }
  22937. if (other.colors) {
  22938. if (!this.colors) {
  22939. this.colors = [];
  22940. }
  22941. for (index = 0; index < other.colors.length; index++) {
  22942. this.colors.push(other.colors[index]);
  22943. }
  22944. }
  22945. };
  22946. // Statics
  22947. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22948. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22949. };
  22950. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22951. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22952. };
  22953. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22954. var result = new VertexData();
  22955. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22956. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22957. }
  22958. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22959. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22960. }
  22961. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22962. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22963. }
  22964. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22965. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22966. }
  22967. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22968. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22969. }
  22970. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22971. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22972. }
  22973. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22974. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22975. }
  22976. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22977. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22978. }
  22979. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22980. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22981. }
  22982. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22983. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22984. }
  22985. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22986. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22987. }
  22988. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22989. return result;
  22990. };
  22991. VertexData.CreateRibbon = function (options) {
  22992. var pathArray = options.pathArray;
  22993. var closeArray = options.closeArray || false;
  22994. var closePath = options.closePath || false;
  22995. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22996. var offset = options.offset || defaultOffset;
  22997. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22998. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22999. var positions = [];
  23000. var indices = [];
  23001. var normals = [];
  23002. var uvs = [];
  23003. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23004. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23005. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23006. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23007. var minlg; // minimal length among all paths from pathArray
  23008. var lg = []; // array of path lengths : nb of vertex per path
  23009. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23010. var p; // path iterator
  23011. var i; // point iterator
  23012. var j; // point iterator
  23013. // if single path in pathArray
  23014. if (pathArray.length < 2) {
  23015. var ar1 = [];
  23016. var ar2 = [];
  23017. for (i = 0; i < pathArray[0].length - offset; i++) {
  23018. ar1.push(pathArray[0][i]);
  23019. ar2.push(pathArray[0][i + offset]);
  23020. }
  23021. pathArray = [ar1, ar2];
  23022. }
  23023. // positions and horizontal distances (u)
  23024. var idc = 0;
  23025. var closePathCorr = (closePath) ? 1 : 0;
  23026. var path;
  23027. var l;
  23028. minlg = pathArray[0].length;
  23029. var vectlg;
  23030. var dist;
  23031. for (p = 0; p < pathArray.length; p++) {
  23032. uTotalDistance[p] = 0;
  23033. us[p] = [0];
  23034. path = pathArray[p];
  23035. l = path.length;
  23036. minlg = (minlg < l) ? minlg : l;
  23037. j = 0;
  23038. while (j < l) {
  23039. positions.push(path[j].x, path[j].y, path[j].z);
  23040. if (j > 0) {
  23041. vectlg = path[j].subtract(path[j - 1]).length();
  23042. dist = vectlg + uTotalDistance[p];
  23043. us[p].push(dist);
  23044. uTotalDistance[p] = dist;
  23045. }
  23046. j++;
  23047. }
  23048. if (closePath) {
  23049. j--;
  23050. positions.push(path[0].x, path[0].y, path[0].z);
  23051. vectlg = path[j].subtract(path[0]).length();
  23052. dist = vectlg + uTotalDistance[p];
  23053. us[p].push(dist);
  23054. uTotalDistance[p] = dist;
  23055. }
  23056. lg[p] = l + closePathCorr;
  23057. idx[p] = idc;
  23058. idc += (l + closePathCorr);
  23059. }
  23060. // vertical distances (v)
  23061. var path1;
  23062. var path2;
  23063. var vertex1;
  23064. var vertex2;
  23065. for (i = 0; i < minlg + closePathCorr; i++) {
  23066. vTotalDistance[i] = 0;
  23067. vs[i] = [0];
  23068. for (p = 0; p < pathArray.length - 1; p++) {
  23069. path1 = pathArray[p];
  23070. path2 = pathArray[p + 1];
  23071. if (i === minlg) {
  23072. vertex1 = path1[0];
  23073. vertex2 = path2[0];
  23074. }
  23075. else {
  23076. vertex1 = path1[i];
  23077. vertex2 = path2[i];
  23078. }
  23079. vectlg = vertex2.subtract(vertex1).length();
  23080. dist = vectlg + vTotalDistance[i];
  23081. vs[i].push(dist);
  23082. vTotalDistance[i] = dist;
  23083. }
  23084. if (closeArray) {
  23085. path1 = pathArray[p];
  23086. path2 = pathArray[0];
  23087. if (i === minlg) {
  23088. vertex2 = path2[0];
  23089. }
  23090. vectlg = vertex2.subtract(vertex1).length();
  23091. dist = vectlg + vTotalDistance[i];
  23092. vTotalDistance[i] = dist;
  23093. }
  23094. }
  23095. // uvs
  23096. var u;
  23097. var v;
  23098. for (p = 0; p < pathArray.length; p++) {
  23099. for (i = 0; i < minlg + closePathCorr; i++) {
  23100. u = us[p][i] / uTotalDistance[p];
  23101. v = vs[i][p] / vTotalDistance[i];
  23102. uvs.push(u, v);
  23103. }
  23104. }
  23105. // indices
  23106. p = 0; // path index
  23107. var pi = 0; // positions array index
  23108. var l1 = lg[p] - 1; // path1 length
  23109. var l2 = lg[p + 1] - 1; // path2 length
  23110. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23111. var shft = idx[1] - idx[0]; // shift
  23112. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23113. while (pi <= min && p < path1nb) {
  23114. // 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
  23115. indices.push(pi, pi + shft, pi + 1);
  23116. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23117. pi += 1;
  23118. if (pi === min) {
  23119. p++;
  23120. if (p === lg.length - 1) {
  23121. shft = idx[0] - idx[p];
  23122. l1 = lg[p] - 1;
  23123. l2 = lg[0] - 1;
  23124. }
  23125. else {
  23126. shft = idx[p + 1] - idx[p];
  23127. l1 = lg[p] - 1;
  23128. l2 = lg[p + 1] - 1;
  23129. }
  23130. pi = idx[p];
  23131. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23132. }
  23133. }
  23134. // normals
  23135. VertexData.ComputeNormals(positions, indices, normals);
  23136. if (closePath) {
  23137. var indexFirst = 0;
  23138. var indexLast = 0;
  23139. for (p = 0; p < pathArray.length; p++) {
  23140. indexFirst = idx[p] * 3;
  23141. if (p + 1 < pathArray.length) {
  23142. indexLast = (idx[p + 1] - 1) * 3;
  23143. }
  23144. else {
  23145. indexLast = normals.length - 3;
  23146. }
  23147. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23148. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23149. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23150. normals[indexLast] = normals[indexFirst];
  23151. normals[indexLast + 1] = normals[indexFirst + 1];
  23152. normals[indexLast + 2] = normals[indexFirst + 2];
  23153. }
  23154. }
  23155. // sides
  23156. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23157. // Result
  23158. var vertexData = new VertexData();
  23159. vertexData.indices = indices;
  23160. vertexData.positions = positions;
  23161. vertexData.normals = normals;
  23162. vertexData.uvs = uvs;
  23163. if (closePath) {
  23164. vertexData._idx = idx;
  23165. }
  23166. return vertexData;
  23167. };
  23168. VertexData.CreateBox = function (options) {
  23169. var normalsSource = [
  23170. new BABYLON.Vector3(0, 0, 1),
  23171. new BABYLON.Vector3(0, 0, -1),
  23172. new BABYLON.Vector3(1, 0, 0),
  23173. new BABYLON.Vector3(-1, 0, 0),
  23174. new BABYLON.Vector3(0, 1, 0),
  23175. new BABYLON.Vector3(0, -1, 0)
  23176. ];
  23177. var indices = [];
  23178. var positions = [];
  23179. var normals = [];
  23180. var uvs = [];
  23181. var width = options.width || options.size || 1;
  23182. var height = options.height || options.size || 1;
  23183. var depth = options.depth || options.size || 1;
  23184. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23185. var faceUV = options.faceUV || new Array(6);
  23186. var faceColors = options.faceColors;
  23187. var colors = [];
  23188. // default face colors and UV if undefined
  23189. for (var f = 0; f < 6; f++) {
  23190. if (faceUV[f] === undefined) {
  23191. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23192. }
  23193. if (faceColors && faceColors[f] === undefined) {
  23194. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23195. }
  23196. }
  23197. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23198. // Create each face in turn.
  23199. for (var index = 0; index < normalsSource.length; index++) {
  23200. var normal = normalsSource[index];
  23201. // Get two vectors perpendicular to the face normal and to each other.
  23202. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23203. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23204. // Six indices (two triangles) per face.
  23205. var verticesLength = positions.length / 3;
  23206. indices.push(verticesLength);
  23207. indices.push(verticesLength + 1);
  23208. indices.push(verticesLength + 2);
  23209. indices.push(verticesLength);
  23210. indices.push(verticesLength + 2);
  23211. indices.push(verticesLength + 3);
  23212. // Four vertices per face.
  23213. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23214. positions.push(vertex.x, vertex.y, vertex.z);
  23215. normals.push(normal.x, normal.y, normal.z);
  23216. uvs.push(faceUV[index].z, faceUV[index].w);
  23217. if (faceColors) {
  23218. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23219. }
  23220. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23221. positions.push(vertex.x, vertex.y, vertex.z);
  23222. normals.push(normal.x, normal.y, normal.z);
  23223. uvs.push(faceUV[index].x, faceUV[index].w);
  23224. if (faceColors) {
  23225. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23226. }
  23227. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23228. positions.push(vertex.x, vertex.y, vertex.z);
  23229. normals.push(normal.x, normal.y, normal.z);
  23230. uvs.push(faceUV[index].x, faceUV[index].y);
  23231. if (faceColors) {
  23232. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23233. }
  23234. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23235. positions.push(vertex.x, vertex.y, vertex.z);
  23236. normals.push(normal.x, normal.y, normal.z);
  23237. uvs.push(faceUV[index].z, faceUV[index].y);
  23238. if (faceColors) {
  23239. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23240. }
  23241. }
  23242. // sides
  23243. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23244. // Result
  23245. var vertexData = new VertexData();
  23246. vertexData.indices = indices;
  23247. vertexData.positions = positions;
  23248. vertexData.normals = normals;
  23249. vertexData.uvs = uvs;
  23250. if (faceColors) {
  23251. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23252. vertexData.colors = totalColors;
  23253. }
  23254. return vertexData;
  23255. };
  23256. VertexData.CreateSphere = function (options) {
  23257. var segments = options.segments || 32;
  23258. var diameterX = options.diameterX || options.diameter || 1;
  23259. var diameterY = options.diameterY || options.diameter || 1;
  23260. var diameterZ = options.diameterZ || options.diameter || 1;
  23261. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23262. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23263. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23264. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23265. var totalZRotationSteps = 2 + segments;
  23266. var totalYRotationSteps = 2 * totalZRotationSteps;
  23267. var indices = [];
  23268. var positions = [];
  23269. var normals = [];
  23270. var uvs = [];
  23271. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23272. var normalizedZ = zRotationStep / totalZRotationSteps;
  23273. var angleZ = normalizedZ * Math.PI * slice;
  23274. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23275. var normalizedY = yRotationStep / totalYRotationSteps;
  23276. var angleY = normalizedY * Math.PI * 2 * arc;
  23277. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23278. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23279. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23280. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23281. var vertex = complete.multiply(radius);
  23282. var normal = BABYLON.Vector3.Normalize(vertex);
  23283. positions.push(vertex.x, vertex.y, vertex.z);
  23284. normals.push(normal.x, normal.y, normal.z);
  23285. uvs.push(normalizedY, normalizedZ);
  23286. }
  23287. if (zRotationStep > 0) {
  23288. var verticesCount = positions.length / 3;
  23289. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23290. indices.push((firstIndex));
  23291. indices.push((firstIndex + 1));
  23292. indices.push(firstIndex + totalYRotationSteps + 1);
  23293. indices.push((firstIndex + totalYRotationSteps + 1));
  23294. indices.push((firstIndex + 1));
  23295. indices.push((firstIndex + totalYRotationSteps + 2));
  23296. }
  23297. }
  23298. }
  23299. // Sides
  23300. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23301. // Result
  23302. var vertexData = new VertexData();
  23303. vertexData.indices = indices;
  23304. vertexData.positions = positions;
  23305. vertexData.normals = normals;
  23306. vertexData.uvs = uvs;
  23307. return vertexData;
  23308. };
  23309. // Cylinder and cone
  23310. VertexData.CreateCylinder = function (options) {
  23311. var height = options.height || 2;
  23312. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23313. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23314. var tessellation = options.tessellation || 24;
  23315. var subdivisions = options.subdivisions || 1;
  23316. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23317. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23318. var faceUV = options.faceUV || new Array(3);
  23319. var faceColors = options.faceColors;
  23320. // default face colors and UV if undefined
  23321. for (var f = 0; f < 3; f++) {
  23322. if (faceColors && faceColors[f] === undefined) {
  23323. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23324. }
  23325. if (faceUV && faceUV[f] === undefined) {
  23326. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23327. }
  23328. }
  23329. var indices = [];
  23330. var positions = [];
  23331. var normals = [];
  23332. var uvs = [];
  23333. var colors = [];
  23334. var angle_step = Math.PI * 2 * arc / tessellation;
  23335. var angle;
  23336. var h;
  23337. var radius;
  23338. var tan = (diameterBottom - diameterTop) / 2 / height;
  23339. var ringVertex = BABYLON.Vector3.Zero();
  23340. var ringNormal = BABYLON.Vector3.Zero();
  23341. // positions, normals, uvs
  23342. var i;
  23343. var j;
  23344. for (i = 0; i <= subdivisions; i++) {
  23345. h = i / subdivisions;
  23346. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23347. for (j = 0; j <= tessellation; j++) {
  23348. angle = j * angle_step;
  23349. ringVertex.x = Math.cos(-angle) * radius;
  23350. ringVertex.y = -height / 2 + h * height;
  23351. ringVertex.z = Math.sin(-angle) * radius;
  23352. if (diameterTop === 0 && i === subdivisions) {
  23353. // if no top cap, reuse former normals
  23354. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23355. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23356. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23357. }
  23358. else {
  23359. ringNormal.x = ringVertex.x;
  23360. ringNormal.z = ringVertex.z;
  23361. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23362. ringNormal.normalize();
  23363. }
  23364. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23365. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23366. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23367. if (faceColors) {
  23368. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23369. }
  23370. }
  23371. }
  23372. // indices
  23373. for (i = 0; i < subdivisions; i++) {
  23374. for (j = 0; j < tessellation; j++) {
  23375. var i0 = i * (tessellation + 1) + j;
  23376. var i1 = (i + 1) * (tessellation + 1) + j;
  23377. var i2 = i * (tessellation + 1) + (j + 1);
  23378. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23379. indices.push(i0, i1, i2);
  23380. indices.push(i3, i2, i1);
  23381. }
  23382. }
  23383. // Caps
  23384. var createCylinderCap = function (isTop) {
  23385. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23386. if (radius === 0) {
  23387. return;
  23388. }
  23389. // Cap positions, normals & uvs
  23390. var angle;
  23391. var circleVector;
  23392. var i;
  23393. var u = (isTop) ? faceUV[2] : faceUV[0];
  23394. var c;
  23395. if (faceColors) {
  23396. c = (isTop) ? faceColors[2] : faceColors[0];
  23397. }
  23398. // cap center
  23399. var vbase = positions.length / 3;
  23400. var offset = isTop ? height / 2 : -height / 2;
  23401. var center = new BABYLON.Vector3(0, offset, 0);
  23402. positions.push(center.x, center.y, center.z);
  23403. normals.push(0, isTop ? 1 : -1, 0);
  23404. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23405. if (faceColors) {
  23406. colors.push(c.r, c.g, c.b, c.a);
  23407. }
  23408. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23409. for (i = 0; i <= tessellation; i++) {
  23410. angle = Math.PI * 2 * i * arc / tessellation;
  23411. var cos = Math.cos(-angle);
  23412. var sin = Math.sin(-angle);
  23413. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23414. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23415. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23416. normals.push(0, isTop ? 1 : -1, 0);
  23417. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23418. if (faceColors) {
  23419. colors.push(c.r, c.g, c.b, c.a);
  23420. }
  23421. }
  23422. // Cap indices
  23423. for (i = 0; i < tessellation; i++) {
  23424. if (!isTop) {
  23425. indices.push(vbase);
  23426. indices.push(vbase + (i + 1));
  23427. indices.push(vbase + (i + 2));
  23428. }
  23429. else {
  23430. indices.push(vbase);
  23431. indices.push(vbase + (i + 2));
  23432. indices.push(vbase + (i + 1));
  23433. }
  23434. }
  23435. };
  23436. // add caps to geometry
  23437. createCylinderCap(false);
  23438. createCylinderCap(true);
  23439. // Sides
  23440. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23441. var vertexData = new VertexData();
  23442. vertexData.indices = indices;
  23443. vertexData.positions = positions;
  23444. vertexData.normals = normals;
  23445. vertexData.uvs = uvs;
  23446. if (faceColors) {
  23447. vertexData.colors = colors;
  23448. }
  23449. return vertexData;
  23450. };
  23451. VertexData.CreateTorus = function (options) {
  23452. var indices = [];
  23453. var positions = [];
  23454. var normals = [];
  23455. var uvs = [];
  23456. var diameter = options.diameter || 1;
  23457. var thickness = options.thickness || 0.5;
  23458. var tessellation = options.tessellation || 16;
  23459. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23460. var stride = tessellation + 1;
  23461. for (var i = 0; i <= tessellation; i++) {
  23462. var u = i / tessellation;
  23463. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23464. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23465. for (var j = 0; j <= tessellation; j++) {
  23466. var v = 1 - j / tessellation;
  23467. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23468. var dx = Math.cos(innerAngle);
  23469. var dy = Math.sin(innerAngle);
  23470. // Create a vertex.
  23471. var normal = new BABYLON.Vector3(dx, dy, 0);
  23472. var position = normal.scale(thickness / 2);
  23473. var textureCoordinate = new BABYLON.Vector2(u, v);
  23474. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23475. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23476. positions.push(position.x, position.y, position.z);
  23477. normals.push(normal.x, normal.y, normal.z);
  23478. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23479. // And create indices for two triangles.
  23480. var nextI = (i + 1) % stride;
  23481. var nextJ = (j + 1) % stride;
  23482. indices.push(i * stride + j);
  23483. indices.push(i * stride + nextJ);
  23484. indices.push(nextI * stride + j);
  23485. indices.push(i * stride + nextJ);
  23486. indices.push(nextI * stride + nextJ);
  23487. indices.push(nextI * stride + j);
  23488. }
  23489. }
  23490. // Sides
  23491. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23492. // Result
  23493. var vertexData = new VertexData();
  23494. vertexData.indices = indices;
  23495. vertexData.positions = positions;
  23496. vertexData.normals = normals;
  23497. vertexData.uvs = uvs;
  23498. return vertexData;
  23499. };
  23500. VertexData.CreateLines = function (options) {
  23501. var indices = [];
  23502. var positions = [];
  23503. var points = options.points;
  23504. for (var index = 0; index < points.length; index++) {
  23505. positions.push(points[index].x, points[index].y, points[index].z);
  23506. if (index > 0) {
  23507. indices.push(index - 1);
  23508. indices.push(index);
  23509. }
  23510. }
  23511. // Result
  23512. var vertexData = new VertexData();
  23513. vertexData.indices = indices;
  23514. vertexData.positions = positions;
  23515. return vertexData;
  23516. };
  23517. VertexData.CreateDashedLines = function (options) {
  23518. var dashSize = options.dashSize || 3;
  23519. var gapSize = options.gapSize || 1;
  23520. var dashNb = options.dashNb || 200;
  23521. var points = options.points;
  23522. var positions = new Array();
  23523. var indices = new Array();
  23524. var curvect = BABYLON.Vector3.Zero();
  23525. var lg = 0;
  23526. var nb = 0;
  23527. var shft = 0;
  23528. var dashshft = 0;
  23529. var curshft = 0;
  23530. var idx = 0;
  23531. var i = 0;
  23532. for (i = 0; i < points.length - 1; i++) {
  23533. points[i + 1].subtractToRef(points[i], curvect);
  23534. lg += curvect.length();
  23535. }
  23536. shft = lg / dashNb;
  23537. dashshft = dashSize * shft / (dashSize + gapSize);
  23538. for (i = 0; i < points.length - 1; i++) {
  23539. points[i + 1].subtractToRef(points[i], curvect);
  23540. nb = Math.floor(curvect.length() / shft);
  23541. curvect.normalize();
  23542. for (var j = 0; j < nb; j++) {
  23543. curshft = shft * j;
  23544. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23545. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23546. indices.push(idx, idx + 1);
  23547. idx += 2;
  23548. }
  23549. }
  23550. // Result
  23551. var vertexData = new VertexData();
  23552. vertexData.positions = positions;
  23553. vertexData.indices = indices;
  23554. return vertexData;
  23555. };
  23556. VertexData.CreateGround = function (options) {
  23557. var indices = [];
  23558. var positions = [];
  23559. var normals = [];
  23560. var uvs = [];
  23561. var row, col;
  23562. var width = options.width || 1;
  23563. var height = options.height || 1;
  23564. var subdivisions = options.subdivisions || 1;
  23565. for (row = 0; row <= subdivisions; row++) {
  23566. for (col = 0; col <= subdivisions; col++) {
  23567. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23568. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23569. positions.push(position.x, position.y, position.z);
  23570. normals.push(normal.x, normal.y, normal.z);
  23571. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23572. }
  23573. }
  23574. for (row = 0; row < subdivisions; row++) {
  23575. for (col = 0; col < subdivisions; col++) {
  23576. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23577. indices.push(col + 1 + row * (subdivisions + 1));
  23578. indices.push(col + row * (subdivisions + 1));
  23579. indices.push(col + (row + 1) * (subdivisions + 1));
  23580. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23581. indices.push(col + row * (subdivisions + 1));
  23582. }
  23583. }
  23584. // Result
  23585. var vertexData = new VertexData();
  23586. vertexData.indices = indices;
  23587. vertexData.positions = positions;
  23588. vertexData.normals = normals;
  23589. vertexData.uvs = uvs;
  23590. return vertexData;
  23591. };
  23592. VertexData.CreateTiledGround = function (options) {
  23593. var xmin = options.xmin;
  23594. var zmin = options.zmin;
  23595. var xmax = options.xmax;
  23596. var zmax = options.zmax;
  23597. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23598. var precision = options.precision || { w: 1, h: 1 };
  23599. var indices = [];
  23600. var positions = [];
  23601. var normals = [];
  23602. var uvs = [];
  23603. var row, col, tileRow, tileCol;
  23604. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23605. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23606. precision.w = (precision.w < 1) ? 1 : precision.w;
  23607. precision.h = (precision.h < 1) ? 1 : precision.h;
  23608. var tileSize = {
  23609. 'w': (xmax - xmin) / subdivisions.w,
  23610. 'h': (zmax - zmin) / subdivisions.h
  23611. };
  23612. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23613. // Indices
  23614. var base = positions.length / 3;
  23615. var rowLength = precision.w + 1;
  23616. for (row = 0; row < precision.h; row++) {
  23617. for (col = 0; col < precision.w; col++) {
  23618. var square = [
  23619. base + col + row * rowLength,
  23620. base + (col + 1) + row * rowLength,
  23621. base + (col + 1) + (row + 1) * rowLength,
  23622. base + col + (row + 1) * rowLength
  23623. ];
  23624. indices.push(square[1]);
  23625. indices.push(square[2]);
  23626. indices.push(square[3]);
  23627. indices.push(square[0]);
  23628. indices.push(square[1]);
  23629. indices.push(square[3]);
  23630. }
  23631. }
  23632. // Position, normals and uvs
  23633. var position = BABYLON.Vector3.Zero();
  23634. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23635. for (row = 0; row <= precision.h; row++) {
  23636. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23637. for (col = 0; col <= precision.w; col++) {
  23638. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23639. position.y = 0;
  23640. positions.push(position.x, position.y, position.z);
  23641. normals.push(normal.x, normal.y, normal.z);
  23642. uvs.push(col / precision.w, row / precision.h);
  23643. }
  23644. }
  23645. }
  23646. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23647. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23648. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23649. }
  23650. }
  23651. // Result
  23652. var vertexData = new VertexData();
  23653. vertexData.indices = indices;
  23654. vertexData.positions = positions;
  23655. vertexData.normals = normals;
  23656. vertexData.uvs = uvs;
  23657. return vertexData;
  23658. };
  23659. VertexData.CreateGroundFromHeightMap = function (options) {
  23660. var indices = [];
  23661. var positions = [];
  23662. var normals = [];
  23663. var uvs = [];
  23664. var row, col;
  23665. // Vertices
  23666. for (row = 0; row <= options.subdivisions; row++) {
  23667. for (col = 0; col <= options.subdivisions; col++) {
  23668. 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));
  23669. // Compute height
  23670. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23671. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23672. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23673. var r = options.buffer[pos] / 255.0;
  23674. var g = options.buffer[pos + 1] / 255.0;
  23675. var b = options.buffer[pos + 2] / 255.0;
  23676. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23677. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23678. // Add vertex
  23679. positions.push(position.x, position.y, position.z);
  23680. normals.push(0, 0, 0);
  23681. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23682. }
  23683. }
  23684. // Indices
  23685. for (row = 0; row < options.subdivisions; row++) {
  23686. for (col = 0; col < options.subdivisions; col++) {
  23687. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23688. indices.push(col + 1 + row * (options.subdivisions + 1));
  23689. indices.push(col + row * (options.subdivisions + 1));
  23690. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23691. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23692. indices.push(col + row * (options.subdivisions + 1));
  23693. }
  23694. }
  23695. // Normals
  23696. VertexData.ComputeNormals(positions, indices, normals);
  23697. // Result
  23698. var vertexData = new VertexData();
  23699. vertexData.indices = indices;
  23700. vertexData.positions = positions;
  23701. vertexData.normals = normals;
  23702. vertexData.uvs = uvs;
  23703. return vertexData;
  23704. };
  23705. VertexData.CreatePlane = function (options) {
  23706. var indices = [];
  23707. var positions = [];
  23708. var normals = [];
  23709. var uvs = [];
  23710. var width = options.width || options.size || 1;
  23711. var height = options.height || options.size || 1;
  23712. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23713. // Vertices
  23714. var halfWidth = width / 2.0;
  23715. var halfHeight = height / 2.0;
  23716. positions.push(-halfWidth, -halfHeight, 0);
  23717. normals.push(0, 0, -1.0);
  23718. uvs.push(0.0, 0.0);
  23719. positions.push(halfWidth, -halfHeight, 0);
  23720. normals.push(0, 0, -1.0);
  23721. uvs.push(1.0, 0.0);
  23722. positions.push(halfWidth, halfHeight, 0);
  23723. normals.push(0, 0, -1.0);
  23724. uvs.push(1.0, 1.0);
  23725. positions.push(-halfWidth, halfHeight, 0);
  23726. normals.push(0, 0, -1.0);
  23727. uvs.push(0.0, 1.0);
  23728. // Indices
  23729. indices.push(0);
  23730. indices.push(1);
  23731. indices.push(2);
  23732. indices.push(0);
  23733. indices.push(2);
  23734. indices.push(3);
  23735. // Sides
  23736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23737. // Result
  23738. var vertexData = new VertexData();
  23739. vertexData.indices = indices;
  23740. vertexData.positions = positions;
  23741. vertexData.normals = normals;
  23742. vertexData.uvs = uvs;
  23743. return vertexData;
  23744. };
  23745. VertexData.CreateDisc = function (options) {
  23746. var positions = [];
  23747. var indices = [];
  23748. var normals = [];
  23749. var uvs = [];
  23750. var radius = options.radius || 0.5;
  23751. var tessellation = options.tessellation || 64;
  23752. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23753. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23754. // positions and uvs
  23755. positions.push(0, 0, 0); // disc center first
  23756. uvs.push(0.5, 0.5);
  23757. var theta = Math.PI * 2 * arc;
  23758. var step = theta / tessellation;
  23759. for (var a = 0; a < theta; a += step) {
  23760. var x = Math.cos(a);
  23761. var y = Math.sin(a);
  23762. var u = (x + 1) / 2;
  23763. var v = (1 - y) / 2;
  23764. positions.push(radius * x, radius * y, 0);
  23765. uvs.push(u, v);
  23766. }
  23767. if (arc === 1) {
  23768. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23769. uvs.push(uvs[2], uvs[3]);
  23770. }
  23771. //indices
  23772. var vertexNb = positions.length / 3;
  23773. for (var i = 1; i < vertexNb - 1; i++) {
  23774. indices.push(i + 1, 0, i);
  23775. }
  23776. // result
  23777. VertexData.ComputeNormals(positions, indices, normals);
  23778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23779. var vertexData = new VertexData();
  23780. vertexData.indices = indices;
  23781. vertexData.positions = positions;
  23782. vertexData.normals = normals;
  23783. vertexData.uvs = uvs;
  23784. return vertexData;
  23785. };
  23786. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  23787. VertexData.CreatePolyhedron = function (options) {
  23788. // provided polyhedron types :
  23789. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  23790. // 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)
  23791. var polyhedra = [];
  23792. 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]] };
  23793. 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]] };
  23794. polyhedra[2] = {
  23795. 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]],
  23796. 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]]
  23797. };
  23798. polyhedra[3] = {
  23799. 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]],
  23800. 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]]
  23801. };
  23802. polyhedra[4] = {
  23803. 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]],
  23804. 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]]
  23805. };
  23806. 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]] };
  23807. 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]] };
  23808. 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]] };
  23809. 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]] };
  23810. 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]] };
  23811. 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]] };
  23812. 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]] };
  23813. 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]] };
  23814. 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]] };
  23815. polyhedra[14] = {
  23816. 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]],
  23817. 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]]
  23818. };
  23819. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  23820. var size = options.size;
  23821. var sizeX = options.sizeX || size || 1;
  23822. var sizeY = options.sizeY || size || 1;
  23823. var sizeZ = options.sizeZ || size || 1;
  23824. var data = options.custom || polyhedra[type];
  23825. var nbfaces = data.face.length;
  23826. var faceUV = options.faceUV || new Array(nbfaces);
  23827. var faceColors = options.faceColors;
  23828. var singleFace = options.singleFace;
  23829. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23830. var positions = [];
  23831. var indices = [];
  23832. var normals = [];
  23833. var uvs = [];
  23834. var colors = [];
  23835. var index = 0;
  23836. var faceIdx = 0; // face cursor in the array "indexes"
  23837. var indexes = [];
  23838. var i = 0;
  23839. var f = 0;
  23840. var u, v, ang, x, y, tmp;
  23841. // default face colors and UV if undefined
  23842. if (!singleFace) {
  23843. for (f = 0; f < nbfaces; f++) {
  23844. if (faceColors && faceColors[f] === undefined) {
  23845. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23846. }
  23847. if (faceUV && faceUV[f] === undefined) {
  23848. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23849. }
  23850. }
  23851. }
  23852. if (singleFace) {
  23853. for (i = 0; i < data.vertex.length; i++) {
  23854. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  23855. uvs.push(0, 0);
  23856. }
  23857. for (f = 0; f < nbfaces; f++) {
  23858. for (i = 0; i < data.face[f].length - 2; i++) {
  23859. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  23860. }
  23861. }
  23862. }
  23863. else {
  23864. for (f = 0; f < nbfaces; f++) {
  23865. var fl = data.face[f].length; // number of vertices of the current face
  23866. ang = 2 * Math.PI / fl;
  23867. x = 0.5 * Math.tan(ang / 2);
  23868. y = 0.5;
  23869. // positions, uvs, colors
  23870. for (i = 0; i < fl; i++) {
  23871. // positions
  23872. 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);
  23873. indexes.push(index);
  23874. index++;
  23875. // uvs
  23876. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  23877. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  23878. uvs.push(u, v);
  23879. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  23880. y = x * Math.sin(ang) + y * Math.cos(ang);
  23881. x = tmp;
  23882. // colors
  23883. if (faceColors) {
  23884. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  23885. }
  23886. }
  23887. // indices from indexes
  23888. for (i = 0; i < fl - 2; i++) {
  23889. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  23890. }
  23891. faceIdx += fl;
  23892. }
  23893. }
  23894. VertexData.ComputeNormals(positions, indices, normals);
  23895. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23896. var vertexData = new VertexData();
  23897. vertexData.positions = positions;
  23898. vertexData.indices = indices;
  23899. vertexData.normals = normals;
  23900. vertexData.uvs = uvs;
  23901. if (faceColors && !singleFace) {
  23902. vertexData.colors = colors;
  23903. }
  23904. return vertexData;
  23905. };
  23906. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23907. VertexData.CreateTorusKnot = function (options) {
  23908. var indices = [];
  23909. var positions = [];
  23910. var normals = [];
  23911. var uvs = [];
  23912. var radius = options.radius || 2;
  23913. var tube = options.tube || 0.5;
  23914. var radialSegments = options.radialSegments || 32;
  23915. var tubularSegments = options.tubularSegments || 32;
  23916. var p = options.p || 2;
  23917. var q = options.q || 3;
  23918. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23919. // Helper
  23920. var getPos = function (angle) {
  23921. var cu = Math.cos(angle);
  23922. var su = Math.sin(angle);
  23923. var quOverP = q / p * angle;
  23924. var cs = Math.cos(quOverP);
  23925. var tx = radius * (2 + cs) * 0.5 * cu;
  23926. var ty = radius * (2 + cs) * su * 0.5;
  23927. var tz = radius * Math.sin(quOverP) * 0.5;
  23928. return new BABYLON.Vector3(tx, ty, tz);
  23929. };
  23930. // Vertices
  23931. var i;
  23932. var j;
  23933. for (i = 0; i <= radialSegments; i++) {
  23934. var modI = i % radialSegments;
  23935. var u = modI / radialSegments * 2 * p * Math.PI;
  23936. var p1 = getPos(u);
  23937. var p2 = getPos(u + 0.01);
  23938. var tang = p2.subtract(p1);
  23939. var n = p2.add(p1);
  23940. var bitan = BABYLON.Vector3.Cross(tang, n);
  23941. n = BABYLON.Vector3.Cross(bitan, tang);
  23942. bitan.normalize();
  23943. n.normalize();
  23944. for (j = 0; j < tubularSegments; j++) {
  23945. var modJ = j % tubularSegments;
  23946. var v = modJ / tubularSegments * 2 * Math.PI;
  23947. var cx = -tube * Math.cos(v);
  23948. var cy = tube * Math.sin(v);
  23949. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23950. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23951. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23952. uvs.push(i / radialSegments);
  23953. uvs.push(j / tubularSegments);
  23954. }
  23955. }
  23956. for (i = 0; i < radialSegments; i++) {
  23957. for (j = 0; j < tubularSegments; j++) {
  23958. var jNext = (j + 1) % tubularSegments;
  23959. var a = i * tubularSegments + j;
  23960. var b = (i + 1) * tubularSegments + j;
  23961. var c = (i + 1) * tubularSegments + jNext;
  23962. var d = i * tubularSegments + jNext;
  23963. indices.push(d);
  23964. indices.push(b);
  23965. indices.push(a);
  23966. indices.push(d);
  23967. indices.push(c);
  23968. indices.push(b);
  23969. }
  23970. }
  23971. // Normals
  23972. VertexData.ComputeNormals(positions, indices, normals);
  23973. // Sides
  23974. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23975. // Result
  23976. var vertexData = new VertexData();
  23977. vertexData.indices = indices;
  23978. vertexData.positions = positions;
  23979. vertexData.normals = normals;
  23980. vertexData.uvs = uvs;
  23981. return vertexData;
  23982. };
  23983. // Tools
  23984. /**
  23985. * @param {any} - positions (number[] or Float32Array)
  23986. * @param {any} - indices (number[] or Uint16Array)
  23987. * @param {any} - normals (number[] or Float32Array)
  23988. */
  23989. VertexData.ComputeNormals = function (positions, indices, normals) {
  23990. var index = 0;
  23991. // temp Vector3
  23992. var p1p2 = BABYLON.Vector3.Zero();
  23993. var p3p2 = BABYLON.Vector3.Zero();
  23994. var faceNormal = BABYLON.Vector3.Zero();
  23995. var vertexNormali1 = BABYLON.Vector3.Zero();
  23996. for (index = 0; index < positions.length; index++) {
  23997. normals[index] = 0.0;
  23998. }
  23999. // indice triplet = 1 face
  24000. var nbFaces = indices.length / 3;
  24001. for (index = 0; index < nbFaces; index++) {
  24002. var i1 = indices[index * 3];
  24003. var i2 = indices[index * 3 + 1];
  24004. var i3 = indices[index * 3 + 2];
  24005. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  24006. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24007. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24008. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  24009. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24010. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24011. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24012. faceNormal.normalize();
  24013. normals[i1 * 3] += faceNormal.x;
  24014. normals[i1 * 3 + 1] += faceNormal.y;
  24015. normals[i1 * 3 + 2] += faceNormal.z;
  24016. normals[i2 * 3] += faceNormal.x;
  24017. normals[i2 * 3 + 1] += faceNormal.y;
  24018. normals[i2 * 3 + 2] += faceNormal.z;
  24019. normals[i3 * 3] += faceNormal.x;
  24020. normals[i3 * 3 + 1] += faceNormal.y;
  24021. normals[i3 * 3 + 2] += faceNormal.z;
  24022. }
  24023. // last normalization
  24024. for (index = 0; index < normals.length / 3; index++) {
  24025. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24026. vertexNormali1.normalize();
  24027. normals[index * 3] = vertexNormali1.x;
  24028. normals[index * 3 + 1] = vertexNormali1.y;
  24029. normals[index * 3 + 2] = vertexNormali1.z;
  24030. }
  24031. };
  24032. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24033. var li = indices.length;
  24034. var ln = normals.length;
  24035. var i;
  24036. var n;
  24037. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24038. switch (sideOrientation) {
  24039. case BABYLON.Mesh.FRONTSIDE:
  24040. // nothing changed
  24041. break;
  24042. case BABYLON.Mesh.BACKSIDE:
  24043. var tmp;
  24044. // indices
  24045. for (i = 0; i < li; i += 3) {
  24046. tmp = indices[i];
  24047. indices[i] = indices[i + 2];
  24048. indices[i + 2] = tmp;
  24049. }
  24050. // normals
  24051. for (n = 0; n < ln; n++) {
  24052. normals[n] = -normals[n];
  24053. }
  24054. break;
  24055. case BABYLON.Mesh.DOUBLESIDE:
  24056. // positions
  24057. var lp = positions.length;
  24058. var l = lp / 3;
  24059. for (var p = 0; p < lp; p++) {
  24060. positions[lp + p] = positions[p];
  24061. }
  24062. // indices
  24063. for (i = 0; i < li; i += 3) {
  24064. indices[i + li] = indices[i + 2] + l;
  24065. indices[i + 1 + li] = indices[i + 1] + l;
  24066. indices[i + 2 + li] = indices[i] + l;
  24067. }
  24068. // normals
  24069. for (n = 0; n < ln; n++) {
  24070. normals[ln + n] = -normals[n];
  24071. }
  24072. // uvs
  24073. var lu = uvs.length;
  24074. for (var u = 0; u < lu; u++) {
  24075. uvs[u + lu] = uvs[u];
  24076. }
  24077. break;
  24078. }
  24079. };
  24080. return VertexData;
  24081. })();
  24082. BABYLON.VertexData = VertexData;
  24083. })(BABYLON || (BABYLON = {}));
  24084. var BABYLON;
  24085. (function (BABYLON) {
  24086. var Tags = (function () {
  24087. function Tags() {
  24088. }
  24089. Tags.EnableFor = function (obj) {
  24090. obj._tags = obj._tags || {};
  24091. obj.hasTags = function () {
  24092. return Tags.HasTags(obj);
  24093. };
  24094. obj.addTags = function (tagsString) {
  24095. return Tags.AddTagsTo(obj, tagsString);
  24096. };
  24097. obj.removeTags = function (tagsString) {
  24098. return Tags.RemoveTagsFrom(obj, tagsString);
  24099. };
  24100. obj.matchesTagsQuery = function (tagsQuery) {
  24101. return Tags.MatchesQuery(obj, tagsQuery);
  24102. };
  24103. };
  24104. Tags.DisableFor = function (obj) {
  24105. delete obj._tags;
  24106. delete obj.hasTags;
  24107. delete obj.addTags;
  24108. delete obj.removeTags;
  24109. delete obj.matchesTagsQuery;
  24110. };
  24111. Tags.HasTags = function (obj) {
  24112. if (!obj._tags) {
  24113. return false;
  24114. }
  24115. return !BABYLON.Tools.IsEmpty(obj._tags);
  24116. };
  24117. Tags.GetTags = function (obj) {
  24118. if (!obj._tags) {
  24119. return null;
  24120. }
  24121. return obj._tags;
  24122. };
  24123. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24124. // a tag cannot start with '||', '&&', and '!'
  24125. // it cannot contain whitespaces
  24126. Tags.AddTagsTo = function (obj, tagsString) {
  24127. if (!tagsString) {
  24128. return;
  24129. }
  24130. if (typeof tagsString !== "string") {
  24131. return;
  24132. }
  24133. var tags = tagsString.split(" ");
  24134. for (var t in tags) {
  24135. Tags._AddTagTo(obj, tags[t]);
  24136. }
  24137. };
  24138. Tags._AddTagTo = function (obj, tag) {
  24139. tag = tag.trim();
  24140. if (tag === "" || tag === "true" || tag === "false") {
  24141. return;
  24142. }
  24143. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24144. return;
  24145. }
  24146. Tags.EnableFor(obj);
  24147. obj._tags[tag] = true;
  24148. };
  24149. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24150. if (!Tags.HasTags(obj)) {
  24151. return;
  24152. }
  24153. var tags = tagsString.split(" ");
  24154. for (var t in tags) {
  24155. Tags._RemoveTagFrom(obj, tags[t]);
  24156. }
  24157. };
  24158. Tags._RemoveTagFrom = function (obj, tag) {
  24159. delete obj._tags[tag];
  24160. };
  24161. Tags.MatchesQuery = function (obj, tagsQuery) {
  24162. if (tagsQuery === undefined) {
  24163. return true;
  24164. }
  24165. if (tagsQuery === "") {
  24166. return Tags.HasTags(obj);
  24167. }
  24168. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24169. };
  24170. return Tags;
  24171. })();
  24172. BABYLON.Tags = Tags;
  24173. })(BABYLON || (BABYLON = {}));
  24174. var BABYLON;
  24175. (function (BABYLON) {
  24176. var Internals;
  24177. (function (Internals) {
  24178. var AndOrNotEvaluator = (function () {
  24179. function AndOrNotEvaluator() {
  24180. }
  24181. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24182. if (!query.match(/\([^\(\)]*\)/g)) {
  24183. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24184. }
  24185. else {
  24186. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24187. // remove parenthesis
  24188. r = r.slice(1, r.length - 1);
  24189. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24190. });
  24191. }
  24192. if (query === "true") {
  24193. return true;
  24194. }
  24195. if (query === "false") {
  24196. return false;
  24197. }
  24198. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24199. };
  24200. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24201. evaluateCallback = evaluateCallback || (function (r) {
  24202. return r === "true" ? true : false;
  24203. });
  24204. var result;
  24205. var or = parenthesisContent.split("||");
  24206. for (var i in or) {
  24207. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24208. var and = ori.split("&&");
  24209. if (and.length > 1) {
  24210. for (var j = 0; j < and.length; ++j) {
  24211. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24212. if (andj !== "true" && andj !== "false") {
  24213. if (andj[0] === "!") {
  24214. result = !evaluateCallback(andj.substring(1));
  24215. }
  24216. else {
  24217. result = evaluateCallback(andj);
  24218. }
  24219. }
  24220. else {
  24221. result = andj === "true" ? true : false;
  24222. }
  24223. if (!result) {
  24224. ori = "false";
  24225. break;
  24226. }
  24227. }
  24228. }
  24229. if (result || ori === "true") {
  24230. result = true;
  24231. break;
  24232. }
  24233. // result equals false (or undefined)
  24234. if (ori !== "true" && ori !== "false") {
  24235. if (ori[0] === "!") {
  24236. result = !evaluateCallback(ori.substring(1));
  24237. }
  24238. else {
  24239. result = evaluateCallback(ori);
  24240. }
  24241. }
  24242. else {
  24243. result = ori === "true" ? true : false;
  24244. }
  24245. }
  24246. // the whole parenthesis scope is replaced by 'true' or 'false'
  24247. return result ? "true" : "false";
  24248. };
  24249. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24250. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24251. // remove whitespaces
  24252. r = r.replace(/[\s]/g, function () { return ""; });
  24253. return r.length % 2 ? "!" : "";
  24254. });
  24255. booleanString = booleanString.trim();
  24256. if (booleanString === "!true") {
  24257. booleanString = "false";
  24258. }
  24259. else if (booleanString === "!false") {
  24260. booleanString = "true";
  24261. }
  24262. return booleanString;
  24263. };
  24264. return AndOrNotEvaluator;
  24265. })();
  24266. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24267. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24268. })(BABYLON || (BABYLON = {}));
  24269. var BABYLON;
  24270. (function (BABYLON) {
  24271. var PostProcessRenderPass = (function () {
  24272. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24273. this._enabled = true;
  24274. this._refCount = 0;
  24275. this._name = name;
  24276. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24277. this.setRenderList(renderList);
  24278. this._renderTexture.onBeforeRender = beforeRender;
  24279. this._renderTexture.onAfterRender = afterRender;
  24280. this._scene = scene;
  24281. this._renderList = renderList;
  24282. }
  24283. // private
  24284. PostProcessRenderPass.prototype._incRefCount = function () {
  24285. if (this._refCount === 0) {
  24286. this._scene.customRenderTargets.push(this._renderTexture);
  24287. }
  24288. return ++this._refCount;
  24289. };
  24290. PostProcessRenderPass.prototype._decRefCount = function () {
  24291. this._refCount--;
  24292. if (this._refCount <= 0) {
  24293. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24294. }
  24295. return this._refCount;
  24296. };
  24297. PostProcessRenderPass.prototype._update = function () {
  24298. this.setRenderList(this._renderList);
  24299. };
  24300. // public
  24301. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24302. this._renderTexture.renderList = renderList;
  24303. };
  24304. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24305. return this._renderTexture;
  24306. };
  24307. return PostProcessRenderPass;
  24308. })();
  24309. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24310. })(BABYLON || (BABYLON = {}));
  24311. var BABYLON;
  24312. (function (BABYLON) {
  24313. var PostProcessRenderEffect = (function () {
  24314. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24315. this._engine = engine;
  24316. this._name = name;
  24317. this._singleInstance = singleInstance || true;
  24318. this._getPostProcess = getPostProcess;
  24319. this._cameras = [];
  24320. this._indicesForCamera = [];
  24321. this._postProcesses = {};
  24322. this._renderPasses = {};
  24323. this._renderEffectAsPasses = {};
  24324. }
  24325. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24326. get: function () {
  24327. for (var index in this._postProcesses) {
  24328. if (!this._postProcesses[index].isSupported) {
  24329. return false;
  24330. }
  24331. }
  24332. return true;
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. PostProcessRenderEffect.prototype._update = function () {
  24338. for (var renderPassName in this._renderPasses) {
  24339. this._renderPasses[renderPassName]._update();
  24340. }
  24341. };
  24342. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24343. this._renderPasses[renderPass._name] = renderPass;
  24344. this._linkParameters();
  24345. };
  24346. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24347. delete this._renderPasses[renderPass._name];
  24348. this._linkParameters();
  24349. };
  24350. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24351. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24352. this._linkParameters();
  24353. };
  24354. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24355. for (var renderPassName in this._renderPasses) {
  24356. if (renderPassName === passName) {
  24357. return this._renderPasses[passName];
  24358. }
  24359. }
  24360. };
  24361. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24362. this._renderPasses = {};
  24363. this._linkParameters();
  24364. };
  24365. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24366. var cameraKey;
  24367. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24368. for (var i = 0; i < _cam.length; i++) {
  24369. var camera = _cam[i];
  24370. var cameraName = camera.name;
  24371. if (this._singleInstance) {
  24372. cameraKey = 0;
  24373. }
  24374. else {
  24375. cameraKey = cameraName;
  24376. }
  24377. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24378. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24379. if (!this._indicesForCamera[cameraName]) {
  24380. this._indicesForCamera[cameraName] = [];
  24381. }
  24382. this._indicesForCamera[cameraName].push(index);
  24383. if (this._cameras.indexOf(camera) === -1) {
  24384. this._cameras[cameraName] = camera;
  24385. }
  24386. for (var passName in this._renderPasses) {
  24387. this._renderPasses[passName]._incRefCount();
  24388. }
  24389. }
  24390. this._linkParameters();
  24391. };
  24392. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24393. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24394. for (var i = 0; i < _cam.length; i++) {
  24395. var camera = _cam[i];
  24396. var cameraName = camera.name;
  24397. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24398. var index = this._cameras.indexOf(cameraName);
  24399. this._indicesForCamera.splice(index, 1);
  24400. this._cameras.splice(index, 1);
  24401. for (var passName in this._renderPasses) {
  24402. this._renderPasses[passName]._decRefCount();
  24403. }
  24404. }
  24405. };
  24406. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24407. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24408. for (var i = 0; i < _cam.length; i++) {
  24409. var camera = _cam[i];
  24410. var cameraName = camera.name;
  24411. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24412. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24413. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24414. }
  24415. }
  24416. for (var passName in this._renderPasses) {
  24417. this._renderPasses[passName]._incRefCount();
  24418. }
  24419. }
  24420. };
  24421. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24422. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24423. for (var i = 0; i < _cam.length; i++) {
  24424. var camera = _cam[i];
  24425. var cameraName = camera.Name;
  24426. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24427. for (var passName in this._renderPasses) {
  24428. this._renderPasses[passName]._decRefCount();
  24429. }
  24430. }
  24431. };
  24432. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24433. if (this._singleInstance) {
  24434. return this._postProcesses[0];
  24435. }
  24436. else {
  24437. return this._postProcesses[camera.name];
  24438. }
  24439. };
  24440. PostProcessRenderEffect.prototype._linkParameters = function () {
  24441. var _this = this;
  24442. for (var index in this._postProcesses) {
  24443. if (this.applyParameters) {
  24444. this.applyParameters(this._postProcesses[index]);
  24445. }
  24446. this._postProcesses[index].onBeforeRender = function (effect) {
  24447. _this._linkTextures(effect);
  24448. };
  24449. }
  24450. };
  24451. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24452. for (var renderPassName in this._renderPasses) {
  24453. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24454. }
  24455. for (var renderEffectName in this._renderEffectAsPasses) {
  24456. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24457. }
  24458. };
  24459. return PostProcessRenderEffect;
  24460. })();
  24461. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24462. })(BABYLON || (BABYLON = {}));
  24463. var BABYLON;
  24464. (function (BABYLON) {
  24465. var PostProcessRenderPipeline = (function () {
  24466. function PostProcessRenderPipeline(engine, name) {
  24467. this._engine = engine;
  24468. this._name = name;
  24469. this._renderEffects = {};
  24470. this._renderEffectsForIsolatedPass = {};
  24471. this._cameras = [];
  24472. }
  24473. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24474. get: function () {
  24475. for (var renderEffectName in this._renderEffects) {
  24476. if (!this._renderEffects[renderEffectName].isSupported) {
  24477. return false;
  24478. }
  24479. }
  24480. return true;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24486. this._renderEffects[renderEffect._name] = renderEffect;
  24487. };
  24488. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24489. var renderEffects = this._renderEffects[renderEffectName];
  24490. if (!renderEffects) {
  24491. return;
  24492. }
  24493. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24494. };
  24495. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24496. var renderEffects = this._renderEffects[renderEffectName];
  24497. if (!renderEffects) {
  24498. return;
  24499. }
  24500. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24501. };
  24502. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24503. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24504. var indicesToDelete = [];
  24505. var i;
  24506. for (i = 0; i < _cam.length; i++) {
  24507. var camera = _cam[i];
  24508. var cameraName = camera.name;
  24509. if (this._cameras.indexOf(camera) === -1) {
  24510. this._cameras[cameraName] = camera;
  24511. }
  24512. else if (unique) {
  24513. indicesToDelete.push(i);
  24514. }
  24515. }
  24516. for (i = 0; i < indicesToDelete.length; i++) {
  24517. cameras.splice(indicesToDelete[i], 1);
  24518. }
  24519. for (var renderEffectName in this._renderEffects) {
  24520. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24521. }
  24522. };
  24523. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24524. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24525. for (var renderEffectName in this._renderEffects) {
  24526. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24527. }
  24528. for (var i = 0; i < _cam.length; i++) {
  24529. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24530. }
  24531. };
  24532. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24533. var _this = this;
  24534. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24535. var pass = null;
  24536. var renderEffectName;
  24537. for (renderEffectName in this._renderEffects) {
  24538. pass = this._renderEffects[renderEffectName].getPass(passName);
  24539. if (pass != null) {
  24540. break;
  24541. }
  24542. }
  24543. if (pass === null) {
  24544. return;
  24545. }
  24546. for (renderEffectName in this._renderEffects) {
  24547. this._renderEffects[renderEffectName]._disable(_cam);
  24548. }
  24549. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24550. for (var i = 0; i < _cam.length; i++) {
  24551. var camera = _cam[i];
  24552. var cameraName = camera.name;
  24553. 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); });
  24554. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24555. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24556. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24557. }
  24558. };
  24559. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24560. var _this = this;
  24561. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24562. for (var i = 0; i < _cam.length; i++) {
  24563. var camera = _cam[i];
  24564. var cameraName = camera.name;
  24565. 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); });
  24566. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24567. }
  24568. for (var renderEffectName in this._renderEffects) {
  24569. this._renderEffects[renderEffectName]._enable(_cam);
  24570. }
  24571. };
  24572. PostProcessRenderPipeline.prototype._update = function () {
  24573. for (var renderEffectName in this._renderEffects) {
  24574. this._renderEffects[renderEffectName]._update();
  24575. }
  24576. for (var i = 0; i < this._cameras.length; i++) {
  24577. var cameraName = this._cameras[i].name;
  24578. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24579. this._renderEffectsForIsolatedPass[cameraName]._update();
  24580. }
  24581. }
  24582. };
  24583. PostProcessRenderPipeline.prototype.dispose = function () {
  24584. // Must be implemented by children
  24585. };
  24586. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24587. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24588. return PostProcessRenderPipeline;
  24589. })();
  24590. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24591. })(BABYLON || (BABYLON = {}));
  24592. var BABYLON;
  24593. (function (BABYLON) {
  24594. var PostProcessRenderPipelineManager = (function () {
  24595. function PostProcessRenderPipelineManager() {
  24596. this._renderPipelines = {};
  24597. }
  24598. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24599. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24600. };
  24601. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24602. var renderPipeline = this._renderPipelines[renderPipelineName];
  24603. if (!renderPipeline) {
  24604. return;
  24605. }
  24606. renderPipeline._attachCameras(cameras, unique);
  24607. };
  24608. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24609. var renderPipeline = this._renderPipelines[renderPipelineName];
  24610. if (!renderPipeline) {
  24611. return;
  24612. }
  24613. renderPipeline._detachCameras(cameras);
  24614. };
  24615. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24616. var renderPipeline = this._renderPipelines[renderPipelineName];
  24617. if (!renderPipeline) {
  24618. return;
  24619. }
  24620. renderPipeline._enableEffect(renderEffectName, cameras);
  24621. };
  24622. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24623. var renderPipeline = this._renderPipelines[renderPipelineName];
  24624. if (!renderPipeline) {
  24625. return;
  24626. }
  24627. renderPipeline._disableEffect(renderEffectName, cameras);
  24628. };
  24629. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24630. var renderPipeline = this._renderPipelines[renderPipelineName];
  24631. if (!renderPipeline) {
  24632. return;
  24633. }
  24634. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24635. };
  24636. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24637. var renderPipeline = this._renderPipelines[renderPipelineName];
  24638. if (!renderPipeline) {
  24639. return;
  24640. }
  24641. renderPipeline._disableDisplayOnlyPass(cameras);
  24642. };
  24643. PostProcessRenderPipelineManager.prototype.update = function () {
  24644. for (var renderPipelineName in this._renderPipelines) {
  24645. var pipeline = this._renderPipelines[renderPipelineName];
  24646. if (!pipeline.isSupported) {
  24647. pipeline.dispose();
  24648. delete this._renderPipelines[renderPipelineName];
  24649. }
  24650. else {
  24651. pipeline._update();
  24652. }
  24653. }
  24654. };
  24655. return PostProcessRenderPipelineManager;
  24656. })();
  24657. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24658. })(BABYLON || (BABYLON = {}));
  24659. var BABYLON;
  24660. (function (BABYLON) {
  24661. var BoundingBoxRenderer = (function () {
  24662. function BoundingBoxRenderer(scene) {
  24663. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24664. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24665. this.showBackLines = true;
  24666. this.renderList = new BABYLON.SmartArray(32);
  24667. this._scene = scene;
  24668. }
  24669. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24670. if (this._colorShader) {
  24671. return;
  24672. }
  24673. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24674. attributes: ["position"],
  24675. uniforms: ["worldViewProjection", "color"]
  24676. });
  24677. var engine = this._scene.getEngine();
  24678. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24679. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24680. 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]);
  24681. };
  24682. BoundingBoxRenderer.prototype.reset = function () {
  24683. this.renderList.reset();
  24684. };
  24685. BoundingBoxRenderer.prototype.render = function () {
  24686. if (this.renderList.length === 0) {
  24687. return;
  24688. }
  24689. this._prepareRessources();
  24690. if (!this._colorShader.isReady()) {
  24691. return;
  24692. }
  24693. var engine = this._scene.getEngine();
  24694. engine.setDepthWrite(false);
  24695. this._colorShader._preBind();
  24696. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24697. var boundingBox = this.renderList.data[boundingBoxIndex];
  24698. var min = boundingBox.minimum;
  24699. var max = boundingBox.maximum;
  24700. var diff = max.subtract(min);
  24701. var median = min.add(diff.scale(0.5));
  24702. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24703. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24704. .multiply(boundingBox.getWorldMatrix());
  24705. // VBOs
  24706. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24707. if (this.showBackLines) {
  24708. // Back
  24709. engine.setDepthFunctionToGreaterOrEqual();
  24710. this._scene.resetCachedMaterial();
  24711. this._colorShader.setColor4("color", this.backColor.toColor4());
  24712. this._colorShader.bind(worldMatrix);
  24713. // Draw order
  24714. engine.draw(false, 0, 24);
  24715. }
  24716. // Front
  24717. engine.setDepthFunctionToLess();
  24718. this._scene.resetCachedMaterial();
  24719. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24720. this._colorShader.bind(worldMatrix);
  24721. // Draw order
  24722. engine.draw(false, 0, 24);
  24723. }
  24724. this._colorShader.unbind();
  24725. engine.setDepthFunctionToLessOrEqual();
  24726. engine.setDepthWrite(true);
  24727. };
  24728. BoundingBoxRenderer.prototype.dispose = function () {
  24729. if (!this._colorShader) {
  24730. return;
  24731. }
  24732. this._colorShader.dispose();
  24733. this._vb.dispose();
  24734. this._scene.getEngine()._releaseBuffer(this._ib);
  24735. };
  24736. return BoundingBoxRenderer;
  24737. })();
  24738. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  24739. })(BABYLON || (BABYLON = {}));
  24740. var BABYLON;
  24741. (function (BABYLON) {
  24742. var Condition = (function () {
  24743. function Condition(actionManager) {
  24744. this._actionManager = actionManager;
  24745. }
  24746. Condition.prototype.isValid = function () {
  24747. return true;
  24748. };
  24749. Condition.prototype._getProperty = function (propertyPath) {
  24750. return this._actionManager._getProperty(propertyPath);
  24751. };
  24752. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24753. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24754. };
  24755. return Condition;
  24756. })();
  24757. BABYLON.Condition = Condition;
  24758. var ValueCondition = (function (_super) {
  24759. __extends(ValueCondition, _super);
  24760. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24761. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24762. _super.call(this, actionManager);
  24763. this.propertyPath = propertyPath;
  24764. this.value = value;
  24765. this.operator = operator;
  24766. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24767. this._property = this._getProperty(this.propertyPath);
  24768. }
  24769. Object.defineProperty(ValueCondition, "IsEqual", {
  24770. get: function () {
  24771. return ValueCondition._IsEqual;
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. Object.defineProperty(ValueCondition, "IsDifferent", {
  24777. get: function () {
  24778. return ValueCondition._IsDifferent;
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. Object.defineProperty(ValueCondition, "IsGreater", {
  24784. get: function () {
  24785. return ValueCondition._IsGreater;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. Object.defineProperty(ValueCondition, "IsLesser", {
  24791. get: function () {
  24792. return ValueCondition._IsLesser;
  24793. },
  24794. enumerable: true,
  24795. configurable: true
  24796. });
  24797. // Methods
  24798. ValueCondition.prototype.isValid = function () {
  24799. switch (this.operator) {
  24800. case ValueCondition.IsGreater:
  24801. return this._target[this._property] > this.value;
  24802. case ValueCondition.IsLesser:
  24803. return this._target[this._property] < this.value;
  24804. case ValueCondition.IsEqual:
  24805. case ValueCondition.IsDifferent:
  24806. var check;
  24807. if (this.value.equals) {
  24808. check = this.value.equals(this._target[this._property]);
  24809. }
  24810. else {
  24811. check = this.value === this._target[this._property];
  24812. }
  24813. return this.operator === ValueCondition.IsEqual ? check : !check;
  24814. }
  24815. return false;
  24816. };
  24817. // Statics
  24818. ValueCondition._IsEqual = 0;
  24819. ValueCondition._IsDifferent = 1;
  24820. ValueCondition._IsGreater = 2;
  24821. ValueCondition._IsLesser = 3;
  24822. return ValueCondition;
  24823. })(Condition);
  24824. BABYLON.ValueCondition = ValueCondition;
  24825. var PredicateCondition = (function (_super) {
  24826. __extends(PredicateCondition, _super);
  24827. function PredicateCondition(actionManager, predicate) {
  24828. _super.call(this, actionManager);
  24829. this.predicate = predicate;
  24830. }
  24831. PredicateCondition.prototype.isValid = function () {
  24832. return this.predicate();
  24833. };
  24834. return PredicateCondition;
  24835. })(Condition);
  24836. BABYLON.PredicateCondition = PredicateCondition;
  24837. var StateCondition = (function (_super) {
  24838. __extends(StateCondition, _super);
  24839. function StateCondition(actionManager, target, value) {
  24840. _super.call(this, actionManager);
  24841. this.value = value;
  24842. this._target = target;
  24843. }
  24844. // Methods
  24845. StateCondition.prototype.isValid = function () {
  24846. return this._target.state === this.value;
  24847. };
  24848. return StateCondition;
  24849. })(Condition);
  24850. BABYLON.StateCondition = StateCondition;
  24851. })(BABYLON || (BABYLON = {}));
  24852. var BABYLON;
  24853. (function (BABYLON) {
  24854. var Action = (function () {
  24855. function Action(triggerOptions, condition) {
  24856. this.triggerOptions = triggerOptions;
  24857. if (triggerOptions.parameter) {
  24858. this.trigger = triggerOptions.trigger;
  24859. this._triggerParameter = triggerOptions.parameter;
  24860. }
  24861. else {
  24862. this.trigger = triggerOptions;
  24863. }
  24864. this._nextActiveAction = this;
  24865. this._condition = condition;
  24866. }
  24867. // Methods
  24868. Action.prototype._prepare = function () {
  24869. };
  24870. Action.prototype.getTriggerParameter = function () {
  24871. return this._triggerParameter;
  24872. };
  24873. Action.prototype._executeCurrent = function (evt) {
  24874. if (this._nextActiveAction._condition) {
  24875. var condition = this._nextActiveAction._condition;
  24876. var currentRenderId = this._actionManager.getScene().getRenderId();
  24877. // We cache the current evaluation for the current frame
  24878. if (condition._evaluationId === currentRenderId) {
  24879. if (!condition._currentResult) {
  24880. return;
  24881. }
  24882. }
  24883. else {
  24884. condition._evaluationId = currentRenderId;
  24885. if (!condition.isValid()) {
  24886. condition._currentResult = false;
  24887. return;
  24888. }
  24889. condition._currentResult = true;
  24890. }
  24891. }
  24892. this._nextActiveAction.execute(evt);
  24893. if (this._nextActiveAction._child) {
  24894. if (!this._nextActiveAction._child._actionManager) {
  24895. this._nextActiveAction._child._actionManager = this._actionManager;
  24896. }
  24897. this._nextActiveAction = this._nextActiveAction._child;
  24898. }
  24899. else {
  24900. this._nextActiveAction = this;
  24901. }
  24902. };
  24903. Action.prototype.execute = function (evt) {
  24904. };
  24905. Action.prototype.then = function (action) {
  24906. this._child = action;
  24907. action._actionManager = this._actionManager;
  24908. action._prepare();
  24909. return action;
  24910. };
  24911. Action.prototype._getProperty = function (propertyPath) {
  24912. return this._actionManager._getProperty(propertyPath);
  24913. };
  24914. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24915. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24916. };
  24917. return Action;
  24918. })();
  24919. BABYLON.Action = Action;
  24920. })(BABYLON || (BABYLON = {}));
  24921. var BABYLON;
  24922. (function (BABYLON) {
  24923. /**
  24924. * ActionEvent is the event beint sent when an action is triggered.
  24925. */
  24926. var ActionEvent = (function () {
  24927. /**
  24928. * @constructor
  24929. * @param source The mesh or sprite that triggered the action.
  24930. * @param pointerX The X mouse cursor position at the time of the event
  24931. * @param pointerY The Y mouse cursor position at the time of the event
  24932. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24933. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24934. */
  24935. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  24936. this.source = source;
  24937. this.pointerX = pointerX;
  24938. this.pointerY = pointerY;
  24939. this.meshUnderPointer = meshUnderPointer;
  24940. this.sourceEvent = sourceEvent;
  24941. this.additionalData = additionalData;
  24942. }
  24943. /**
  24944. * Helper function to auto-create an ActionEvent from a source mesh.
  24945. * @param source The source mesh that triggered the event
  24946. * @param evt {Event} The original (browser) event
  24947. */
  24948. ActionEvent.CreateNew = function (source, evt, additionalData) {
  24949. var scene = source.getScene();
  24950. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24951. };
  24952. /**
  24953. * Helper function to auto-create an ActionEvent from a source mesh.
  24954. * @param source The source sprite that triggered the event
  24955. * @param scene Scene associated with the sprite
  24956. * @param evt {Event} The original (browser) event
  24957. */
  24958. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  24959. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24960. };
  24961. /**
  24962. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24963. * @param scene the scene where the event occurred
  24964. * @param evt {Event} The original (browser) event
  24965. */
  24966. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24967. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24968. };
  24969. return ActionEvent;
  24970. })();
  24971. BABYLON.ActionEvent = ActionEvent;
  24972. /**
  24973. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24974. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24975. */
  24976. var ActionManager = (function () {
  24977. function ActionManager(scene) {
  24978. // Members
  24979. this.actions = new Array();
  24980. this._scene = scene;
  24981. scene._actionManagers.push(this);
  24982. }
  24983. Object.defineProperty(ActionManager, "NothingTrigger", {
  24984. get: function () {
  24985. return ActionManager._NothingTrigger;
  24986. },
  24987. enumerable: true,
  24988. configurable: true
  24989. });
  24990. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24991. get: function () {
  24992. return ActionManager._OnPickTrigger;
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24998. get: function () {
  24999. return ActionManager._OnLeftPickTrigger;
  25000. },
  25001. enumerable: true,
  25002. configurable: true
  25003. });
  25004. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25005. get: function () {
  25006. return ActionManager._OnRightPickTrigger;
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25012. get: function () {
  25013. return ActionManager._OnCenterPickTrigger;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25019. get: function () {
  25020. return ActionManager._OnPointerOverTrigger;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25026. get: function () {
  25027. return ActionManager._OnPointerOutTrigger;
  25028. },
  25029. enumerable: true,
  25030. configurable: true
  25031. });
  25032. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25033. get: function () {
  25034. return ActionManager._OnEveryFrameTrigger;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25040. get: function () {
  25041. return ActionManager._OnIntersectionEnterTrigger;
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25047. get: function () {
  25048. return ActionManager._OnIntersectionExitTrigger;
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25054. get: function () {
  25055. return ActionManager._OnKeyDownTrigger;
  25056. },
  25057. enumerable: true,
  25058. configurable: true
  25059. });
  25060. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25061. get: function () {
  25062. return ActionManager._OnKeyUpTrigger;
  25063. },
  25064. enumerable: true,
  25065. configurable: true
  25066. });
  25067. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25068. get: function () {
  25069. return ActionManager._OnPickUpTrigger;
  25070. },
  25071. enumerable: true,
  25072. configurable: true
  25073. });
  25074. // Methods
  25075. ActionManager.prototype.dispose = function () {
  25076. var index = this._scene._actionManagers.indexOf(this);
  25077. if (index > -1) {
  25078. this._scene._actionManagers.splice(index, 1);
  25079. }
  25080. };
  25081. ActionManager.prototype.getScene = function () {
  25082. return this._scene;
  25083. };
  25084. /**
  25085. * Does this action manager handles actions of any of the given triggers
  25086. * @param {number[]} triggers - the triggers to be tested
  25087. * @return {boolean} whether one (or more) of the triggers is handeled
  25088. */
  25089. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25090. for (var index = 0; index < this.actions.length; index++) {
  25091. var action = this.actions[index];
  25092. if (triggers.indexOf(action.trigger) > -1) {
  25093. return true;
  25094. }
  25095. }
  25096. return false;
  25097. };
  25098. /**
  25099. * Does this action manager handles actions of a given trigger
  25100. * @param {number} trigger - the trigger to be tested
  25101. * @return {boolean} whether the trigger is handeled
  25102. */
  25103. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25104. for (var index = 0; index < this.actions.length; index++) {
  25105. var action = this.actions[index];
  25106. if (action.trigger === trigger) {
  25107. return true;
  25108. }
  25109. }
  25110. return false;
  25111. };
  25112. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25113. /**
  25114. * Does this action manager has pointer triggers
  25115. * @return {boolean} whether or not it has pointer triggers
  25116. */
  25117. get: function () {
  25118. for (var index = 0; index < this.actions.length; index++) {
  25119. var action = this.actions[index];
  25120. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25121. return true;
  25122. }
  25123. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25124. return true;
  25125. }
  25126. }
  25127. return false;
  25128. },
  25129. enumerable: true,
  25130. configurable: true
  25131. });
  25132. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25133. /**
  25134. * Does this action manager has pick triggers
  25135. * @return {boolean} whether or not it has pick triggers
  25136. */
  25137. get: function () {
  25138. for (var index = 0; index < this.actions.length; index++) {
  25139. var action = this.actions[index];
  25140. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25141. return true;
  25142. }
  25143. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25144. return true;
  25145. }
  25146. }
  25147. return false;
  25148. },
  25149. enumerable: true,
  25150. configurable: true
  25151. });
  25152. /**
  25153. * Registers an action to this action manager
  25154. * @param {BABYLON.Action} action - the action to be registered
  25155. * @return {BABYLON.Action} the action amended (prepared) after registration
  25156. */
  25157. ActionManager.prototype.registerAction = function (action) {
  25158. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25159. if (this.getScene().actionManager !== this) {
  25160. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25161. return null;
  25162. }
  25163. }
  25164. this.actions.push(action);
  25165. action._actionManager = this;
  25166. action._prepare();
  25167. return action;
  25168. };
  25169. /**
  25170. * Process a specific trigger
  25171. * @param {number} trigger - the trigger to process
  25172. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25173. */
  25174. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25175. for (var index = 0; index < this.actions.length; index++) {
  25176. var action = this.actions[index];
  25177. if (action.trigger === trigger) {
  25178. if (trigger === ActionManager.OnKeyUpTrigger
  25179. || trigger === ActionManager.OnKeyDownTrigger) {
  25180. var parameter = action.getTriggerParameter();
  25181. if (parameter) {
  25182. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25183. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25184. if (actualkey !== parameter.toLowerCase()) {
  25185. continue;
  25186. }
  25187. }
  25188. }
  25189. action._executeCurrent(evt);
  25190. }
  25191. }
  25192. };
  25193. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25194. var properties = propertyPath.split(".");
  25195. for (var index = 0; index < properties.length - 1; index++) {
  25196. target = target[properties[index]];
  25197. }
  25198. return target;
  25199. };
  25200. ActionManager.prototype._getProperty = function (propertyPath) {
  25201. var properties = propertyPath.split(".");
  25202. return properties[properties.length - 1];
  25203. };
  25204. // Statics
  25205. ActionManager._NothingTrigger = 0;
  25206. ActionManager._OnPickTrigger = 1;
  25207. ActionManager._OnLeftPickTrigger = 2;
  25208. ActionManager._OnRightPickTrigger = 3;
  25209. ActionManager._OnCenterPickTrigger = 4;
  25210. ActionManager._OnPointerOverTrigger = 5;
  25211. ActionManager._OnPointerOutTrigger = 6;
  25212. ActionManager._OnEveryFrameTrigger = 7;
  25213. ActionManager._OnIntersectionEnterTrigger = 8;
  25214. ActionManager._OnIntersectionExitTrigger = 9;
  25215. ActionManager._OnKeyDownTrigger = 10;
  25216. ActionManager._OnKeyUpTrigger = 11;
  25217. ActionManager._OnPickUpTrigger = 12;
  25218. return ActionManager;
  25219. })();
  25220. BABYLON.ActionManager = ActionManager;
  25221. })(BABYLON || (BABYLON = {}));
  25222. var BABYLON;
  25223. (function (BABYLON) {
  25224. var InterpolateValueAction = (function (_super) {
  25225. __extends(InterpolateValueAction, _super);
  25226. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25227. if (duration === void 0) { duration = 1000; }
  25228. _super.call(this, triggerOptions, condition);
  25229. this.propertyPath = propertyPath;
  25230. this.value = value;
  25231. this.duration = duration;
  25232. this.stopOtherAnimations = stopOtherAnimations;
  25233. this.onInterpolationDone = onInterpolationDone;
  25234. this._target = target;
  25235. }
  25236. InterpolateValueAction.prototype._prepare = function () {
  25237. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25238. this._property = this._getProperty(this.propertyPath);
  25239. };
  25240. InterpolateValueAction.prototype.execute = function () {
  25241. var scene = this._actionManager.getScene();
  25242. var keys = [
  25243. {
  25244. frame: 0,
  25245. value: this._target[this._property]
  25246. }, {
  25247. frame: 100,
  25248. value: this.value
  25249. }
  25250. ];
  25251. var dataType;
  25252. if (typeof this.value === "number") {
  25253. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25254. }
  25255. else if (this.value instanceof BABYLON.Color3) {
  25256. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25257. }
  25258. else if (this.value instanceof BABYLON.Vector3) {
  25259. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25260. }
  25261. else if (this.value instanceof BABYLON.Matrix) {
  25262. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25263. }
  25264. else if (this.value instanceof BABYLON.Quaternion) {
  25265. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25266. }
  25267. else {
  25268. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25269. return;
  25270. }
  25271. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25272. animation.setKeys(keys);
  25273. if (this.stopOtherAnimations) {
  25274. scene.stopAnimation(this._target);
  25275. }
  25276. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25277. };
  25278. return InterpolateValueAction;
  25279. })(BABYLON.Action);
  25280. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25281. })(BABYLON || (BABYLON = {}));
  25282. var BABYLON;
  25283. (function (BABYLON) {
  25284. var SwitchBooleanAction = (function (_super) {
  25285. __extends(SwitchBooleanAction, _super);
  25286. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25287. _super.call(this, triggerOptions, condition);
  25288. this.propertyPath = propertyPath;
  25289. this._target = target;
  25290. }
  25291. SwitchBooleanAction.prototype._prepare = function () {
  25292. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25293. this._property = this._getProperty(this.propertyPath);
  25294. };
  25295. SwitchBooleanAction.prototype.execute = function () {
  25296. this._target[this._property] = !this._target[this._property];
  25297. };
  25298. return SwitchBooleanAction;
  25299. })(BABYLON.Action);
  25300. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25301. var SetStateAction = (function (_super) {
  25302. __extends(SetStateAction, _super);
  25303. function SetStateAction(triggerOptions, target, value, condition) {
  25304. _super.call(this, triggerOptions, condition);
  25305. this.value = value;
  25306. this._target = target;
  25307. }
  25308. SetStateAction.prototype.execute = function () {
  25309. this._target.state = this.value;
  25310. };
  25311. return SetStateAction;
  25312. })(BABYLON.Action);
  25313. BABYLON.SetStateAction = SetStateAction;
  25314. var SetValueAction = (function (_super) {
  25315. __extends(SetValueAction, _super);
  25316. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25317. _super.call(this, triggerOptions, condition);
  25318. this.propertyPath = propertyPath;
  25319. this.value = value;
  25320. this._target = target;
  25321. }
  25322. SetValueAction.prototype._prepare = function () {
  25323. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25324. this._property = this._getProperty(this.propertyPath);
  25325. };
  25326. SetValueAction.prototype.execute = function () {
  25327. this._target[this._property] = this.value;
  25328. };
  25329. return SetValueAction;
  25330. })(BABYLON.Action);
  25331. BABYLON.SetValueAction = SetValueAction;
  25332. var IncrementValueAction = (function (_super) {
  25333. __extends(IncrementValueAction, _super);
  25334. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25335. _super.call(this, triggerOptions, condition);
  25336. this.propertyPath = propertyPath;
  25337. this.value = value;
  25338. this._target = target;
  25339. }
  25340. IncrementValueAction.prototype._prepare = function () {
  25341. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25342. this._property = this._getProperty(this.propertyPath);
  25343. if (typeof this._target[this._property] !== "number") {
  25344. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25345. }
  25346. };
  25347. IncrementValueAction.prototype.execute = function () {
  25348. this._target[this._property] += this.value;
  25349. };
  25350. return IncrementValueAction;
  25351. })(BABYLON.Action);
  25352. BABYLON.IncrementValueAction = IncrementValueAction;
  25353. var PlayAnimationAction = (function (_super) {
  25354. __extends(PlayAnimationAction, _super);
  25355. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25356. _super.call(this, triggerOptions, condition);
  25357. this.from = from;
  25358. this.to = to;
  25359. this.loop = loop;
  25360. this._target = target;
  25361. }
  25362. PlayAnimationAction.prototype._prepare = function () {
  25363. };
  25364. PlayAnimationAction.prototype.execute = function () {
  25365. var scene = this._actionManager.getScene();
  25366. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25367. };
  25368. return PlayAnimationAction;
  25369. })(BABYLON.Action);
  25370. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25371. var StopAnimationAction = (function (_super) {
  25372. __extends(StopAnimationAction, _super);
  25373. function StopAnimationAction(triggerOptions, target, condition) {
  25374. _super.call(this, triggerOptions, condition);
  25375. this._target = target;
  25376. }
  25377. StopAnimationAction.prototype._prepare = function () {
  25378. };
  25379. StopAnimationAction.prototype.execute = function () {
  25380. var scene = this._actionManager.getScene();
  25381. scene.stopAnimation(this._target);
  25382. };
  25383. return StopAnimationAction;
  25384. })(BABYLON.Action);
  25385. BABYLON.StopAnimationAction = StopAnimationAction;
  25386. var DoNothingAction = (function (_super) {
  25387. __extends(DoNothingAction, _super);
  25388. function DoNothingAction(triggerOptions, condition) {
  25389. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25390. _super.call(this, triggerOptions, condition);
  25391. }
  25392. DoNothingAction.prototype.execute = function () {
  25393. };
  25394. return DoNothingAction;
  25395. })(BABYLON.Action);
  25396. BABYLON.DoNothingAction = DoNothingAction;
  25397. var CombineAction = (function (_super) {
  25398. __extends(CombineAction, _super);
  25399. function CombineAction(triggerOptions, children, condition) {
  25400. _super.call(this, triggerOptions, condition);
  25401. this.children = children;
  25402. }
  25403. CombineAction.prototype._prepare = function () {
  25404. for (var index = 0; index < this.children.length; index++) {
  25405. this.children[index]._actionManager = this._actionManager;
  25406. this.children[index]._prepare();
  25407. }
  25408. };
  25409. CombineAction.prototype.execute = function (evt) {
  25410. for (var index = 0; index < this.children.length; index++) {
  25411. this.children[index].execute(evt);
  25412. }
  25413. };
  25414. return CombineAction;
  25415. })(BABYLON.Action);
  25416. BABYLON.CombineAction = CombineAction;
  25417. var ExecuteCodeAction = (function (_super) {
  25418. __extends(ExecuteCodeAction, _super);
  25419. function ExecuteCodeAction(triggerOptions, func, condition) {
  25420. _super.call(this, triggerOptions, condition);
  25421. this.func = func;
  25422. }
  25423. ExecuteCodeAction.prototype.execute = function (evt) {
  25424. this.func(evt);
  25425. };
  25426. return ExecuteCodeAction;
  25427. })(BABYLON.Action);
  25428. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25429. var SetParentAction = (function (_super) {
  25430. __extends(SetParentAction, _super);
  25431. function SetParentAction(triggerOptions, target, parent, condition) {
  25432. _super.call(this, triggerOptions, condition);
  25433. this._target = target;
  25434. this._parent = parent;
  25435. }
  25436. SetParentAction.prototype._prepare = function () {
  25437. };
  25438. SetParentAction.prototype.execute = function () {
  25439. if (this._target.parent === this._parent) {
  25440. return;
  25441. }
  25442. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25443. invertParentWorldMatrix.invert();
  25444. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25445. this._target.parent = this._parent;
  25446. };
  25447. return SetParentAction;
  25448. })(BABYLON.Action);
  25449. BABYLON.SetParentAction = SetParentAction;
  25450. var PlaySoundAction = (function (_super) {
  25451. __extends(PlaySoundAction, _super);
  25452. function PlaySoundAction(triggerOptions, sound, condition) {
  25453. _super.call(this, triggerOptions, condition);
  25454. this._sound = sound;
  25455. }
  25456. PlaySoundAction.prototype._prepare = function () {
  25457. };
  25458. PlaySoundAction.prototype.execute = function () {
  25459. if (this._sound !== undefined)
  25460. this._sound.play();
  25461. };
  25462. return PlaySoundAction;
  25463. })(BABYLON.Action);
  25464. BABYLON.PlaySoundAction = PlaySoundAction;
  25465. var StopSoundAction = (function (_super) {
  25466. __extends(StopSoundAction, _super);
  25467. function StopSoundAction(triggerOptions, sound, condition) {
  25468. _super.call(this, triggerOptions, condition);
  25469. this._sound = sound;
  25470. }
  25471. StopSoundAction.prototype._prepare = function () {
  25472. };
  25473. StopSoundAction.prototype.execute = function () {
  25474. if (this._sound !== undefined)
  25475. this._sound.stop();
  25476. };
  25477. return StopSoundAction;
  25478. })(BABYLON.Action);
  25479. BABYLON.StopSoundAction = StopSoundAction;
  25480. })(BABYLON || (BABYLON = {}));
  25481. var BABYLON;
  25482. (function (BABYLON) {
  25483. var Geometry = (function () {
  25484. function Geometry(id, scene, vertexData, updatable, mesh) {
  25485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25486. this._totalVertices = 0;
  25487. this._isDisposed = false;
  25488. this.id = id;
  25489. this._engine = scene.getEngine();
  25490. this._meshes = [];
  25491. this._scene = scene;
  25492. //Init vertex buffer cache
  25493. this._vertexBuffers = {};
  25494. this._indices = [];
  25495. // vertexData
  25496. if (vertexData) {
  25497. this.setAllVerticesData(vertexData, updatable);
  25498. }
  25499. else {
  25500. this._totalVertices = 0;
  25501. this._indices = [];
  25502. }
  25503. // applyToMesh
  25504. if (mesh) {
  25505. this.applyToMesh(mesh);
  25506. mesh.computeWorldMatrix(true);
  25507. }
  25508. }
  25509. Object.defineProperty(Geometry.prototype, "extend", {
  25510. get: function () {
  25511. return this._extend;
  25512. },
  25513. enumerable: true,
  25514. configurable: true
  25515. });
  25516. Geometry.prototype.getScene = function () {
  25517. return this._scene;
  25518. };
  25519. Geometry.prototype.getEngine = function () {
  25520. return this._engine;
  25521. };
  25522. Geometry.prototype.isReady = function () {
  25523. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25524. };
  25525. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25526. vertexData.applyToGeometry(this, updatable);
  25527. this.notifyUpdate();
  25528. };
  25529. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25530. if (this._vertexBuffers[kind]) {
  25531. this._vertexBuffers[kind].dispose();
  25532. }
  25533. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25534. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25535. stride = this._vertexBuffers[kind].getStrideSize();
  25536. this._totalVertices = data.length / stride;
  25537. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25538. var meshes = this._meshes;
  25539. var numOfMeshes = meshes.length;
  25540. for (var index = 0; index < numOfMeshes; index++) {
  25541. var mesh = meshes[index];
  25542. mesh._resetPointsArrayCache();
  25543. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25544. mesh._createGlobalSubMesh();
  25545. mesh.computeWorldMatrix(true);
  25546. }
  25547. }
  25548. this.notifyUpdate(kind);
  25549. };
  25550. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25551. var vertexBuffer = this.getVertexBuffer(kind);
  25552. if (!vertexBuffer) {
  25553. return;
  25554. }
  25555. vertexBuffer.updateDirectly(data, offset);
  25556. this.notifyUpdate(kind);
  25557. };
  25558. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25559. var vertexBuffer = this.getVertexBuffer(kind);
  25560. if (!vertexBuffer) {
  25561. return;
  25562. }
  25563. vertexBuffer.update(data);
  25564. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25565. var stride = vertexBuffer.getStrideSize();
  25566. this._totalVertices = data.length / stride;
  25567. if (updateExtends) {
  25568. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25569. }
  25570. var meshes = this._meshes;
  25571. var numOfMeshes = meshes.length;
  25572. for (var index = 0; index < numOfMeshes; index++) {
  25573. var mesh = meshes[index];
  25574. mesh._resetPointsArrayCache();
  25575. if (updateExtends) {
  25576. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25577. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25578. var subMesh = mesh.subMeshes[subIndex];
  25579. subMesh.refreshBoundingInfo();
  25580. }
  25581. }
  25582. }
  25583. }
  25584. this.notifyUpdate(kind);
  25585. };
  25586. Geometry.prototype.getTotalVertices = function () {
  25587. if (!this.isReady()) {
  25588. return 0;
  25589. }
  25590. return this._totalVertices;
  25591. };
  25592. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25593. var vertexBuffer = this.getVertexBuffer(kind);
  25594. if (!vertexBuffer) {
  25595. return null;
  25596. }
  25597. var orig = vertexBuffer.getData();
  25598. if (!copyWhenShared || this._meshes.length === 1) {
  25599. return orig;
  25600. }
  25601. else {
  25602. var len = orig.length;
  25603. var copy = [];
  25604. for (var i = 0; i < len; i++) {
  25605. copy.push(orig[i]);
  25606. }
  25607. return copy;
  25608. }
  25609. };
  25610. Geometry.prototype.getVertexBuffer = function (kind) {
  25611. if (!this.isReady()) {
  25612. return null;
  25613. }
  25614. return this._vertexBuffers[kind];
  25615. };
  25616. Geometry.prototype.getVertexBuffers = function () {
  25617. if (!this.isReady()) {
  25618. return null;
  25619. }
  25620. return this._vertexBuffers;
  25621. };
  25622. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25623. if (!this._vertexBuffers) {
  25624. if (this._delayInfo) {
  25625. return this._delayInfo.indexOf(kind) !== -1;
  25626. }
  25627. return false;
  25628. }
  25629. return this._vertexBuffers[kind] !== undefined;
  25630. };
  25631. Geometry.prototype.getVerticesDataKinds = function () {
  25632. var result = [];
  25633. var kind;
  25634. if (!this._vertexBuffers && this._delayInfo) {
  25635. for (kind in this._delayInfo) {
  25636. result.push(kind);
  25637. }
  25638. }
  25639. else {
  25640. for (kind in this._vertexBuffers) {
  25641. result.push(kind);
  25642. }
  25643. }
  25644. return result;
  25645. };
  25646. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25647. if (this._indexBuffer) {
  25648. this._engine._releaseBuffer(this._indexBuffer);
  25649. }
  25650. this._indices = indices;
  25651. if (this._meshes.length !== 0 && this._indices) {
  25652. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25653. }
  25654. if (totalVertices !== undefined) {
  25655. this._totalVertices = totalVertices;
  25656. }
  25657. var meshes = this._meshes;
  25658. var numOfMeshes = meshes.length;
  25659. for (var index = 0; index < numOfMeshes; index++) {
  25660. meshes[index]._createGlobalSubMesh();
  25661. }
  25662. this.notifyUpdate();
  25663. };
  25664. Geometry.prototype.getTotalIndices = function () {
  25665. if (!this.isReady()) {
  25666. return 0;
  25667. }
  25668. return this._indices.length;
  25669. };
  25670. Geometry.prototype.getIndices = function (copyWhenShared) {
  25671. if (!this.isReady()) {
  25672. return null;
  25673. }
  25674. var orig = this._indices;
  25675. if (!copyWhenShared || this._meshes.length === 1) {
  25676. return orig;
  25677. }
  25678. else {
  25679. var len = orig.length;
  25680. var copy = [];
  25681. for (var i = 0; i < len; i++) {
  25682. copy.push(orig[i]);
  25683. }
  25684. return copy;
  25685. }
  25686. };
  25687. Geometry.prototype.getIndexBuffer = function () {
  25688. if (!this.isReady()) {
  25689. return null;
  25690. }
  25691. return this._indexBuffer;
  25692. };
  25693. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25694. var meshes = this._meshes;
  25695. var index = meshes.indexOf(mesh);
  25696. if (index === -1) {
  25697. return;
  25698. }
  25699. for (var kind in this._vertexBuffers) {
  25700. this._vertexBuffers[kind].dispose();
  25701. }
  25702. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25703. this._indexBuffer = null;
  25704. }
  25705. meshes.splice(index, 1);
  25706. mesh._geometry = null;
  25707. if (meshes.length === 0 && shouldDispose) {
  25708. this.dispose();
  25709. }
  25710. };
  25711. Geometry.prototype.applyToMesh = function (mesh) {
  25712. if (mesh._geometry === this) {
  25713. return;
  25714. }
  25715. var previousGeometry = mesh._geometry;
  25716. if (previousGeometry) {
  25717. previousGeometry.releaseForMesh(mesh);
  25718. }
  25719. var meshes = this._meshes;
  25720. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25721. mesh._geometry = this;
  25722. this._scene.pushGeometry(this);
  25723. meshes.push(mesh);
  25724. if (this.isReady()) {
  25725. this._applyToMesh(mesh);
  25726. }
  25727. else {
  25728. mesh._boundingInfo = this._boundingInfo;
  25729. }
  25730. };
  25731. Geometry.prototype._applyToMesh = function (mesh) {
  25732. var numOfMeshes = this._meshes.length;
  25733. // vertexBuffers
  25734. for (var kind in this._vertexBuffers) {
  25735. if (numOfMeshes === 1) {
  25736. this._vertexBuffers[kind].create();
  25737. }
  25738. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25739. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25740. mesh._resetPointsArrayCache();
  25741. if (!this._extend) {
  25742. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25743. }
  25744. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25745. mesh._createGlobalSubMesh();
  25746. //bounding info was just created again, world matrix should be applied again.
  25747. mesh._updateBoundingInfo();
  25748. }
  25749. }
  25750. // indexBuffer
  25751. if (numOfMeshes === 1 && this._indices) {
  25752. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25753. }
  25754. if (this._indexBuffer) {
  25755. this._indexBuffer.references = numOfMeshes;
  25756. }
  25757. };
  25758. Geometry.prototype.notifyUpdate = function (kind) {
  25759. if (this.onGeometryUpdated) {
  25760. this.onGeometryUpdated(this, kind);
  25761. }
  25762. };
  25763. Geometry.prototype.load = function (scene, onLoaded) {
  25764. var _this = this;
  25765. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25766. return;
  25767. }
  25768. if (this.isReady()) {
  25769. if (onLoaded) {
  25770. onLoaded();
  25771. }
  25772. return;
  25773. }
  25774. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25775. scene._addPendingData(this);
  25776. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25777. _this._delayLoadingFunction(JSON.parse(data), _this);
  25778. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25779. _this._delayInfo = [];
  25780. scene._removePendingData(_this);
  25781. var meshes = _this._meshes;
  25782. var numOfMeshes = meshes.length;
  25783. for (var index = 0; index < numOfMeshes; index++) {
  25784. _this._applyToMesh(meshes[index]);
  25785. }
  25786. if (onLoaded) {
  25787. onLoaded();
  25788. }
  25789. }, function () { }, scene.database);
  25790. };
  25791. Geometry.prototype.isDisposed = function () {
  25792. return this._isDisposed;
  25793. };
  25794. Geometry.prototype.dispose = function () {
  25795. var meshes = this._meshes;
  25796. var numOfMeshes = meshes.length;
  25797. var index;
  25798. for (index = 0; index < numOfMeshes; index++) {
  25799. this.releaseForMesh(meshes[index]);
  25800. }
  25801. this._meshes = [];
  25802. for (var kind in this._vertexBuffers) {
  25803. this._vertexBuffers[kind].dispose();
  25804. }
  25805. this._vertexBuffers = [];
  25806. this._totalVertices = 0;
  25807. if (this._indexBuffer) {
  25808. this._engine._releaseBuffer(this._indexBuffer);
  25809. }
  25810. this._indexBuffer = null;
  25811. this._indices = [];
  25812. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25813. this.delayLoadingFile = null;
  25814. this._delayLoadingFunction = null;
  25815. this._delayInfo = [];
  25816. this._boundingInfo = null;
  25817. this._scene.removeGeometry(this);
  25818. this._isDisposed = true;
  25819. };
  25820. Geometry.prototype.copy = function (id) {
  25821. var vertexData = new BABYLON.VertexData();
  25822. vertexData.indices = [];
  25823. var indices = this.getIndices();
  25824. for (var index = 0; index < indices.length; index++) {
  25825. vertexData.indices.push(indices[index]);
  25826. }
  25827. var updatable = false;
  25828. var stopChecking = false;
  25829. var kind;
  25830. for (kind in this._vertexBuffers) {
  25831. // using slice() to make a copy of the array and not just reference it
  25832. var data = this.getVerticesData(kind);
  25833. if (data instanceof Float32Array) {
  25834. vertexData.set(new Float32Array(data), kind);
  25835. }
  25836. else {
  25837. vertexData.set(data.slice(0), kind);
  25838. }
  25839. if (!stopChecking) {
  25840. updatable = this.getVertexBuffer(kind).isUpdatable();
  25841. stopChecking = !updatable;
  25842. }
  25843. }
  25844. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25845. geometry.delayLoadState = this.delayLoadState;
  25846. geometry.delayLoadingFile = this.delayLoadingFile;
  25847. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25848. for (kind in this._delayInfo) {
  25849. geometry._delayInfo = geometry._delayInfo || [];
  25850. geometry._delayInfo.push(kind);
  25851. }
  25852. // Bounding info
  25853. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25854. return geometry;
  25855. };
  25856. // Statics
  25857. Geometry.ExtractFromMesh = function (mesh, id) {
  25858. var geometry = mesh._geometry;
  25859. if (!geometry) {
  25860. return null;
  25861. }
  25862. return geometry.copy(id);
  25863. };
  25864. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25865. // be aware Math.random() could cause collisions
  25866. Geometry.RandomId = function () {
  25867. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25868. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25869. return v.toString(16);
  25870. });
  25871. };
  25872. return Geometry;
  25873. })();
  25874. BABYLON.Geometry = Geometry;
  25875. /////// Primitives //////////////////////////////////////////////
  25876. var Geometry;
  25877. (function (Geometry) {
  25878. var Primitives;
  25879. (function (Primitives) {
  25880. /// Abstract class
  25881. var _Primitive = (function (_super) {
  25882. __extends(_Primitive, _super);
  25883. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25884. this._beingRegenerated = true;
  25885. this._canBeRegenerated = canBeRegenerated;
  25886. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25887. this._beingRegenerated = false;
  25888. }
  25889. _Primitive.prototype.canBeRegenerated = function () {
  25890. return this._canBeRegenerated;
  25891. };
  25892. _Primitive.prototype.regenerate = function () {
  25893. if (!this._canBeRegenerated) {
  25894. return;
  25895. }
  25896. this._beingRegenerated = true;
  25897. this.setAllVerticesData(this._regenerateVertexData(), false);
  25898. this._beingRegenerated = false;
  25899. };
  25900. _Primitive.prototype.asNewGeometry = function (id) {
  25901. return _super.prototype.copy.call(this, id);
  25902. };
  25903. // overrides
  25904. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25905. if (!this._beingRegenerated) {
  25906. return;
  25907. }
  25908. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25909. };
  25910. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25911. if (!this._beingRegenerated) {
  25912. return;
  25913. }
  25914. _super.prototype.setVerticesData.call(this, kind, data, false);
  25915. };
  25916. // to override
  25917. // protected
  25918. _Primitive.prototype._regenerateVertexData = function () {
  25919. throw new Error("Abstract method");
  25920. };
  25921. _Primitive.prototype.copy = function (id) {
  25922. throw new Error("Must be overriden in sub-classes.");
  25923. };
  25924. return _Primitive;
  25925. })(Geometry);
  25926. Primitives._Primitive = _Primitive;
  25927. var Ribbon = (function (_super) {
  25928. __extends(Ribbon, _super);
  25929. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25930. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25931. this.pathArray = pathArray;
  25932. this.closeArray = closeArray;
  25933. this.closePath = closePath;
  25934. this.offset = offset;
  25935. this.side = side;
  25936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25937. }
  25938. Ribbon.prototype._regenerateVertexData = function () {
  25939. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  25940. };
  25941. Ribbon.prototype.copy = function (id) {
  25942. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25943. };
  25944. return Ribbon;
  25945. })(_Primitive);
  25946. Primitives.Ribbon = Ribbon;
  25947. var Box = (function (_super) {
  25948. __extends(Box, _super);
  25949. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25951. this.size = size;
  25952. this.side = side;
  25953. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25954. }
  25955. Box.prototype._regenerateVertexData = function () {
  25956. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  25957. };
  25958. Box.prototype.copy = function (id) {
  25959. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25960. };
  25961. return Box;
  25962. })(_Primitive);
  25963. Primitives.Box = Box;
  25964. var Sphere = (function (_super) {
  25965. __extends(Sphere, _super);
  25966. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25967. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25968. this.segments = segments;
  25969. this.diameter = diameter;
  25970. this.side = side;
  25971. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25972. }
  25973. Sphere.prototype._regenerateVertexData = function () {
  25974. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  25975. };
  25976. Sphere.prototype.copy = function (id) {
  25977. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25978. };
  25979. return Sphere;
  25980. })(_Primitive);
  25981. Primitives.Sphere = Sphere;
  25982. var Disc = (function (_super) {
  25983. __extends(Disc, _super);
  25984. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  25985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25986. this.radius = radius;
  25987. this.tessellation = tessellation;
  25988. this.side = side;
  25989. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25990. }
  25991. Disc.prototype._regenerateVertexData = function () {
  25992. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  25993. };
  25994. Disc.prototype.copy = function (id) {
  25995. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  25996. };
  25997. return Disc;
  25998. })(_Primitive);
  25999. Primitives.Disc = Disc;
  26000. var Cylinder = (function (_super) {
  26001. __extends(Cylinder, _super);
  26002. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26003. if (subdivisions === void 0) { subdivisions = 1; }
  26004. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26005. this.height = height;
  26006. this.diameterTop = diameterTop;
  26007. this.diameterBottom = diameterBottom;
  26008. this.tessellation = tessellation;
  26009. this.subdivisions = subdivisions;
  26010. this.side = side;
  26011. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26012. }
  26013. Cylinder.prototype._regenerateVertexData = function () {
  26014. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26015. };
  26016. Cylinder.prototype.copy = function (id) {
  26017. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26018. };
  26019. return Cylinder;
  26020. })(_Primitive);
  26021. Primitives.Cylinder = Cylinder;
  26022. var Torus = (function (_super) {
  26023. __extends(Torus, _super);
  26024. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26025. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26026. this.diameter = diameter;
  26027. this.thickness = thickness;
  26028. this.tessellation = tessellation;
  26029. this.side = side;
  26030. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26031. }
  26032. Torus.prototype._regenerateVertexData = function () {
  26033. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26034. };
  26035. Torus.prototype.copy = function (id) {
  26036. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26037. };
  26038. return Torus;
  26039. })(_Primitive);
  26040. Primitives.Torus = Torus;
  26041. var Ground = (function (_super) {
  26042. __extends(Ground, _super);
  26043. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26044. this.width = width;
  26045. this.height = height;
  26046. this.subdivisions = subdivisions;
  26047. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26048. }
  26049. Ground.prototype._regenerateVertexData = function () {
  26050. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26051. };
  26052. Ground.prototype.copy = function (id) {
  26053. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26054. };
  26055. return Ground;
  26056. })(_Primitive);
  26057. Primitives.Ground = Ground;
  26058. var TiledGround = (function (_super) {
  26059. __extends(TiledGround, _super);
  26060. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26061. this.xmin = xmin;
  26062. this.zmin = zmin;
  26063. this.xmax = xmax;
  26064. this.zmax = zmax;
  26065. this.subdivisions = subdivisions;
  26066. this.precision = precision;
  26067. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26068. }
  26069. TiledGround.prototype._regenerateVertexData = function () {
  26070. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26071. };
  26072. TiledGround.prototype.copy = function (id) {
  26073. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26074. };
  26075. return TiledGround;
  26076. })(_Primitive);
  26077. Primitives.TiledGround = TiledGround;
  26078. var Plane = (function (_super) {
  26079. __extends(Plane, _super);
  26080. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26082. this.size = size;
  26083. this.side = side;
  26084. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26085. }
  26086. Plane.prototype._regenerateVertexData = function () {
  26087. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26088. };
  26089. Plane.prototype.copy = function (id) {
  26090. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26091. };
  26092. return Plane;
  26093. })(_Primitive);
  26094. Primitives.Plane = Plane;
  26095. var TorusKnot = (function (_super) {
  26096. __extends(TorusKnot, _super);
  26097. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26099. this.radius = radius;
  26100. this.tube = tube;
  26101. this.radialSegments = radialSegments;
  26102. this.tubularSegments = tubularSegments;
  26103. this.p = p;
  26104. this.q = q;
  26105. this.side = side;
  26106. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26107. }
  26108. TorusKnot.prototype._regenerateVertexData = function () {
  26109. 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 });
  26110. };
  26111. TorusKnot.prototype.copy = function (id) {
  26112. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26113. };
  26114. return TorusKnot;
  26115. })(_Primitive);
  26116. Primitives.TorusKnot = TorusKnot;
  26117. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26118. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26119. })(BABYLON || (BABYLON = {}));
  26120. var BABYLON;
  26121. (function (BABYLON) {
  26122. var GroundMesh = (function (_super) {
  26123. __extends(GroundMesh, _super);
  26124. function GroundMesh(name, scene) {
  26125. _super.call(this, name, scene);
  26126. this.generateOctree = false;
  26127. this._worldInverse = new BABYLON.Matrix();
  26128. }
  26129. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26130. get: function () {
  26131. return this._subdivisions;
  26132. },
  26133. enumerable: true,
  26134. configurable: true
  26135. });
  26136. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26137. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26138. this._subdivisions = chunksCount;
  26139. this.subdivide(this._subdivisions);
  26140. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26141. };
  26142. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26143. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26144. this.getWorldMatrix().invertToRef(this._worldInverse);
  26145. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26146. var pickInfo = this.intersects(ray);
  26147. if (pickInfo.hit) {
  26148. return pickInfo.pickedPoint.y;
  26149. }
  26150. return 0;
  26151. };
  26152. return GroundMesh;
  26153. })(BABYLON.Mesh);
  26154. BABYLON.GroundMesh = GroundMesh;
  26155. })(BABYLON || (BABYLON = {}));
  26156. var BABYLON;
  26157. (function (BABYLON) {
  26158. var LinesMesh = (function (_super) {
  26159. __extends(LinesMesh, _super);
  26160. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26161. if (parent === void 0) { parent = null; }
  26162. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26163. this.color = new BABYLON.Color3(1, 1, 1);
  26164. this.alpha = 1;
  26165. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26166. attributes: ["position"],
  26167. uniforms: ["worldViewProjection", "color"],
  26168. needAlphaBlending: true
  26169. });
  26170. }
  26171. Object.defineProperty(LinesMesh.prototype, "material", {
  26172. get: function () {
  26173. return this._colorShader;
  26174. },
  26175. enumerable: true,
  26176. configurable: true
  26177. });
  26178. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26179. get: function () {
  26180. return false;
  26181. },
  26182. enumerable: true,
  26183. configurable: true
  26184. });
  26185. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26186. get: function () {
  26187. return false;
  26188. },
  26189. enumerable: true,
  26190. configurable: true
  26191. });
  26192. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26193. var engine = this.getScene().getEngine();
  26194. var indexToBind = this._geometry.getIndexBuffer();
  26195. // VBOs
  26196. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26197. // Color
  26198. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26199. };
  26200. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26201. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26202. return;
  26203. }
  26204. var engine = this.getScene().getEngine();
  26205. // Draw order
  26206. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26207. };
  26208. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26209. return null;
  26210. };
  26211. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26212. this._colorShader.dispose();
  26213. _super.prototype.dispose.call(this, doNotRecurse);
  26214. };
  26215. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26216. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26217. };
  26218. return LinesMesh;
  26219. })(BABYLON.Mesh);
  26220. BABYLON.LinesMesh = LinesMesh;
  26221. })(BABYLON || (BABYLON = {}));
  26222. var BABYLON;
  26223. (function (BABYLON) {
  26224. var DebugLayer = (function () {
  26225. function DebugLayer(scene) {
  26226. var _this = this;
  26227. this._transformationMatrix = BABYLON.Matrix.Identity();
  26228. this._enabled = false;
  26229. this._labelsEnabled = false;
  26230. this._displayStatistics = true;
  26231. this._displayTree = false;
  26232. this._displayLogs = false;
  26233. this._identityMatrix = BABYLON.Matrix.Identity();
  26234. this.axisRatio = 0.02;
  26235. this.accentColor = "orange";
  26236. this._scene = scene;
  26237. this._syncPositions = function () {
  26238. var engine = _this._scene.getEngine();
  26239. var canvasRect = engine.getRenderingCanvasClientRect();
  26240. if (_this._showUI) {
  26241. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26242. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26243. _this._statsDiv.style.width = "400px";
  26244. _this._statsDiv.style.height = "auto";
  26245. _this._statsSubsetDiv.style.maxHeight = "240px";
  26246. _this._optionsDiv.style.left = "0px";
  26247. _this._optionsDiv.style.top = "10px";
  26248. _this._optionsDiv.style.width = "200px";
  26249. _this._optionsDiv.style.height = "auto";
  26250. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26251. _this._logDiv.style.left = "0px";
  26252. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26253. _this._logDiv.style.width = "600px";
  26254. _this._logDiv.style.height = "160px";
  26255. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26256. _this._treeDiv.style.top = "10px";
  26257. _this._treeDiv.style.width = "300px";
  26258. _this._treeDiv.style.height = "auto";
  26259. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26260. }
  26261. _this._globalDiv.style.left = canvasRect.left + "px";
  26262. _this._globalDiv.style.top = canvasRect.top + "px";
  26263. _this._drawingCanvas.style.left = "0px";
  26264. _this._drawingCanvas.style.top = "0px";
  26265. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26266. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26267. var devicePixelRatio = window.devicePixelRatio || 1;
  26268. var context = _this._drawingContext;
  26269. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26270. context.mozBackingStorePixelRatio ||
  26271. context.msBackingStorePixelRatio ||
  26272. context.oBackingStorePixelRatio ||
  26273. context.backingStorePixelRatio || 1;
  26274. _this._ratio = devicePixelRatio / backingStoreRatio;
  26275. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26276. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26277. };
  26278. this._onCanvasClick = function (evt) {
  26279. _this._clickPosition = {
  26280. x: evt.clientX * _this._ratio,
  26281. y: evt.clientY * _this._ratio
  26282. };
  26283. };
  26284. this._syncUI = function () {
  26285. if (_this._showUI) {
  26286. if (_this._displayStatistics) {
  26287. _this._displayStats();
  26288. _this._statsDiv.style.display = "";
  26289. }
  26290. else {
  26291. _this._statsDiv.style.display = "none";
  26292. }
  26293. if (_this._displayLogs) {
  26294. _this._logDiv.style.display = "";
  26295. }
  26296. else {
  26297. _this._logDiv.style.display = "none";
  26298. }
  26299. if (_this._displayTree) {
  26300. _this._treeDiv.style.display = "";
  26301. if (_this._needToRefreshMeshesTree) {
  26302. _this._needToRefreshMeshesTree = false;
  26303. _this._refreshMeshesTreeContent();
  26304. }
  26305. }
  26306. else {
  26307. _this._treeDiv.style.display = "none";
  26308. }
  26309. }
  26310. };
  26311. this._syncData = function () {
  26312. if (_this._labelsEnabled || !_this._showUI) {
  26313. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26314. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26315. var engine = _this._scene.getEngine();
  26316. var viewport = _this._camera.viewport;
  26317. var globalViewport = viewport.toGlobal(engine);
  26318. // Meshes
  26319. var meshes = _this._camera.getActiveMeshes();
  26320. for (var index = 0; index < meshes.length; index++) {
  26321. var mesh = meshes.data[index];
  26322. var position = mesh.getBoundingInfo().boundingSphere.center;
  26323. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26324. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26325. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26326. }
  26327. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26328. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26329. }
  26330. }
  26331. // Cameras
  26332. var cameras = _this._scene.cameras;
  26333. for (index = 0; index < cameras.length; index++) {
  26334. var camera = cameras[index];
  26335. if (camera === _this._camera) {
  26336. continue;
  26337. }
  26338. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26339. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26340. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26341. _this._camera.detachControl(engine.getRenderingCanvas());
  26342. _this._camera = camera;
  26343. _this._camera.attachControl(engine.getRenderingCanvas());
  26344. }, function () { return "purple"; });
  26345. }
  26346. }
  26347. // Lights
  26348. var lights = _this._scene.lights;
  26349. for (index = 0; index < lights.length; index++) {
  26350. var light = lights[index];
  26351. if (light.position) {
  26352. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26353. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26354. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26355. light.setEnabled(!light.isEnabled());
  26356. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26357. }
  26358. }
  26359. }
  26360. }
  26361. _this._clickPosition = undefined;
  26362. };
  26363. }
  26364. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26365. while (this._treeSubsetDiv.hasChildNodes()) {
  26366. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26367. }
  26368. // Add meshes
  26369. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26370. sortedArray.sort(function (a, b) {
  26371. if (a.name === b.name) {
  26372. return 0;
  26373. }
  26374. return (a.name > b.name) ? 1 : -1;
  26375. });
  26376. for (var index = 0; index < sortedArray.length; index++) {
  26377. var mesh = sortedArray[index];
  26378. if (!mesh.isEnabled()) {
  26379. continue;
  26380. }
  26381. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26382. m.isVisible = element.checked;
  26383. }, mesh);
  26384. }
  26385. };
  26386. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26387. this._drawingContext.beginPath();
  26388. this._drawingContext.moveTo(zero.x, zero.y);
  26389. this._drawingContext.lineTo(unit.x, unit.y);
  26390. this._drawingContext.strokeStyle = color;
  26391. this._drawingContext.lineWidth = 4;
  26392. this._drawingContext.stroke();
  26393. this._drawingContext.font = "normal 14px Segoe UI";
  26394. this._drawingContext.fillStyle = color;
  26395. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26396. };
  26397. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26398. var position = mesh.getBoundingInfo().boundingSphere.center;
  26399. var worldMatrix = mesh.getWorldMatrix();
  26400. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26401. var unit = (unprojectedVector.subtract(position)).length();
  26402. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26403. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26404. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26405. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26406. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26407. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26408. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26409. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26410. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26411. };
  26412. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26413. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26414. this._drawingContext.font = "normal 12px Segoe UI";
  26415. var textMetrics = this._drawingContext.measureText(text);
  26416. var centerX = projectedPosition.x - textMetrics.width / 2;
  26417. var centerY = projectedPosition.y;
  26418. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26419. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26420. onClick();
  26421. }
  26422. this._drawingContext.beginPath();
  26423. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26424. this._drawingContext.fillStyle = getFillStyle();
  26425. this._drawingContext.globalAlpha = 0.5;
  26426. this._drawingContext.fill();
  26427. this._drawingContext.globalAlpha = 1.0;
  26428. this._drawingContext.strokeStyle = '#FFFFFF';
  26429. this._drawingContext.lineWidth = 1;
  26430. this._drawingContext.stroke();
  26431. this._drawingContext.fillStyle = "#FFFFFF";
  26432. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26433. this._drawingContext.beginPath();
  26434. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26435. this._drawingContext.fill();
  26436. }
  26437. };
  26438. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26439. if (!this._clickPosition) {
  26440. return false;
  26441. }
  26442. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26443. return false;
  26444. }
  26445. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26446. return false;
  26447. }
  26448. return true;
  26449. };
  26450. DebugLayer.prototype.isVisible = function () {
  26451. return this._enabled;
  26452. };
  26453. DebugLayer.prototype.hide = function () {
  26454. if (!this._enabled) {
  26455. return;
  26456. }
  26457. this._enabled = false;
  26458. var engine = this._scene.getEngine();
  26459. this._scene.unregisterBeforeRender(this._syncData);
  26460. this._scene.unregisterAfterRender(this._syncUI);
  26461. this._rootElement.removeChild(this._globalDiv);
  26462. this._scene.forceShowBoundingBoxes = false;
  26463. this._scene.forceWireframe = false;
  26464. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26465. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26466. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26467. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26468. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26469. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26470. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26471. BABYLON.StandardMaterial.LightmapEnabled = true;
  26472. this._scene.shadowsEnabled = true;
  26473. this._scene.particlesEnabled = true;
  26474. this._scene.postProcessesEnabled = true;
  26475. this._scene.collisionsEnabled = true;
  26476. this._scene.lightsEnabled = true;
  26477. this._scene.texturesEnabled = true;
  26478. this._scene.lensFlaresEnabled = true;
  26479. this._scene.proceduralTexturesEnabled = true;
  26480. this._scene.renderTargetsEnabled = true;
  26481. this._scene.probesEnabled = true;
  26482. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26483. };
  26484. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26485. if (showUI === void 0) { showUI = true; }
  26486. if (camera === void 0) { camera = null; }
  26487. if (rootElement === void 0) { rootElement = null; }
  26488. if (this._enabled) {
  26489. return;
  26490. }
  26491. this._enabled = true;
  26492. if (camera) {
  26493. this._camera = camera;
  26494. }
  26495. else {
  26496. this._camera = this._scene.activeCamera;
  26497. }
  26498. this._showUI = showUI;
  26499. var engine = this._scene.getEngine();
  26500. this._globalDiv = document.createElement("div");
  26501. this._rootElement = rootElement || document.body;
  26502. this._rootElement.appendChild(this._globalDiv);
  26503. this._generateDOMelements();
  26504. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26505. this._syncPositions();
  26506. this._scene.registerBeforeRender(this._syncData);
  26507. this._scene.registerAfterRender(this._syncUI);
  26508. };
  26509. DebugLayer.prototype._clearLabels = function () {
  26510. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26511. for (var index = 0; index < this._scene.meshes.length; index++) {
  26512. var mesh = this._scene.meshes[index];
  26513. mesh.renderOverlay = false;
  26514. }
  26515. };
  26516. DebugLayer.prototype._generateheader = function (root, text) {
  26517. var header = document.createElement("div");
  26518. header.innerHTML = text + "&nbsp;";
  26519. header.style.textAlign = "right";
  26520. header.style.width = "100%";
  26521. header.style.color = "white";
  26522. header.style.backgroundColor = "Black";
  26523. header.style.padding = "5px 5px 4px 0px";
  26524. header.style.marginLeft = "-5px";
  26525. header.style.fontWeight = "bold";
  26526. root.appendChild(header);
  26527. };
  26528. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26529. var label = document.createElement("label");
  26530. label.innerHTML = title;
  26531. label.style.color = color;
  26532. root.appendChild(label);
  26533. root.appendChild(document.createElement("br"));
  26534. };
  26535. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26536. if (tag === void 0) { tag = null; }
  26537. var label = document.createElement("label");
  26538. var boundingBoxesCheckbox = document.createElement("input");
  26539. boundingBoxesCheckbox.type = "checkbox";
  26540. boundingBoxesCheckbox.checked = initialState;
  26541. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26542. task(evt.target, tag);
  26543. });
  26544. label.appendChild(boundingBoxesCheckbox);
  26545. var container = document.createElement("span");
  26546. var leftPart = document.createElement("span");
  26547. var rightPart = document.createElement("span");
  26548. rightPart.style.cssFloat = "right";
  26549. leftPart.innerHTML = leftTitle;
  26550. rightPart.innerHTML = rightTitle;
  26551. rightPart.style.fontSize = "12px";
  26552. rightPart.style.maxWidth = "200px";
  26553. container.appendChild(leftPart);
  26554. container.appendChild(rightPart);
  26555. label.appendChild(container);
  26556. root.appendChild(label);
  26557. root.appendChild(document.createElement("br"));
  26558. };
  26559. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26560. if (tag === void 0) { tag = null; }
  26561. var label = document.createElement("label");
  26562. var checkBox = document.createElement("input");
  26563. checkBox.type = "checkbox";
  26564. checkBox.checked = initialState;
  26565. checkBox.addEventListener("change", function (evt) {
  26566. task(evt.target, tag);
  26567. });
  26568. label.appendChild(checkBox);
  26569. label.appendChild(document.createTextNode(title));
  26570. root.appendChild(label);
  26571. root.appendChild(document.createElement("br"));
  26572. };
  26573. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26574. if (tag === void 0) { tag = null; }
  26575. var button = document.createElement("button");
  26576. button.innerHTML = title;
  26577. button.style.height = "24px";
  26578. button.style.color = "#444444";
  26579. button.style.border = "1px solid white";
  26580. button.className = "debugLayerButton";
  26581. button.addEventListener("click", function (evt) {
  26582. task(evt.target, tag);
  26583. });
  26584. root.appendChild(button);
  26585. root.appendChild(document.createElement("br"));
  26586. };
  26587. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26588. if (tag === void 0) { tag = null; }
  26589. var label = document.createElement("label");
  26590. var boundingBoxesRadio = document.createElement("input");
  26591. boundingBoxesRadio.type = "radio";
  26592. boundingBoxesRadio.name = name;
  26593. boundingBoxesRadio.checked = initialState;
  26594. boundingBoxesRadio.addEventListener("change", function (evt) {
  26595. task(evt.target, tag);
  26596. });
  26597. label.appendChild(boundingBoxesRadio);
  26598. label.appendChild(document.createTextNode(title));
  26599. root.appendChild(label);
  26600. root.appendChild(document.createElement("br"));
  26601. };
  26602. DebugLayer.prototype._generateDOMelements = function () {
  26603. var _this = this;
  26604. this._globalDiv.id = "DebugLayer";
  26605. this._globalDiv.style.position = "absolute";
  26606. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26607. this._globalDiv.style.fontSize = "14px";
  26608. this._globalDiv.style.color = "white";
  26609. // Drawing canvas
  26610. this._drawingCanvas = document.createElement("canvas");
  26611. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26612. this._drawingCanvas.style.position = "absolute";
  26613. this._drawingCanvas.style.pointerEvents = "none";
  26614. this._drawingCanvas.style.backgroundColor = "transparent";
  26615. this._drawingContext = this._drawingCanvas.getContext("2d");
  26616. this._globalDiv.appendChild(this._drawingCanvas);
  26617. if (this._showUI) {
  26618. var background = "rgba(128, 128, 128, 0.4)";
  26619. var border = "rgb(180, 180, 180) solid 1px";
  26620. // Stats
  26621. this._statsDiv = document.createElement("div");
  26622. this._statsDiv.id = "DebugLayerStats";
  26623. this._statsDiv.style.border = border;
  26624. this._statsDiv.style.position = "absolute";
  26625. this._statsDiv.style.background = background;
  26626. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26627. this._generateheader(this._statsDiv, "STATISTICS");
  26628. this._statsSubsetDiv = document.createElement("div");
  26629. this._statsSubsetDiv.style.paddingTop = "5px";
  26630. this._statsSubsetDiv.style.paddingBottom = "5px";
  26631. this._statsSubsetDiv.style.overflowY = "auto";
  26632. this._statsDiv.appendChild(this._statsSubsetDiv);
  26633. // Tree
  26634. this._treeDiv = document.createElement("div");
  26635. this._treeDiv.id = "DebugLayerTree";
  26636. this._treeDiv.style.border = border;
  26637. this._treeDiv.style.position = "absolute";
  26638. this._treeDiv.style.background = background;
  26639. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26640. this._treeDiv.style.display = "none";
  26641. this._generateheader(this._treeDiv, "MESHES TREE");
  26642. this._treeSubsetDiv = document.createElement("div");
  26643. this._treeSubsetDiv.style.paddingTop = "5px";
  26644. this._treeSubsetDiv.style.paddingRight = "5px";
  26645. this._treeSubsetDiv.style.overflowY = "auto";
  26646. this._treeSubsetDiv.style.maxHeight = "300px";
  26647. this._treeDiv.appendChild(this._treeSubsetDiv);
  26648. this._needToRefreshMeshesTree = true;
  26649. // Logs
  26650. this._logDiv = document.createElement("div");
  26651. this._logDiv.style.border = border;
  26652. this._logDiv.id = "DebugLayerLogs";
  26653. this._logDiv.style.position = "absolute";
  26654. this._logDiv.style.background = background;
  26655. this._logDiv.style.padding = "0px 0px 0px 5px";
  26656. this._logDiv.style.display = "none";
  26657. this._generateheader(this._logDiv, "LOGS");
  26658. this._logSubsetDiv = document.createElement("div");
  26659. this._logSubsetDiv.style.height = "127px";
  26660. this._logSubsetDiv.style.paddingTop = "5px";
  26661. this._logSubsetDiv.style.overflowY = "auto";
  26662. this._logSubsetDiv.style.fontSize = "12px";
  26663. this._logSubsetDiv.style.fontFamily = "consolas";
  26664. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26665. this._logDiv.appendChild(this._logSubsetDiv);
  26666. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26667. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26668. };
  26669. // Options
  26670. this._optionsDiv = document.createElement("div");
  26671. this._optionsDiv.id = "DebugLayerOptions";
  26672. this._optionsDiv.style.border = border;
  26673. this._optionsDiv.style.position = "absolute";
  26674. this._optionsDiv.style.background = background;
  26675. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26676. this._optionsDiv.style.overflowY = "auto";
  26677. this._generateheader(this._optionsDiv, "OPTIONS");
  26678. this._optionsSubsetDiv = document.createElement("div");
  26679. this._optionsSubsetDiv.style.paddingTop = "5px";
  26680. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26681. this._optionsSubsetDiv.style.overflowY = "auto";
  26682. this._optionsSubsetDiv.style.maxHeight = "200px";
  26683. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26684. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26685. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  26686. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  26687. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26688. _this._displayTree = element.checked;
  26689. _this._needToRefreshMeshesTree = true;
  26690. });
  26691. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26692. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26693. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  26694. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26695. _this._labelsEnabled = element.checked;
  26696. if (!_this._labelsEnabled) {
  26697. _this._clearLabels();
  26698. }
  26699. });
  26700. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26701. if (element.checked) {
  26702. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26703. }
  26704. else {
  26705. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26706. }
  26707. });
  26708. ;
  26709. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26710. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26711. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26712. if (element.checked) {
  26713. _this._scene.forceWireframe = false;
  26714. _this._scene.forcePointsCloud = false;
  26715. }
  26716. });
  26717. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26718. if (element.checked) {
  26719. _this._scene.forceWireframe = true;
  26720. _this._scene.forcePointsCloud = false;
  26721. }
  26722. });
  26723. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26724. if (element.checked) {
  26725. _this._scene.forceWireframe = false;
  26726. _this._scene.forcePointsCloud = true;
  26727. }
  26728. });
  26729. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26730. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26731. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  26732. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  26733. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  26734. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  26735. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  26736. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  26737. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  26738. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  26739. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  26740. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26741. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26742. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  26743. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  26744. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  26745. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  26746. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  26747. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  26748. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  26749. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  26750. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  26751. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  26752. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  26753. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  26754. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  26755. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  26756. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  26757. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26758. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  26759. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  26760. if (element.checked) {
  26761. _this._scene.headphone = true;
  26762. }
  26763. });
  26764. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  26765. if (element.checked) {
  26766. _this._scene.headphone = false;
  26767. }
  26768. });
  26769. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  26770. _this._scene.audioEnabled = !element.checked;
  26771. });
  26772. }
  26773. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26774. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  26775. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  26776. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26777. this._globalDiv.appendChild(this._statsDiv);
  26778. this._globalDiv.appendChild(this._logDiv);
  26779. this._globalDiv.appendChild(this._optionsDiv);
  26780. this._globalDiv.appendChild(this._treeDiv);
  26781. }
  26782. };
  26783. DebugLayer.prototype._displayStats = function () {
  26784. var scene = this._scene;
  26785. var engine = scene.getEngine();
  26786. var glInfo = engine.getGlInfo();
  26787. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  26788. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26789. + "<b>Count</b><br>"
  26790. + "Total meshes: " + scene.meshes.length + "<br>"
  26791. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  26792. + "Total materials: " + scene.materials.length + "<br>"
  26793. + "Total textures: " + scene.textures.length + "<br>"
  26794. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  26795. + "Active indices: " + scene.getActiveIndices() + "<br>"
  26796. + "Active bones: " + scene.getActiveBones() + "<br>"
  26797. + "Active particles: " + scene.getActiveParticles() + "<br>"
  26798. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  26799. + "<b>Duration</b><br>"
  26800. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  26801. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  26802. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  26803. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  26804. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  26805. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  26806. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  26807. + "</div>"
  26808. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26809. + "<b>Extensions</b><br>"
  26810. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  26811. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  26812. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  26813. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  26814. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  26815. + "<b>Caps.</b><br>"
  26816. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  26817. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  26818. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  26819. + "</div><br>"
  26820. + "<b>Info</b><br>"
  26821. + glInfo.version + "<br>"
  26822. + glInfo.renderer + "<br>";
  26823. if (this.customStatsFunction) {
  26824. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26825. }
  26826. };
  26827. return DebugLayer;
  26828. })();
  26829. BABYLON.DebugLayer = DebugLayer;
  26830. })(BABYLON || (BABYLON = {}));
  26831. var BABYLON;
  26832. (function (BABYLON) {
  26833. var DefaultLoadingScreen = (function () {
  26834. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  26835. var _this = this;
  26836. if (_loadingText === void 0) { _loadingText = ""; }
  26837. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  26838. this._renderingCanvas = _renderingCanvas;
  26839. this._loadingText = _loadingText;
  26840. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  26841. // Resize
  26842. this._resizeLoadingUI = function () {
  26843. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  26844. _this._loadingDiv.style.position = "absolute";
  26845. _this._loadingDiv.style.left = canvasRect.left + "px";
  26846. _this._loadingDiv.style.top = canvasRect.top + "px";
  26847. _this._loadingDiv.style.width = canvasRect.width + "px";
  26848. _this._loadingDiv.style.height = canvasRect.height + "px";
  26849. };
  26850. }
  26851. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  26852. var _this = this;
  26853. this._loadingDiv = document.createElement("div");
  26854. this._loadingDiv.style.opacity = "0";
  26855. this._loadingDiv.style.transition = "opacity 1.5s ease";
  26856. // Loading text
  26857. this._loadingTextDiv = document.createElement("div");
  26858. this._loadingTextDiv.style.position = "absolute";
  26859. this._loadingTextDiv.style.left = "0";
  26860. this._loadingTextDiv.style.top = "50%";
  26861. this._loadingTextDiv.style.marginTop = "80px";
  26862. this._loadingTextDiv.style.width = "100%";
  26863. this._loadingTextDiv.style.height = "20px";
  26864. this._loadingTextDiv.style.fontFamily = "Arial";
  26865. this._loadingTextDiv.style.fontSize = "14px";
  26866. this._loadingTextDiv.style.color = "white";
  26867. this._loadingTextDiv.style.textAlign = "center";
  26868. this._loadingTextDiv.innerHTML = "Loading";
  26869. this._loadingDiv.appendChild(this._loadingTextDiv);
  26870. //set the predefined text
  26871. this._loadingTextDiv.innerHTML = this._loadingText;
  26872. // Loading img
  26873. var imgBack = new Image();
  26874. 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==";
  26875. imgBack.style.position = "absolute";
  26876. imgBack.style.left = "50%";
  26877. imgBack.style.top = "50%";
  26878. imgBack.style.marginLeft = "-50px";
  26879. imgBack.style.marginTop = "-50px";
  26880. imgBack.style.transition = "transform 1.0s ease";
  26881. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  26882. var deg = 360;
  26883. var onTransitionEnd = function () {
  26884. deg += 360;
  26885. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  26886. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  26887. };
  26888. imgBack.addEventListener("transitionend", onTransitionEnd);
  26889. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  26890. this._loadingDiv.appendChild(imgBack);
  26891. // front image
  26892. var imgFront = new Image();
  26893. 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=";
  26894. imgFront.style.position = "absolute";
  26895. imgFront.style.left = "50%";
  26896. imgFront.style.top = "50%";
  26897. imgFront.style.marginLeft = "-50px";
  26898. imgFront.style.marginTop = "-50px";
  26899. this._loadingDiv.appendChild(imgFront);
  26900. this._resizeLoadingUI();
  26901. window.addEventListener("resize", this._resizeLoadingUI);
  26902. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26903. document.body.appendChild(this._loadingDiv);
  26904. setTimeout(function () {
  26905. _this._loadingDiv.style.opacity = "1";
  26906. imgBack.style.transform = "rotateZ(360deg)";
  26907. imgBack.style.webkitTransform = "rotateZ(360deg)";
  26908. }, 0);
  26909. };
  26910. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  26911. var _this = this;
  26912. if (!this._loadingDiv) {
  26913. return;
  26914. }
  26915. var onTransitionEnd = function () {
  26916. if (!_this._loadingDiv) {
  26917. return;
  26918. }
  26919. document.body.removeChild(_this._loadingDiv);
  26920. window.removeEventListener("resize", _this._resizeLoadingUI);
  26921. _this._loadingDiv = null;
  26922. };
  26923. this._loadingDiv.style.opacity = "0";
  26924. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  26925. };
  26926. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  26927. set: function (text) {
  26928. this._loadingText = text;
  26929. if (this._loadingTextDiv) {
  26930. this._loadingTextDiv.innerHTML = this._loadingText;
  26931. }
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  26937. get: function () {
  26938. return this._loadingDivBackgroundColor;
  26939. },
  26940. set: function (color) {
  26941. this._loadingDivBackgroundColor = color;
  26942. if (!this._loadingDiv) {
  26943. return;
  26944. }
  26945. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26946. },
  26947. enumerable: true,
  26948. configurable: true
  26949. });
  26950. return DefaultLoadingScreen;
  26951. })();
  26952. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  26953. })(BABYLON || (BABYLON = {}));
  26954. var BABYLON;
  26955. (function (BABYLON) {
  26956. var SIMDVector3 = (function () {
  26957. function SIMDVector3() {
  26958. }
  26959. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  26960. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  26961. var m0 = SIMD.float32x4.load(transformation.m, 0);
  26962. var m1 = SIMD.float32x4.load(transformation.m, 4);
  26963. var m2 = SIMD.float32x4.load(transformation.m, 8);
  26964. var m3 = SIMD.float32x4.load(transformation.m, 12);
  26965. 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));
  26966. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  26967. SIMD.float32x4.storeXYZ(result._data, 0, r);
  26968. };
  26969. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  26970. var v0 = SIMD.float32x4.splat(x);
  26971. var v1 = SIMD.float32x4.splat(y);
  26972. var v2 = SIMD.float32x4.splat(z);
  26973. var m0 = SIMD.float32x4.load(transformation.m, 0);
  26974. var m1 = SIMD.float32x4.load(transformation.m, 4);
  26975. var m2 = SIMD.float32x4.load(transformation.m, 8);
  26976. var m3 = SIMD.float32x4.load(transformation.m, 12);
  26977. 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));
  26978. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  26979. SIMD.float32x4.storeXYZ(result._data, 0, r);
  26980. };
  26981. return SIMDVector3;
  26982. })();
  26983. BABYLON.SIMDVector3 = SIMDVector3;
  26984. var SIMDMatrix = (function () {
  26985. function SIMDMatrix() {
  26986. }
  26987. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  26988. if (offset === void 0) { offset = 0; }
  26989. var tm = this.m;
  26990. var om = other.m;
  26991. var om0 = SIMD.float32x4.load(om, 0);
  26992. var om1 = SIMD.float32x4.load(om, 4);
  26993. var om2 = SIMD.float32x4.load(om, 8);
  26994. var om3 = SIMD.float32x4.load(om, 12);
  26995. var tm0 = SIMD.float32x4.load(tm, 0);
  26996. 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)))));
  26997. var tm1 = SIMD.float32x4.load(tm, 4);
  26998. 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)))));
  26999. var tm2 = SIMD.float32x4.load(tm, 8);
  27000. 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)))));
  27001. var tm3 = SIMD.float32x4.load(tm, 12);
  27002. 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)))));
  27003. };
  27004. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27005. var src = this.m;
  27006. var dest = other.m;
  27007. var row0, row1, row2, row3;
  27008. var tmp1;
  27009. var minor0, minor1, minor2, minor3;
  27010. var det;
  27011. // Load the 4 rows
  27012. var src0 = SIMD.float32x4.load(src, 0);
  27013. var src1 = SIMD.float32x4.load(src, 4);
  27014. var src2 = SIMD.float32x4.load(src, 8);
  27015. var src3 = SIMD.float32x4.load(src, 12);
  27016. // Transpose the source matrix. Sort of. Not a true transpose operation
  27017. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27018. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27019. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27020. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27021. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27022. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27023. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27024. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27025. // This is a true transposition, but it will lead to an incorrect result
  27026. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27027. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27028. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27029. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27030. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27031. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27032. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27033. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27034. // ----
  27035. tmp1 = SIMD.float32x4.mul(row2, row3);
  27036. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27037. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27038. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27039. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27040. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27041. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27042. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27043. // ----
  27044. tmp1 = SIMD.float32x4.mul(row1, row2);
  27045. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27046. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27047. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27048. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27049. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27050. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27051. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27052. // ----
  27053. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27054. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27055. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27056. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27057. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27058. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27059. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27060. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27061. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27062. // ----
  27063. tmp1 = SIMD.float32x4.mul(row0, row1);
  27064. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27065. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27066. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27067. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27068. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27069. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27070. // ----
  27071. tmp1 = SIMD.float32x4.mul(row0, row3);
  27072. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27073. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27074. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27075. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27076. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27077. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27078. // ----
  27079. tmp1 = SIMD.float32x4.mul(row0, row2);
  27080. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27081. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27082. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27083. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27084. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27085. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27086. // Compute determinant
  27087. det = SIMD.float32x4.mul(row0, minor0);
  27088. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27089. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27090. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27091. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27092. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27093. // These shuffles aren't necessary if the faulty transposition is done
  27094. // up at the top of this function.
  27095. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27096. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27097. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27098. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27099. // Compute final values by multiplying with 1/det
  27100. minor0 = SIMD.float32x4.mul(det, minor0);
  27101. minor1 = SIMD.float32x4.mul(det, minor1);
  27102. minor2 = SIMD.float32x4.mul(det, minor2);
  27103. minor3 = SIMD.float32x4.mul(det, minor3);
  27104. SIMD.float32x4.store(dest, 0, minor0);
  27105. SIMD.float32x4.store(dest, 4, minor1);
  27106. SIMD.float32x4.store(dest, 8, minor2);
  27107. SIMD.float32x4.store(dest, 12, minor3);
  27108. return this;
  27109. };
  27110. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27111. var out = result.m;
  27112. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27113. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27114. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27115. // cc.kmVec3Subtract(f, pCenter, pEye);
  27116. var f = SIMD.float32x4.sub(center, eye);
  27117. // cc.kmVec3Normalize(f, f);
  27118. var tmp = SIMD.float32x4.mul(f, f);
  27119. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27120. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27121. // cc.kmVec3Assign(up, pUp);
  27122. // cc.kmVec3Normalize(up, up);
  27123. tmp = SIMD.float32x4.mul(up, up);
  27124. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27125. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27126. // cc.kmVec3Cross(s, f, up);
  27127. 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)));
  27128. // cc.kmVec3Normalize(s, s);
  27129. tmp = SIMD.float32x4.mul(s, s);
  27130. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27131. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27132. // cc.kmVec3Cross(u, s, f);
  27133. 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)));
  27134. // cc.kmVec3Normalize(s, s);
  27135. tmp = SIMD.float32x4.mul(s, s);
  27136. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27137. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27138. var zero = SIMD.float32x4.splat(0.0);
  27139. s = SIMD.float32x4.neg(s);
  27140. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27141. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27142. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27143. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27144. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27145. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27146. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27147. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27148. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27149. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27150. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27151. var b3 = SIMD.float32x4.neg(eye);
  27152. b3 = SIMD.float32x4.withW(b3, 1.0);
  27153. 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)))));
  27154. 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)))));
  27155. 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)))));
  27156. 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)))));
  27157. };
  27158. return SIMDMatrix;
  27159. })();
  27160. BABYLON.SIMDMatrix = SIMDMatrix;
  27161. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27162. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27163. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27164. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27165. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27166. var SIMDHelper = (function () {
  27167. function SIMDHelper() {
  27168. }
  27169. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27170. get: function () {
  27171. return SIMDHelper._isEnabled;
  27172. },
  27173. enumerable: true,
  27174. configurable: true
  27175. });
  27176. SIMDHelper.DisableSIMD = function () {
  27177. // Replace functions
  27178. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27179. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27180. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27181. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27182. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27183. SIMDHelper._isEnabled = false;
  27184. };
  27185. SIMDHelper.EnableSIMD = function () {
  27186. if (window.SIMD === undefined) {
  27187. return;
  27188. }
  27189. // Replace functions
  27190. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27191. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27192. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27193. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27194. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27195. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27196. get: function () { return this._data[0]; },
  27197. set: function (value) {
  27198. if (!this._data) {
  27199. this._data = new Float32Array(3);
  27200. }
  27201. this._data[0] = value;
  27202. }
  27203. });
  27204. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27205. get: function () { return this._data[1]; },
  27206. set: function (value) {
  27207. this._data[1] = value;
  27208. }
  27209. });
  27210. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27211. get: function () { return this._data[2]; },
  27212. set: function (value) {
  27213. this._data[2] = value;
  27214. }
  27215. });
  27216. SIMDHelper._isEnabled = true;
  27217. };
  27218. SIMDHelper._isEnabled = false;
  27219. return SIMDHelper;
  27220. })();
  27221. BABYLON.SIMDHelper = SIMDHelper;
  27222. })(BABYLON || (BABYLON = {}));
  27223. var BABYLON;
  27224. (function (BABYLON) {
  27225. var ShaderMaterial = (function (_super) {
  27226. __extends(ShaderMaterial, _super);
  27227. function ShaderMaterial(name, scene, shaderPath, options) {
  27228. _super.call(this, name, scene);
  27229. this._textures = new Array();
  27230. this._floats = new Array();
  27231. this._floatsArrays = {};
  27232. this._colors3 = new Array();
  27233. this._colors4 = new Array();
  27234. this._vectors2 = new Array();
  27235. this._vectors3 = new Array();
  27236. this._vectors4 = new Array();
  27237. this._matrices = new Array();
  27238. this._matrices3x3 = new Array();
  27239. this._matrices2x2 = new Array();
  27240. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27241. this._shaderPath = shaderPath;
  27242. options.needAlphaBlending = options.needAlphaBlending || false;
  27243. options.needAlphaTesting = options.needAlphaTesting || false;
  27244. options.attributes = options.attributes || ["position", "normal", "uv"];
  27245. options.uniforms = options.uniforms || ["worldViewProjection"];
  27246. options.samplers = options.samplers || [];
  27247. options.defines = options.defines || [];
  27248. this._options = options;
  27249. }
  27250. ShaderMaterial.prototype.needAlphaBlending = function () {
  27251. return this._options.needAlphaBlending;
  27252. };
  27253. ShaderMaterial.prototype.needAlphaTesting = function () {
  27254. return this._options.needAlphaTesting;
  27255. };
  27256. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27257. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27258. this._options.uniforms.push(uniformName);
  27259. }
  27260. };
  27261. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27262. if (this._options.samplers.indexOf(name) === -1) {
  27263. this._options.samplers.push(name);
  27264. }
  27265. this._textures[name] = texture;
  27266. return this;
  27267. };
  27268. ShaderMaterial.prototype.setFloat = function (name, value) {
  27269. this._checkUniform(name);
  27270. this._floats[name] = value;
  27271. return this;
  27272. };
  27273. ShaderMaterial.prototype.setFloats = function (name, value) {
  27274. this._checkUniform(name);
  27275. this._floatsArrays[name] = value;
  27276. return this;
  27277. };
  27278. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27279. this._checkUniform(name);
  27280. this._colors3[name] = value;
  27281. return this;
  27282. };
  27283. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27284. this._checkUniform(name);
  27285. this._colors4[name] = value;
  27286. return this;
  27287. };
  27288. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27289. this._checkUniform(name);
  27290. this._vectors2[name] = value;
  27291. return this;
  27292. };
  27293. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27294. this._checkUniform(name);
  27295. this._vectors3[name] = value;
  27296. return this;
  27297. };
  27298. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27299. this._checkUniform(name);
  27300. this._vectors4[name] = value;
  27301. return this;
  27302. };
  27303. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27304. this._checkUniform(name);
  27305. this._matrices[name] = value;
  27306. return this;
  27307. };
  27308. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27309. this._checkUniform(name);
  27310. this._matrices3x3[name] = value;
  27311. return this;
  27312. };
  27313. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27314. this._checkUniform(name);
  27315. this._matrices2x2[name] = value;
  27316. return this;
  27317. };
  27318. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27319. var scene = this.getScene();
  27320. var engine = scene.getEngine();
  27321. if (!this.checkReadyOnEveryCall) {
  27322. if (this._renderId === scene.getRenderId()) {
  27323. return true;
  27324. }
  27325. }
  27326. // Instances
  27327. var defines = [];
  27328. var fallbacks = new BABYLON.EffectFallbacks();
  27329. if (useInstances) {
  27330. defines.push("#define INSTANCES");
  27331. }
  27332. for (var index = 0; index < this._options.defines.length; index++) {
  27333. defines.push(this._options.defines[index]);
  27334. }
  27335. // Bones
  27336. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27337. defines.push("#define BONES");
  27338. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27339. defines.push("#define BONES4");
  27340. fallbacks.addFallback(0, "BONES4");
  27341. }
  27342. // Alpha test
  27343. if (engine.getAlphaTesting()) {
  27344. defines.push("#define ALPHATEST");
  27345. }
  27346. var previousEffect = this._effect;
  27347. var join = defines.join("\n");
  27348. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27349. if (!this._effect.isReady()) {
  27350. return false;
  27351. }
  27352. if (previousEffect !== this._effect) {
  27353. scene.resetCachedMaterial();
  27354. }
  27355. this._renderId = scene.getRenderId();
  27356. return true;
  27357. };
  27358. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27359. var scene = this.getScene();
  27360. if (this._options.uniforms.indexOf("world") !== -1) {
  27361. this._effect.setMatrix("world", world);
  27362. }
  27363. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27364. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27365. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27366. }
  27367. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27368. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27369. }
  27370. };
  27371. ShaderMaterial.prototype.bind = function (world, mesh) {
  27372. // Std values
  27373. this.bindOnlyWorldMatrix(world);
  27374. if (this.getScene().getCachedMaterial() !== this) {
  27375. if (this._options.uniforms.indexOf("view") !== -1) {
  27376. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27377. }
  27378. if (this._options.uniforms.indexOf("projection") !== -1) {
  27379. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27380. }
  27381. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27382. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27383. }
  27384. // Bones
  27385. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27386. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27387. }
  27388. // Texture
  27389. for (var name in this._textures) {
  27390. this._effect.setTexture(name, this._textures[name]);
  27391. }
  27392. // Float
  27393. for (name in this._floats) {
  27394. this._effect.setFloat(name, this._floats[name]);
  27395. }
  27396. // Float s
  27397. for (name in this._floatsArrays) {
  27398. this._effect.setArray(name, this._floatsArrays[name]);
  27399. }
  27400. // Color3
  27401. for (name in this._colors3) {
  27402. this._effect.setColor3(name, this._colors3[name]);
  27403. }
  27404. // Color4
  27405. for (name in this._colors4) {
  27406. var color = this._colors4[name];
  27407. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27408. }
  27409. // Vector2
  27410. for (name in this._vectors2) {
  27411. this._effect.setVector2(name, this._vectors2[name]);
  27412. }
  27413. // Vector3
  27414. for (name in this._vectors3) {
  27415. this._effect.setVector3(name, this._vectors3[name]);
  27416. }
  27417. // Vector4
  27418. for (name in this._vectors4) {
  27419. this._effect.setVector4(name, this._vectors4[name]);
  27420. }
  27421. // Matrix
  27422. for (name in this._matrices) {
  27423. this._effect.setMatrix(name, this._matrices[name]);
  27424. }
  27425. // Matrix 3x3
  27426. for (name in this._matrices3x3) {
  27427. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27428. }
  27429. // Matrix 2x2
  27430. for (name in this._matrices2x2) {
  27431. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27432. }
  27433. }
  27434. _super.prototype.bind.call(this, world, mesh);
  27435. };
  27436. ShaderMaterial.prototype.clone = function (name) {
  27437. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27438. return newShaderMaterial;
  27439. };
  27440. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27441. for (var name in this._textures) {
  27442. this._textures[name].dispose();
  27443. }
  27444. this._textures = [];
  27445. _super.prototype.dispose.call(this, forceDisposeEffect);
  27446. };
  27447. return ShaderMaterial;
  27448. })(BABYLON.Material);
  27449. BABYLON.ShaderMaterial = ShaderMaterial;
  27450. })(BABYLON || (BABYLON = {}));
  27451. var BABYLON;
  27452. (function (BABYLON) {
  27453. var Internals;
  27454. (function (Internals) {
  27455. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27456. // All values and structures referenced from:
  27457. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27458. var DDS_MAGIC = 0x20534444;
  27459. 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;
  27460. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27461. 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;
  27462. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27463. function FourCCToInt32(value) {
  27464. return value.charCodeAt(0) +
  27465. (value.charCodeAt(1) << 8) +
  27466. (value.charCodeAt(2) << 16) +
  27467. (value.charCodeAt(3) << 24);
  27468. }
  27469. function Int32ToFourCC(value) {
  27470. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27471. }
  27472. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27473. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27474. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27475. var headerLengthInt = 31; // The header length in 32 bit ints
  27476. // Offsets into the header array
  27477. var off_magic = 0;
  27478. var off_size = 1;
  27479. var off_flags = 2;
  27480. var off_height = 3;
  27481. var off_width = 4;
  27482. var off_mipmapCount = 7;
  27483. var off_pfFlags = 20;
  27484. var off_pfFourCC = 21;
  27485. var off_RGBbpp = 22;
  27486. var off_RMask = 23;
  27487. var off_GMask = 24;
  27488. var off_BMask = 25;
  27489. var off_AMask = 26;
  27490. var off_caps1 = 27;
  27491. var off_caps2 = 28;
  27492. ;
  27493. var DDSTools = (function () {
  27494. function DDSTools() {
  27495. }
  27496. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27497. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27498. var mipmapCount = 1;
  27499. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27500. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27501. }
  27502. return {
  27503. width: header[off_width],
  27504. height: header[off_height],
  27505. mipmapCount: mipmapCount,
  27506. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27507. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27508. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27509. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27510. };
  27511. };
  27512. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27513. var byteArray = new Uint8Array(dataLength);
  27514. var srcData = new Uint8Array(arrayBuffer);
  27515. var index = 0;
  27516. for (var y = height - 1; y >= 0; y--) {
  27517. for (var x = 0; x < width; x++) {
  27518. var srcPos = dataOffset + (x + y * width) * 4;
  27519. byteArray[index + 2] = srcData[srcPos];
  27520. byteArray[index + 1] = srcData[srcPos + 1];
  27521. byteArray[index] = srcData[srcPos + 2];
  27522. byteArray[index + 3] = srcData[srcPos + 3];
  27523. index += 4;
  27524. }
  27525. }
  27526. return byteArray;
  27527. };
  27528. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27529. var byteArray = new Uint8Array(dataLength);
  27530. var srcData = new Uint8Array(arrayBuffer);
  27531. var index = 0;
  27532. for (var y = height - 1; y >= 0; y--) {
  27533. for (var x = 0; x < width; x++) {
  27534. var srcPos = dataOffset + (x + y * width) * 3;
  27535. byteArray[index + 2] = srcData[srcPos];
  27536. byteArray[index + 1] = srcData[srcPos + 1];
  27537. byteArray[index] = srcData[srcPos + 2];
  27538. index += 3;
  27539. }
  27540. }
  27541. return byteArray;
  27542. };
  27543. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27544. var byteArray = new Uint8Array(dataLength);
  27545. var srcData = new Uint8Array(arrayBuffer);
  27546. var index = 0;
  27547. for (var y = height - 1; y >= 0; y--) {
  27548. for (var x = 0; x < width; x++) {
  27549. var srcPos = dataOffset + (x + y * width);
  27550. byteArray[index] = srcData[srcPos];
  27551. index++;
  27552. }
  27553. }
  27554. return byteArray;
  27555. };
  27556. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27557. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27558. if (header[off_magic] != DDS_MAGIC) {
  27559. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27560. return;
  27561. }
  27562. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27563. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27564. return;
  27565. }
  27566. if (info.isFourCC) {
  27567. fourCC = header[off_pfFourCC];
  27568. switch (fourCC) {
  27569. case FOURCC_DXT1:
  27570. blockBytes = 8;
  27571. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27572. break;
  27573. case FOURCC_DXT3:
  27574. blockBytes = 16;
  27575. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27576. break;
  27577. case FOURCC_DXT5:
  27578. blockBytes = 16;
  27579. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27580. break;
  27581. default:
  27582. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27583. return;
  27584. }
  27585. }
  27586. mipmapCount = 1;
  27587. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27588. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27589. }
  27590. var bpp = header[off_RGBbpp];
  27591. for (var face = 0; face < faces; face++) {
  27592. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27593. width = header[off_width];
  27594. height = header[off_height];
  27595. dataOffset = header[off_size] + 4;
  27596. for (i = 0; i < mipmapCount; ++i) {
  27597. if (info.isRGB) {
  27598. if (bpp === 24) {
  27599. dataLength = width * height * 3;
  27600. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27601. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  27602. }
  27603. else {
  27604. dataLength = width * height * 4;
  27605. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27606. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  27607. }
  27608. }
  27609. else if (info.isLuminance) {
  27610. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  27611. var unpaddedRowSize = width;
  27612. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  27613. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  27614. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27615. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  27616. }
  27617. else {
  27618. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  27619. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  27620. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  27621. }
  27622. dataOffset += dataLength;
  27623. width *= 0.5;
  27624. height *= 0.5;
  27625. width = Math.max(1.0, width);
  27626. height = Math.max(1.0, height);
  27627. }
  27628. }
  27629. };
  27630. return DDSTools;
  27631. })();
  27632. Internals.DDSTools = DDSTools;
  27633. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27634. })(BABYLON || (BABYLON = {}));
  27635. var BABYLON;
  27636. (function (BABYLON) {
  27637. var CannonJSPlugin = (function () {
  27638. function CannonJSPlugin() {
  27639. this._registeredMeshes = [];
  27640. this._physicsMaterials = [];
  27641. this.updateBodyPosition = function (mesh) {
  27642. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27643. var registeredMesh = this._registeredMeshes[index];
  27644. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27645. var body = registeredMesh.body;
  27646. var center = mesh.getBoundingInfo().boundingBox.center;
  27647. body.position.set(center.x, center.y, center.z);
  27648. body.quaternion.copy(mesh.rotationQuaternion);
  27649. if (registeredMesh.deltaRotation) {
  27650. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  27651. body.quaternion = body.quaternion.mult(tmpQ);
  27652. }
  27653. if (registeredMesh.heightmap) {
  27654. //calculate the correct body position:
  27655. var rotationQuaternion = mesh.rotationQuaternion;
  27656. mesh.rotationQuaternion = new BABYLON.Quaternion();
  27657. mesh.computeWorldMatrix(true);
  27658. //get original center with no rotation
  27659. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  27660. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  27661. //rotation is back
  27662. mesh.rotationQuaternion = rotationQuaternion;
  27663. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  27664. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  27665. mesh.setPivotMatrix(p);
  27666. mesh.computeWorldMatrix(true);
  27667. //calculate the translation
  27668. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  27669. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  27670. //add it inverted to the delta
  27671. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  27672. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  27673. mesh.setPivotMatrix(oldPivot);
  27674. mesh.computeWorldMatrix(true);
  27675. }
  27676. return;
  27677. }
  27678. }
  27679. };
  27680. }
  27681. CannonJSPlugin.prototype.initialize = function (iterations) {
  27682. if (iterations === void 0) { iterations = 10; }
  27683. this._world = new CANNON.World();
  27684. this._world.broadphase = new CANNON.NaiveBroadphase();
  27685. this._world.solver.iterations = iterations;
  27686. };
  27687. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  27688. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27689. };
  27690. CannonJSPlugin.prototype.runOneStep = function (delta) {
  27691. this._world.step(delta);
  27692. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27693. var registeredMesh = this._registeredMeshes[index];
  27694. if (registeredMesh.isChild) {
  27695. continue;
  27696. }
  27697. // Body position
  27698. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  27699. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  27700. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  27701. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  27702. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  27703. if (registeredMesh.deltaRotation) {
  27704. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  27705. }
  27706. }
  27707. };
  27708. CannonJSPlugin.prototype.setGravity = function (gravity) {
  27709. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  27710. };
  27711. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27712. this.unregisterMesh(mesh);
  27713. if (!mesh.rotationQuaternion) {
  27714. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27715. }
  27716. mesh.computeWorldMatrix(true);
  27717. var shape = this._createShape(mesh, impostor);
  27718. return this._createRigidBodyFromShape(shape, mesh, options);
  27719. };
  27720. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  27721. //get the correct bounding box
  27722. var oldQuaternion = mesh.rotationQuaternion;
  27723. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27724. mesh.computeWorldMatrix(true);
  27725. var returnValue;
  27726. switch (impostor) {
  27727. case BABYLON.PhysicsEngine.SphereImpostor:
  27728. var bbox = mesh.getBoundingInfo().boundingBox;
  27729. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27730. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27731. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27732. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  27733. break;
  27734. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  27735. case BABYLON.PhysicsEngine.CylinderImpostor:
  27736. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  27737. case BABYLON.PhysicsEngine.BoxImpostor:
  27738. bbox = mesh.getBoundingInfo().boundingBox;
  27739. var min = bbox.minimumWorld;
  27740. var max = bbox.maximumWorld;
  27741. var box = max.subtract(min).scale(0.5);
  27742. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  27743. break;
  27744. case BABYLON.PhysicsEngine.PlaneImpostor:
  27745. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  27746. returnValue = new CANNON.Plane();
  27747. break;
  27748. case BABYLON.PhysicsEngine.MeshImpostor:
  27749. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27750. var rawFaces = mesh.getIndices();
  27751. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  27752. break;
  27753. case BABYLON.PhysicsEngine.HeightmapImpostor:
  27754. returnValue = this._createHeightmap(mesh);
  27755. break;
  27756. }
  27757. mesh.rotationQuaternion = oldQuaternion;
  27758. return returnValue;
  27759. };
  27760. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  27761. var verts = [], faces = [];
  27762. mesh.computeWorldMatrix(true);
  27763. //reuse this variable
  27764. var transformed = BABYLON.Vector3.Zero();
  27765. // Get vertices
  27766. for (var i = 0; i < rawVerts.length; i += 3) {
  27767. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  27768. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  27769. }
  27770. // Get faces
  27771. for (var j = 0; j < rawFaces.length; j += 3) {
  27772. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  27773. }
  27774. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  27775. return shape;
  27776. };
  27777. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  27778. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27779. var matrix = [];
  27780. //For now pointDepth will not be used and will be automatically calculated.
  27781. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  27782. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  27783. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  27784. var elementSize = dim * 2 / arraySize;
  27785. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  27786. for (var i = 0; i < pos.length; i = i + 3) {
  27787. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  27788. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  27789. var y = pos[i + 1] + minY;
  27790. if (!matrix[x]) {
  27791. matrix[x] = [];
  27792. }
  27793. if (!matrix[x][z]) {
  27794. matrix[x][z] = y;
  27795. }
  27796. matrix[x][z] = Math.max(y, matrix[x][z]);
  27797. }
  27798. for (var x = 0; x <= arraySize; ++x) {
  27799. if (!matrix[x]) {
  27800. var loc = 1;
  27801. while (!matrix[(x + loc) % arraySize]) {
  27802. loc++;
  27803. }
  27804. matrix[x] = matrix[(x + loc) % arraySize].slice();
  27805. }
  27806. for (var z = 0; z <= arraySize; ++z) {
  27807. if (!matrix[x][z]) {
  27808. var loc = 1;
  27809. var newValue;
  27810. while (newValue === undefined) {
  27811. newValue = matrix[x][(z + loc++) % arraySize];
  27812. }
  27813. matrix[x][z] = newValue;
  27814. }
  27815. }
  27816. }
  27817. var shape = new CANNON.Heightfield(matrix, {
  27818. elementSize: elementSize
  27819. });
  27820. //For future reference, needed for body transformation
  27821. shape.minY = minY;
  27822. return shape;
  27823. };
  27824. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  27825. var index;
  27826. var mat;
  27827. for (index = 0; index < this._physicsMaterials.length; index++) {
  27828. mat = this._physicsMaterials[index];
  27829. if (mat.friction === friction && mat.restitution === restitution) {
  27830. return mat;
  27831. }
  27832. }
  27833. var currentMat = new CANNON.Material("mat");
  27834. this._physicsMaterials.push(currentMat);
  27835. for (index = 0; index < this._physicsMaterials.length; index++) {
  27836. mat = this._physicsMaterials[index];
  27837. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  27838. this._world.addContactMaterial(contactMaterial);
  27839. }
  27840. return currentMat;
  27841. };
  27842. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  27843. if (!mesh.rotationQuaternion) {
  27844. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27845. }
  27846. // The delta between the mesh position and the mesh bounding box center
  27847. var bbox = mesh.getBoundingInfo().boundingBox;
  27848. var deltaPosition = mesh.position.subtract(bbox.center);
  27849. var deltaRotation;
  27850. var material = this._addMaterial(options.friction, options.restitution);
  27851. var body = new CANNON.Body({
  27852. mass: options.mass,
  27853. material: material,
  27854. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  27855. });
  27856. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  27857. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  27858. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  27859. //-90 DEG in X, precalculated
  27860. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  27861. body.quaternion = body.quaternion.mult(tmpQ);
  27862. //Invert! (Precalculated, 90 deg in X)
  27863. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  27864. }
  27865. //If it is a heightfield, if should be centered.
  27866. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  27867. //calculate the correct body position:
  27868. var rotationQuaternion = mesh.rotationQuaternion;
  27869. mesh.rotationQuaternion = new BABYLON.Quaternion();
  27870. mesh.computeWorldMatrix(true);
  27871. //get original center with no rotation
  27872. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  27873. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  27874. //rotation is back
  27875. mesh.rotationQuaternion = rotationQuaternion;
  27876. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  27877. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  27878. mesh.setPivotMatrix(p);
  27879. mesh.computeWorldMatrix(true);
  27880. //calculate the translation
  27881. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  27882. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  27883. //add it inverted to the delta
  27884. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  27885. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  27886. mesh.setPivotMatrix(oldPivot);
  27887. mesh.computeWorldMatrix(true);
  27888. }
  27889. //add the shape
  27890. body.addShape(shape);
  27891. this._world.add(body);
  27892. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  27893. return body;
  27894. };
  27895. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  27896. var initialMesh = parts[0].mesh;
  27897. this.unregisterMesh(initialMesh);
  27898. initialMesh.computeWorldMatrix(true);
  27899. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  27900. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  27901. for (var index = 1; index < parts.length; index++) {
  27902. var mesh = parts[index].mesh;
  27903. mesh.computeWorldMatrix(true);
  27904. var shape = this._createShape(mesh, parts[index].impostor);
  27905. var localPosition = mesh.position;
  27906. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  27907. }
  27908. return body;
  27909. };
  27910. CannonJSPlugin.prototype._unbindBody = function (body) {
  27911. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27912. var registeredMesh = this._registeredMeshes[index];
  27913. if (registeredMesh.body === body) {
  27914. this._world.remove(registeredMesh.body);
  27915. registeredMesh.body = null;
  27916. registeredMesh.delta = null;
  27917. registeredMesh.deltaRotation = null;
  27918. }
  27919. }
  27920. };
  27921. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  27922. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27923. var registeredMesh = this._registeredMeshes[index];
  27924. if (registeredMesh.mesh === mesh) {
  27925. // Remove body
  27926. if (registeredMesh.body) {
  27927. this._unbindBody(registeredMesh.body);
  27928. }
  27929. this._registeredMeshes.splice(index, 1);
  27930. return;
  27931. }
  27932. }
  27933. };
  27934. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  27935. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  27936. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  27937. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27938. var registeredMesh = this._registeredMeshes[index];
  27939. if (registeredMesh.mesh === mesh) {
  27940. registeredMesh.body.applyImpulse(impulse, worldPoint);
  27941. return;
  27942. }
  27943. }
  27944. };
  27945. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  27946. var body1 = null, body2 = null;
  27947. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27948. var registeredMesh = this._registeredMeshes[index];
  27949. if (registeredMesh.mesh === mesh1) {
  27950. body1 = registeredMesh.body;
  27951. }
  27952. else if (registeredMesh.mesh === mesh2) {
  27953. body2 = registeredMesh.body;
  27954. }
  27955. }
  27956. if (!body1 || !body2) {
  27957. return false;
  27958. }
  27959. 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));
  27960. this._world.addConstraint(constraint);
  27961. return true;
  27962. };
  27963. CannonJSPlugin.prototype.dispose = function () {
  27964. while (this._registeredMeshes.length) {
  27965. this.unregisterMesh(this._registeredMeshes[0].mesh);
  27966. }
  27967. };
  27968. CannonJSPlugin.prototype.isSupported = function () {
  27969. return window.CANNON !== undefined;
  27970. };
  27971. CannonJSPlugin.prototype.getWorldObject = function () {
  27972. return this._world;
  27973. };
  27974. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  27975. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27976. var registeredMesh = this._registeredMeshes[index];
  27977. if (registeredMesh.mesh === mesh) {
  27978. return registeredMesh.body;
  27979. }
  27980. }
  27981. return null;
  27982. };
  27983. return CannonJSPlugin;
  27984. })();
  27985. BABYLON.CannonJSPlugin = CannonJSPlugin;
  27986. })(BABYLON || (BABYLON = {}));
  27987. var BABYLON;
  27988. (function (BABYLON) {
  27989. var OimoJSPlugin = (function () {
  27990. function OimoJSPlugin() {
  27991. this._registeredMeshes = [];
  27992. /**
  27993. * Update the body position according to the mesh position
  27994. * @param mesh
  27995. */
  27996. this.updateBodyPosition = function (mesh) {
  27997. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27998. var registeredMesh = this._registeredMeshes[index];
  27999. var body = registeredMesh.body.body;
  28000. var updated = false;
  28001. var newPosition;
  28002. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28003. mesh.computeWorldMatrix(true);
  28004. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28005. updated = true;
  28006. }
  28007. else if (registeredMesh.mesh.parent === mesh) {
  28008. mesh.computeWorldMatrix(true);
  28009. registeredMesh.mesh.computeWorldMatrix(true);
  28010. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28011. updated = true;
  28012. }
  28013. if (updated) {
  28014. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28015. body.setQuaternion(mesh.rotationQuaternion);
  28016. body.sleeping = false;
  28017. //force Oimo to update the body's position
  28018. body.updatePosition(1);
  28019. }
  28020. }
  28021. };
  28022. }
  28023. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28024. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28025. };
  28026. OimoJSPlugin.prototype.initialize = function (iterations) {
  28027. this._world = new OIMO.World(null, null, iterations);
  28028. this._world.clear();
  28029. };
  28030. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28031. this._world.gravity = gravity;
  28032. };
  28033. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28034. this.unregisterMesh(mesh);
  28035. if (!mesh.rotationQuaternion) {
  28036. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28037. }
  28038. mesh.computeWorldMatrix(true);
  28039. var bbox = mesh.getBoundingInfo().boundingBox;
  28040. // The delta between the mesh position and the mesh bounding box center
  28041. var deltaPosition = mesh.position.subtract(bbox.center);
  28042. //calculate rotation to fit Oimo's needs (Euler...)
  28043. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28044. //get the correct bounding box
  28045. var oldQuaternion = mesh.rotationQuaternion;
  28046. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28047. mesh.computeWorldMatrix(true);
  28048. var bodyConfig = {
  28049. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28050. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28051. move: options.mass != 0,
  28052. config: [options.mass, options.friction, options.restitution],
  28053. world: this._world
  28054. };
  28055. // register mesh
  28056. switch (impostor) {
  28057. case BABYLON.PhysicsEngine.SphereImpostor:
  28058. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28059. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28060. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28061. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28062. bodyConfig.type = 'sphere';
  28063. bodyConfig.size = [size];
  28064. break;
  28065. case BABYLON.PhysicsEngine.PlaneImpostor:
  28066. //Oimo "fakes" a cylinder as a box, so why don't we!
  28067. case BABYLON.PhysicsEngine.CylinderImpostor:
  28068. case BABYLON.PhysicsEngine.BoxImpostor:
  28069. var min = bbox.minimumWorld;
  28070. var max = bbox.maximumWorld;
  28071. var box = max.subtract(min);
  28072. var sizeX = this._checkWithEpsilon(box.x);
  28073. var sizeY = this._checkWithEpsilon(box.y);
  28074. var sizeZ = this._checkWithEpsilon(box.z);
  28075. bodyConfig.type = 'box';
  28076. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28077. break;
  28078. }
  28079. var body = new OIMO.Body(bodyConfig);
  28080. //We have to access the rigid body's properties to set the quaternion.
  28081. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28082. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28083. //TEST
  28084. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28085. //update the internal rotation matrix
  28086. //body.body.syncShapes();
  28087. this._registeredMeshes.push({
  28088. mesh: mesh,
  28089. body: body,
  28090. delta: deltaPosition
  28091. });
  28092. //for the sake of consistency.
  28093. mesh.rotationQuaternion = oldQuaternion;
  28094. return body;
  28095. };
  28096. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28097. var types = [], sizes = [], positions = [], rotations = [];
  28098. var initialMesh = parts[0].mesh;
  28099. for (var index = 0; index < parts.length; index++) {
  28100. var part = parts[index];
  28101. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28102. types.push(bodyParameters.type);
  28103. sizes.push.apply(sizes, bodyParameters.size);
  28104. positions.push.apply(positions, bodyParameters.pos);
  28105. rotations.push.apply(rotations, bodyParameters.rot);
  28106. }
  28107. var body = new OIMO.Body({
  28108. type: types,
  28109. size: sizes,
  28110. pos: positions,
  28111. rot: rotations,
  28112. move: options.mass != 0,
  28113. config: [options.mass, options.friction, options.restitution],
  28114. world: this._world
  28115. });
  28116. //Reset the body's rotation to be of the initial mesh's.
  28117. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28118. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28119. this._registeredMeshes.push({
  28120. mesh: initialMesh,
  28121. body: body
  28122. });
  28123. return body;
  28124. };
  28125. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28126. var mesh = part.mesh;
  28127. if (!mesh.rotationQuaternion) {
  28128. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28129. }
  28130. // We need the bounding box/sphere info to compute the physics body
  28131. mesh.computeWorldMatrix(true);
  28132. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28133. var bodyParameters = {
  28134. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28135. //A bug in Oimo (Body class) prevents us from using rot directly.
  28136. rot: [0, 0, 0],
  28137. //For future reference, if the bug will ever be fixed.
  28138. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28139. };
  28140. var oldQuaternion = mesh.rotationQuaternion;
  28141. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28142. mesh.computeWorldMatrix(true);
  28143. switch (part.impostor) {
  28144. case BABYLON.PhysicsEngine.SphereImpostor:
  28145. var bbox = mesh.getBoundingInfo().boundingBox;
  28146. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28147. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28148. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28149. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28150. bodyParameters.type = 'sphere';
  28151. bodyParameters.size = [size, size, size];
  28152. break;
  28153. case BABYLON.PhysicsEngine.PlaneImpostor:
  28154. case BABYLON.PhysicsEngine.CylinderImpostor:
  28155. case BABYLON.PhysicsEngine.BoxImpostor:
  28156. bbox = mesh.getBoundingInfo().boundingBox;
  28157. var min = bbox.minimumWorld;
  28158. var max = bbox.maximumWorld;
  28159. var box = max.subtract(min);
  28160. var sizeX = this._checkWithEpsilon(box.x);
  28161. var sizeY = this._checkWithEpsilon(box.y);
  28162. var sizeZ = this._checkWithEpsilon(box.z);
  28163. bodyParameters.type = 'box';
  28164. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28165. break;
  28166. }
  28167. mesh.rotationQuaternion = oldQuaternion;
  28168. return bodyParameters;
  28169. };
  28170. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28171. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28172. var registeredMesh = this._registeredMeshes[index];
  28173. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28174. if (registeredMesh.body) {
  28175. this._world.removeRigidBody(registeredMesh.body.body);
  28176. this._unbindBody(registeredMesh.body);
  28177. }
  28178. this._registeredMeshes.splice(index, 1);
  28179. return;
  28180. }
  28181. }
  28182. };
  28183. OimoJSPlugin.prototype._unbindBody = function (body) {
  28184. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28185. var registeredMesh = this._registeredMeshes[index];
  28186. if (registeredMesh.body === body) {
  28187. registeredMesh.body = null;
  28188. }
  28189. }
  28190. };
  28191. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28192. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28193. var registeredMesh = this._registeredMeshes[index];
  28194. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28195. // Get object mass to have a behaviour similar to cannon.js
  28196. var mass = registeredMesh.body.body.massInfo.mass;
  28197. // The force is scaled with the mass of object
  28198. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28199. return;
  28200. }
  28201. }
  28202. };
  28203. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28204. var body1 = null, body2 = null;
  28205. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28206. var registeredMesh = this._registeredMeshes[index];
  28207. if (registeredMesh.mesh === mesh1) {
  28208. body1 = registeredMesh.body.body;
  28209. }
  28210. else if (registeredMesh.mesh === mesh2) {
  28211. body2 = registeredMesh.body.body;
  28212. }
  28213. }
  28214. if (!body1 || !body2) {
  28215. return false;
  28216. }
  28217. if (!options) {
  28218. options = {};
  28219. }
  28220. new OIMO.Link({
  28221. type: options.type,
  28222. body1: body1,
  28223. body2: body2,
  28224. min: options.min,
  28225. max: options.max,
  28226. axe1: options.axe1,
  28227. axe2: options.axe2,
  28228. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28229. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28230. collision: options.collision,
  28231. spring: options.spring,
  28232. world: this._world
  28233. });
  28234. return true;
  28235. };
  28236. OimoJSPlugin.prototype.dispose = function () {
  28237. this._world.clear();
  28238. while (this._registeredMeshes.length) {
  28239. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28240. }
  28241. };
  28242. OimoJSPlugin.prototype.isSupported = function () {
  28243. return OIMO !== undefined;
  28244. };
  28245. OimoJSPlugin.prototype.getWorldObject = function () {
  28246. return this._world;
  28247. };
  28248. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28249. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28250. var registeredMesh = this._registeredMeshes[index];
  28251. if (registeredMesh.mesh === mesh) {
  28252. return registeredMesh.body;
  28253. }
  28254. }
  28255. return null;
  28256. };
  28257. OimoJSPlugin.prototype._getLastShape = function (body) {
  28258. var lastShape = body.shapes;
  28259. while (lastShape.next) {
  28260. lastShape = lastShape.next;
  28261. }
  28262. return lastShape;
  28263. };
  28264. OimoJSPlugin.prototype.runOneStep = function (time) {
  28265. this._world.step();
  28266. // Update the position of all registered meshes
  28267. var i = this._registeredMeshes.length;
  28268. var m;
  28269. while (i--) {
  28270. var body = this._registeredMeshes[i].body.body;
  28271. var mesh = this._registeredMeshes[i].mesh;
  28272. if (!this._registeredMeshes[i].delta) {
  28273. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28274. }
  28275. if (!body.sleeping) {
  28276. //TODO check that
  28277. if (body.shapes.next) {
  28278. var parentShape = this._getLastShape(body);
  28279. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28280. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28281. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28282. }
  28283. else {
  28284. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28285. }
  28286. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28287. mesh.computeWorldMatrix();
  28288. }
  28289. }
  28290. };
  28291. return OimoJSPlugin;
  28292. })();
  28293. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28294. })(BABYLON || (BABYLON = {}));
  28295. var BABYLON;
  28296. (function (BABYLON) {
  28297. var DisplayPassPostProcess = (function (_super) {
  28298. __extends(DisplayPassPostProcess, _super);
  28299. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28300. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28301. }
  28302. return DisplayPassPostProcess;
  28303. })(BABYLON.PostProcess);
  28304. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28305. })(BABYLON || (BABYLON = {}));
  28306. var BABYLON;
  28307. (function (BABYLON) {
  28308. var SimplificationSettings = (function () {
  28309. function SimplificationSettings(quality, distance, optimizeMesh) {
  28310. this.quality = quality;
  28311. this.distance = distance;
  28312. this.optimizeMesh = optimizeMesh;
  28313. }
  28314. return SimplificationSettings;
  28315. })();
  28316. BABYLON.SimplificationSettings = SimplificationSettings;
  28317. var SimplificationQueue = (function () {
  28318. function SimplificationQueue() {
  28319. this.running = false;
  28320. this._simplificationArray = [];
  28321. }
  28322. SimplificationQueue.prototype.addTask = function (task) {
  28323. this._simplificationArray.push(task);
  28324. };
  28325. SimplificationQueue.prototype.executeNext = function () {
  28326. var task = this._simplificationArray.pop();
  28327. if (task) {
  28328. this.running = true;
  28329. this.runSimplification(task);
  28330. }
  28331. else {
  28332. this.running = false;
  28333. }
  28334. };
  28335. SimplificationQueue.prototype.runSimplification = function (task) {
  28336. var _this = this;
  28337. if (task.parallelProcessing) {
  28338. //parallel simplifier
  28339. task.settings.forEach(function (setting) {
  28340. var simplifier = _this.getSimplifier(task);
  28341. simplifier.simplify(setting, function (newMesh) {
  28342. task.mesh.addLODLevel(setting.distance, newMesh);
  28343. newMesh.isVisible = true;
  28344. //check if it is the last
  28345. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28346. //all done, run the success callback.
  28347. task.successCallback();
  28348. }
  28349. _this.executeNext();
  28350. });
  28351. });
  28352. }
  28353. else {
  28354. //single simplifier.
  28355. var simplifier = this.getSimplifier(task);
  28356. var runDecimation = function (setting, callback) {
  28357. simplifier.simplify(setting, function (newMesh) {
  28358. task.mesh.addLODLevel(setting.distance, newMesh);
  28359. newMesh.isVisible = true;
  28360. //run the next quality level
  28361. callback();
  28362. });
  28363. };
  28364. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28365. runDecimation(task.settings[loop.index], function () {
  28366. loop.executeNext();
  28367. });
  28368. }, function () {
  28369. //execution ended, run the success callback.
  28370. if (task.successCallback) {
  28371. task.successCallback();
  28372. }
  28373. _this.executeNext();
  28374. });
  28375. }
  28376. };
  28377. SimplificationQueue.prototype.getSimplifier = function (task) {
  28378. switch (task.simplificationType) {
  28379. case SimplificationType.QUADRATIC:
  28380. default:
  28381. return new QuadraticErrorSimplification(task.mesh);
  28382. }
  28383. };
  28384. return SimplificationQueue;
  28385. })();
  28386. BABYLON.SimplificationQueue = SimplificationQueue;
  28387. /**
  28388. * The implemented types of simplification.
  28389. * At the moment only Quadratic Error Decimation is implemented.
  28390. */
  28391. (function (SimplificationType) {
  28392. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28393. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28394. var SimplificationType = BABYLON.SimplificationType;
  28395. var DecimationTriangle = (function () {
  28396. function DecimationTriangle(vertices) {
  28397. this.vertices = vertices;
  28398. this.error = new Array(4);
  28399. this.deleted = false;
  28400. this.isDirty = false;
  28401. this.deletePending = false;
  28402. this.borderFactor = 0;
  28403. }
  28404. return DecimationTriangle;
  28405. })();
  28406. BABYLON.DecimationTriangle = DecimationTriangle;
  28407. var DecimationVertex = (function () {
  28408. function DecimationVertex(position, id) {
  28409. this.position = position;
  28410. this.id = id;
  28411. this.isBorder = true;
  28412. this.q = new QuadraticMatrix();
  28413. this.triangleCount = 0;
  28414. this.triangleStart = 0;
  28415. this.originalOffsets = [];
  28416. }
  28417. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28418. this.position.copyFrom(newPosition);
  28419. };
  28420. return DecimationVertex;
  28421. })();
  28422. BABYLON.DecimationVertex = DecimationVertex;
  28423. var QuadraticMatrix = (function () {
  28424. function QuadraticMatrix(data) {
  28425. this.data = new Array(10);
  28426. for (var i = 0; i < 10; ++i) {
  28427. if (data && data[i]) {
  28428. this.data[i] = data[i];
  28429. }
  28430. else {
  28431. this.data[i] = 0;
  28432. }
  28433. }
  28434. }
  28435. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28436. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28437. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28438. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28439. return det;
  28440. };
  28441. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28442. for (var i = 0; i < 10; ++i) {
  28443. this.data[i] += matrix.data[i];
  28444. }
  28445. };
  28446. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28447. for (var i = 0; i < 10; ++i) {
  28448. this.data[i] += data[i];
  28449. }
  28450. };
  28451. QuadraticMatrix.prototype.add = function (matrix) {
  28452. var m = new QuadraticMatrix();
  28453. for (var i = 0; i < 10; ++i) {
  28454. m.data[i] = this.data[i] + matrix.data[i];
  28455. }
  28456. return m;
  28457. };
  28458. QuadraticMatrix.FromData = function (a, b, c, d) {
  28459. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28460. };
  28461. //returning an array to avoid garbage collection
  28462. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28463. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28464. };
  28465. return QuadraticMatrix;
  28466. })();
  28467. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28468. var Reference = (function () {
  28469. function Reference(vertexId, triangleId) {
  28470. this.vertexId = vertexId;
  28471. this.triangleId = triangleId;
  28472. }
  28473. return Reference;
  28474. })();
  28475. BABYLON.Reference = Reference;
  28476. /**
  28477. * An implementation of the Quadratic Error simplification algorithm.
  28478. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28479. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28480. * @author RaananW
  28481. */
  28482. var QuadraticErrorSimplification = (function () {
  28483. function QuadraticErrorSimplification(_mesh) {
  28484. this._mesh = _mesh;
  28485. this.initialized = false;
  28486. this.syncIterations = 5000;
  28487. this.aggressiveness = 7;
  28488. this.decimationIterations = 100;
  28489. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28490. }
  28491. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28492. var _this = this;
  28493. this.initDecimatedMesh();
  28494. //iterating through the submeshes array, one after the other.
  28495. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28496. _this.initWithMesh(loop.index, function () {
  28497. _this.runDecimation(settings, loop.index, function () {
  28498. loop.executeNext();
  28499. });
  28500. }, settings.optimizeMesh);
  28501. }, function () {
  28502. setTimeout(function () {
  28503. successCallback(_this._reconstructedMesh);
  28504. }, 0);
  28505. });
  28506. };
  28507. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28508. var _this = this;
  28509. var gCount = 0;
  28510. triangle.vertices.forEach(function (vertex) {
  28511. var count = 0;
  28512. var vPos = vertex.position;
  28513. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28514. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28515. ++count;
  28516. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28517. ++count;
  28518. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28519. ++count;
  28520. if (count > 1) {
  28521. ++gCount;
  28522. }
  28523. ;
  28524. });
  28525. if (gCount > 1) {
  28526. console.log(triangle, gCount);
  28527. }
  28528. return gCount > 1;
  28529. };
  28530. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28531. var _this = this;
  28532. var targetCount = ~~(this.triangles.length * settings.quality);
  28533. var deletedTriangles = 0;
  28534. var triangleCount = this.triangles.length;
  28535. var iterationFunction = function (iteration, callback) {
  28536. setTimeout(function () {
  28537. if (iteration % 5 === 0) {
  28538. _this.updateMesh(iteration === 0);
  28539. }
  28540. for (var i = 0; i < _this.triangles.length; ++i) {
  28541. _this.triangles[i].isDirty = false;
  28542. }
  28543. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28544. var trianglesIterator = function (i) {
  28545. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28546. var t = _this.triangles[tIdx];
  28547. if (!t)
  28548. return;
  28549. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28550. return;
  28551. }
  28552. for (var j = 0; j < 3; ++j) {
  28553. if (t.error[j] < threshold) {
  28554. var deleted0 = [];
  28555. var deleted1 = [];
  28556. var v0 = t.vertices[j];
  28557. var v1 = t.vertices[(j + 1) % 3];
  28558. if (v0.isBorder !== v1.isBorder)
  28559. continue;
  28560. var p = BABYLON.Vector3.Zero();
  28561. var n = BABYLON.Vector3.Zero();
  28562. var uv = BABYLON.Vector2.Zero();
  28563. var color = new BABYLON.Color4(0, 0, 0, 1);
  28564. _this.calculateError(v0, v1, p, n, uv, color);
  28565. var delTr = [];
  28566. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28567. continue;
  28568. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28569. continue;
  28570. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28571. continue;
  28572. var uniqueArray = [];
  28573. delTr.forEach(function (deletedT) {
  28574. if (uniqueArray.indexOf(deletedT) === -1) {
  28575. deletedT.deletePending = true;
  28576. uniqueArray.push(deletedT);
  28577. }
  28578. });
  28579. if (uniqueArray.length % 2 !== 0) {
  28580. continue;
  28581. }
  28582. v0.q = v1.q.add(v0.q);
  28583. v0.updatePosition(p);
  28584. var tStart = _this.references.length;
  28585. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28586. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28587. var tCount = _this.references.length - tStart;
  28588. if (tCount <= v0.triangleCount) {
  28589. if (tCount) {
  28590. for (var c = 0; c < tCount; c++) {
  28591. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28592. }
  28593. }
  28594. }
  28595. else {
  28596. v0.triangleStart = tStart;
  28597. }
  28598. v0.triangleCount = tCount;
  28599. break;
  28600. }
  28601. }
  28602. };
  28603. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  28604. }, 0);
  28605. };
  28606. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28607. if (triangleCount - deletedTriangles <= targetCount)
  28608. loop.breakLoop();
  28609. else {
  28610. iterationFunction(loop.index, function () {
  28611. loop.executeNext();
  28612. });
  28613. }
  28614. }, function () {
  28615. setTimeout(function () {
  28616. //reconstruct this part of the mesh
  28617. _this.reconstructMesh(submeshIndex);
  28618. successCallback();
  28619. }, 0);
  28620. });
  28621. };
  28622. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28623. var _this = this;
  28624. this.vertices = [];
  28625. this.triangles = [];
  28626. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28627. var indices = this._mesh.getIndices();
  28628. var submesh = this._mesh.subMeshes[submeshIndex];
  28629. var findInVertices = function (positionToSearch) {
  28630. if (optimizeMesh) {
  28631. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28632. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28633. return _this.vertices[ii];
  28634. }
  28635. }
  28636. }
  28637. return null;
  28638. };
  28639. var vertexReferences = [];
  28640. var vertexInit = function (i) {
  28641. var offset = i + submesh.verticesStart;
  28642. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28643. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28644. vertex.originalOffsets.push(offset);
  28645. if (vertex.id === _this.vertices.length) {
  28646. _this.vertices.push(vertex);
  28647. }
  28648. vertexReferences.push(vertex.id);
  28649. };
  28650. //var totalVertices = mesh.getTotalVertices();
  28651. var totalVertices = submesh.verticesCount;
  28652. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28653. var indicesInit = function (i) {
  28654. var offset = (submesh.indexStart / 3) + i;
  28655. var pos = (offset * 3);
  28656. var i0 = indices[pos + 0];
  28657. var i1 = indices[pos + 1];
  28658. var i2 = indices[pos + 2];
  28659. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28660. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28661. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28662. var triangle = new DecimationTriangle([v0, v1, v2]);
  28663. triangle.originalOffset = pos;
  28664. _this.triangles.push(triangle);
  28665. };
  28666. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28667. _this.init(callback);
  28668. });
  28669. });
  28670. };
  28671. QuadraticErrorSimplification.prototype.init = function (callback) {
  28672. var _this = this;
  28673. var triangleInit1 = function (i) {
  28674. var t = _this.triangles[i];
  28675. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28676. for (var j = 0; j < 3; j++) {
  28677. 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))));
  28678. }
  28679. };
  28680. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28681. var triangleInit2 = function (i) {
  28682. var t = _this.triangles[i];
  28683. for (var j = 0; j < 3; ++j) {
  28684. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28685. }
  28686. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28687. };
  28688. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28689. _this.initialized = true;
  28690. callback();
  28691. });
  28692. });
  28693. };
  28694. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28695. var newTriangles = [];
  28696. var i;
  28697. for (i = 0; i < this.vertices.length; ++i) {
  28698. this.vertices[i].triangleCount = 0;
  28699. }
  28700. var t;
  28701. var j;
  28702. for (i = 0; i < this.triangles.length; ++i) {
  28703. if (!this.triangles[i].deleted) {
  28704. t = this.triangles[i];
  28705. for (j = 0; j < 3; ++j) {
  28706. t.vertices[j].triangleCount = 1;
  28707. }
  28708. newTriangles.push(t);
  28709. }
  28710. }
  28711. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  28712. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  28713. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  28714. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  28715. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28716. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28717. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28718. var vertexCount = 0;
  28719. for (i = 0; i < this.vertices.length; ++i) {
  28720. var vertex = this.vertices[i];
  28721. vertex.id = vertexCount;
  28722. if (vertex.triangleCount) {
  28723. vertex.originalOffsets.forEach(function (originalOffset) {
  28724. newPositionData.push(vertex.position.x);
  28725. newPositionData.push(vertex.position.y);
  28726. newPositionData.push(vertex.position.z);
  28727. newNormalData.push(normalData[originalOffset * 3]);
  28728. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28729. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28730. if (uvs && uvs.length) {
  28731. newUVsData.push(uvs[(originalOffset * 2)]);
  28732. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28733. }
  28734. else if (colorsData && colorsData.length) {
  28735. newColorsData.push(colorsData[(originalOffset * 4)]);
  28736. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28737. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28738. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28739. }
  28740. ++vertexCount;
  28741. });
  28742. }
  28743. }
  28744. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28745. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28746. var submeshesArray = this._reconstructedMesh.subMeshes;
  28747. this._reconstructedMesh.subMeshes = [];
  28748. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28749. var originalIndices = this._mesh.getIndices();
  28750. for (i = 0; i < newTriangles.length; ++i) {
  28751. t = newTriangles[i]; //now get the new referencing point for each vertex
  28752. [0, 1, 2].forEach(function (idx) {
  28753. var id = originalIndices[t.originalOffset + idx];
  28754. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28755. if (offset < 0)
  28756. offset = 0;
  28757. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28758. });
  28759. }
  28760. //overwriting the old vertex buffers and indices.
  28761. this._reconstructedMesh.setIndices(newIndicesArray);
  28762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28763. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28764. if (newUVsData.length > 0)
  28765. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28766. if (newColorsData.length > 0)
  28767. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28768. //create submesh
  28769. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28770. if (submeshIndex > 0) {
  28771. this._reconstructedMesh.subMeshes = [];
  28772. submeshesArray.forEach(function (submesh) {
  28773. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28774. });
  28775. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28776. }
  28777. };
  28778. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28779. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28780. this._reconstructedMesh.material = this._mesh.material;
  28781. this._reconstructedMesh.parent = this._mesh.parent;
  28782. this._reconstructedMesh.isVisible = false;
  28783. };
  28784. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  28785. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28786. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28787. if (t.deleted)
  28788. continue;
  28789. var s = this.references[vertex1.triangleStart + i].vertexId;
  28790. var v1 = t.vertices[(s + 1) % 3];
  28791. var v2 = t.vertices[(s + 2) % 3];
  28792. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  28793. deletedArray[i] = true;
  28794. delTr.push(t);
  28795. continue;
  28796. }
  28797. var d1 = v1.position.subtract(point);
  28798. d1 = d1.normalize();
  28799. var d2 = v2.position.subtract(point);
  28800. d2 = d2.normalize();
  28801. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28802. return true;
  28803. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28804. deletedArray[i] = false;
  28805. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28806. return true;
  28807. }
  28808. return false;
  28809. };
  28810. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  28811. var newDeleted = deletedTriangles;
  28812. for (var i = 0; i < vertex.triangleCount; ++i) {
  28813. var ref = this.references[vertex.triangleStart + i];
  28814. var t = this.triangles[ref.triangleId];
  28815. if (t.deleted)
  28816. continue;
  28817. if (deletedArray[i] && t.deletePending) {
  28818. t.deleted = true;
  28819. newDeleted++;
  28820. continue;
  28821. }
  28822. t.vertices[ref.vertexId] = origVertex;
  28823. t.isDirty = true;
  28824. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  28825. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  28826. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  28827. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28828. this.references.push(ref);
  28829. }
  28830. return newDeleted;
  28831. };
  28832. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28833. for (var i = 0; i < this.vertices.length; ++i) {
  28834. var vCount = [];
  28835. var vId = [];
  28836. var v = this.vertices[i];
  28837. var j;
  28838. for (j = 0; j < v.triangleCount; ++j) {
  28839. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28840. for (var ii = 0; ii < 3; ii++) {
  28841. var ofs = 0;
  28842. var vv = triangle.vertices[ii];
  28843. while (ofs < vCount.length) {
  28844. if (vId[ofs] === vv.id)
  28845. break;
  28846. ++ofs;
  28847. }
  28848. if (ofs === vCount.length) {
  28849. vCount.push(1);
  28850. vId.push(vv.id);
  28851. }
  28852. else {
  28853. vCount[ofs]++;
  28854. }
  28855. }
  28856. }
  28857. for (j = 0; j < vCount.length; ++j) {
  28858. if (vCount[j] === 1) {
  28859. this.vertices[vId[j]].isBorder = true;
  28860. }
  28861. else {
  28862. this.vertices[vId[j]].isBorder = false;
  28863. }
  28864. }
  28865. }
  28866. };
  28867. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28868. if (identifyBorders === void 0) { identifyBorders = false; }
  28869. var i;
  28870. if (!identifyBorders) {
  28871. var newTrianglesVector = [];
  28872. for (i = 0; i < this.triangles.length; ++i) {
  28873. if (!this.triangles[i].deleted) {
  28874. newTrianglesVector.push(this.triangles[i]);
  28875. }
  28876. }
  28877. this.triangles = newTrianglesVector;
  28878. }
  28879. for (i = 0; i < this.vertices.length; ++i) {
  28880. this.vertices[i].triangleCount = 0;
  28881. this.vertices[i].triangleStart = 0;
  28882. }
  28883. var t;
  28884. var j;
  28885. var v;
  28886. for (i = 0; i < this.triangles.length; ++i) {
  28887. t = this.triangles[i];
  28888. for (j = 0; j < 3; ++j) {
  28889. v = t.vertices[j];
  28890. v.triangleCount++;
  28891. }
  28892. }
  28893. var tStart = 0;
  28894. for (i = 0; i < this.vertices.length; ++i) {
  28895. this.vertices[i].triangleStart = tStart;
  28896. tStart += this.vertices[i].triangleCount;
  28897. this.vertices[i].triangleCount = 0;
  28898. }
  28899. var newReferences = new Array(this.triangles.length * 3);
  28900. for (i = 0; i < this.triangles.length; ++i) {
  28901. t = this.triangles[i];
  28902. for (j = 0; j < 3; ++j) {
  28903. v = t.vertices[j];
  28904. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28905. v.triangleCount++;
  28906. }
  28907. }
  28908. this.references = newReferences;
  28909. if (identifyBorders) {
  28910. this.identifyBorder();
  28911. }
  28912. };
  28913. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28914. var x = point.x;
  28915. var y = point.y;
  28916. var z = point.z;
  28917. 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
  28918. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  28919. };
  28920. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28921. var q = vertex1.q.add(vertex2.q);
  28922. var border = vertex1.isBorder && vertex2.isBorder;
  28923. var error = 0;
  28924. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28925. if (qDet !== 0 && !border) {
  28926. if (!pointResult) {
  28927. pointResult = BABYLON.Vector3.Zero();
  28928. }
  28929. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28930. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28931. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28932. error = this.vertexError(q, pointResult);
  28933. }
  28934. else {
  28935. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28936. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28937. var error1 = this.vertexError(q, vertex1.position);
  28938. var error2 = this.vertexError(q, vertex2.position);
  28939. var error3 = this.vertexError(q, p3);
  28940. error = Math.min(error1, error2, error3);
  28941. if (error === error1) {
  28942. if (pointResult) {
  28943. pointResult.copyFrom(vertex1.position);
  28944. }
  28945. }
  28946. else if (error === error2) {
  28947. if (pointResult) {
  28948. pointResult.copyFrom(vertex2.position);
  28949. }
  28950. }
  28951. else {
  28952. if (pointResult) {
  28953. pointResult.copyFrom(p3);
  28954. }
  28955. }
  28956. }
  28957. return error;
  28958. };
  28959. return QuadraticErrorSimplification;
  28960. })();
  28961. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28962. })(BABYLON || (BABYLON = {}));
  28963. var BABYLON;
  28964. (function (BABYLON) {
  28965. var serializeLight = function (light) {
  28966. var serializationObject = {};
  28967. serializationObject.name = light.name;
  28968. serializationObject.id = light.id;
  28969. serializationObject.tags = BABYLON.Tags.GetTags(light);
  28970. if (light instanceof BABYLON.PointLight) {
  28971. serializationObject.type = 0;
  28972. serializationObject.position = (light).position.asArray();
  28973. }
  28974. else if (light instanceof BABYLON.DirectionalLight) {
  28975. serializationObject.type = 1;
  28976. var directionalLight = light;
  28977. serializationObject.position = directionalLight.position.asArray();
  28978. serializationObject.direction = directionalLight.direction.asArray();
  28979. }
  28980. else if (light instanceof BABYLON.SpotLight) {
  28981. serializationObject.type = 2;
  28982. var spotLight = light;
  28983. serializationObject.position = spotLight.position.asArray();
  28984. serializationObject.direction = spotLight.position.asArray();
  28985. serializationObject.angle = spotLight.angle;
  28986. serializationObject.exponent = spotLight.exponent;
  28987. }
  28988. else if (light instanceof BABYLON.HemisphericLight) {
  28989. serializationObject.type = 3;
  28990. var hemisphericLight = light;
  28991. serializationObject.direction = hemisphericLight.direction.asArray();
  28992. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  28993. }
  28994. if (light.intensity) {
  28995. serializationObject.intensity = light.intensity;
  28996. }
  28997. serializationObject.range = light.range;
  28998. serializationObject.diffuse = light.diffuse.asArray();
  28999. serializationObject.specular = light.specular.asArray();
  29000. return serializationObject;
  29001. };
  29002. var serializeFresnelParameter = function (fresnelParameter) {
  29003. var serializationObject = {};
  29004. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29005. serializationObject.leftColor = fresnelParameter.leftColor;
  29006. serializationObject.rightColor = fresnelParameter.rightColor;
  29007. serializationObject.bias = fresnelParameter.bias;
  29008. serializationObject.power = fresnelParameter.power;
  29009. return serializationObject;
  29010. };
  29011. var serializeAnimation;
  29012. var appendAnimations = function (source, destination) {
  29013. if (source.animations) {
  29014. destination.animations = [];
  29015. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29016. var animation = source.animations[animationIndex];
  29017. destination.animations.push(serializeAnimation(animation));
  29018. }
  29019. }
  29020. };
  29021. var serializeCamera = function (camera) {
  29022. var serializationObject = {};
  29023. serializationObject.name = camera.name;
  29024. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29025. serializationObject.id = camera.id;
  29026. serializationObject.position = camera.position.asArray();
  29027. // Parent
  29028. if (camera.parent) {
  29029. serializationObject.parentId = camera.parent.id;
  29030. }
  29031. serializationObject.fov = camera.fov;
  29032. serializationObject.minZ = camera.minZ;
  29033. serializationObject.maxZ = camera.maxZ;
  29034. serializationObject.inertia = camera.inertia;
  29035. //setting the type
  29036. if (camera instanceof BABYLON.FreeCamera) {
  29037. serializationObject.type = "FreeCamera";
  29038. }
  29039. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29040. serializationObject.type = "ArcRotateCamera";
  29041. }
  29042. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29043. serializationObject.type = "AnaglyphArcRotateCamera";
  29044. }
  29045. else if (camera instanceof BABYLON.GamepadCamera) {
  29046. serializationObject.type = "GamepadCamera";
  29047. }
  29048. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29049. serializationObject.type = "AnaglyphFreeCamera";
  29050. }
  29051. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29052. serializationObject.type = "DeviceOrientationCamera";
  29053. }
  29054. else if (camera instanceof BABYLON.FollowCamera) {
  29055. serializationObject.type = "FollowCamera";
  29056. }
  29057. else if (camera instanceof BABYLON.TouchCamera) {
  29058. serializationObject.type = "TouchCamera";
  29059. }
  29060. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29061. serializationObject.type = "VirtualJoysticksCamera";
  29062. }
  29063. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29064. serializationObject.type = "WebVRFreeCamera";
  29065. }
  29066. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29067. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29068. }
  29069. //special properties of specific cameras
  29070. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29071. var arcCamera = camera;
  29072. serializationObject.alpha = arcCamera.alpha;
  29073. serializationObject.beta = arcCamera.beta;
  29074. serializationObject.radius = arcCamera.radius;
  29075. if (arcCamera.target && arcCamera.target.id) {
  29076. serializationObject.lockedTargetId = arcCamera.target.id;
  29077. }
  29078. }
  29079. else if (camera instanceof BABYLON.FollowCamera) {
  29080. var followCam = camera;
  29081. serializationObject.radius = followCam.radius;
  29082. serializationObject.heightOffset = followCam.heightOffset;
  29083. serializationObject.rotationOffset = followCam.rotationOffset;
  29084. }
  29085. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29086. //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.
  29087. if (camera['_interaxialDistance'] !== undefined) {
  29088. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29089. }
  29090. }
  29091. //general properties that not all cameras have. The [] is due to typescript's type safety
  29092. if (camera['speed'] !== undefined) {
  29093. serializationObject.speed = camera['speed'];
  29094. }
  29095. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29096. serializationObject.target = camera['target'].asArray();
  29097. }
  29098. // Target
  29099. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29100. serializationObject.rotation = camera['rotation'].asArray();
  29101. }
  29102. // Locked target
  29103. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29104. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29105. }
  29106. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29107. serializationObject.applyGravity = camera['applyGravity'] || false;
  29108. if (camera['ellipsoid']) {
  29109. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29110. }
  29111. // Animations
  29112. appendAnimations(camera, serializationObject);
  29113. // Layer mask
  29114. serializationObject.layerMask = camera.layerMask;
  29115. return serializationObject;
  29116. };
  29117. serializeAnimation = function (animation) {
  29118. var serializationObject = {};
  29119. serializationObject.name = animation.name;
  29120. serializationObject.property = animation.targetProperty;
  29121. serializationObject.framePerSecond = animation.framePerSecond;
  29122. serializationObject.dataType = animation.dataType;
  29123. serializationObject.loopBehavior = animation.loopMode;
  29124. var dataType = animation.dataType;
  29125. serializationObject.keys = [];
  29126. var keys = animation.getKeys();
  29127. for (var index = 0; index < keys.length; index++) {
  29128. var animationKey = keys[index];
  29129. var key = {};
  29130. key.frame = animationKey.frame;
  29131. switch (dataType) {
  29132. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29133. key.values = [animationKey.value];
  29134. break;
  29135. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29136. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29137. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29138. key.values = animationKey.value.asArray();
  29139. break;
  29140. }
  29141. serializationObject.keys.push(key);
  29142. }
  29143. return serializationObject;
  29144. };
  29145. var serializeMultiMaterial = function (material) {
  29146. var serializationObject = {};
  29147. serializationObject.name = material.name;
  29148. serializationObject.id = material.id;
  29149. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29150. serializationObject.materials = [];
  29151. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29152. var subMat = material.subMaterials[matIndex];
  29153. if (subMat) {
  29154. serializationObject.materials.push(subMat.id);
  29155. }
  29156. else {
  29157. serializationObject.materials.push(null);
  29158. }
  29159. }
  29160. return serializationObject;
  29161. };
  29162. var serializeTexture;
  29163. var serializeMaterial = function (material) {
  29164. var serializationObject = {};
  29165. serializationObject.name = material.name;
  29166. serializationObject.ambient = material.ambientColor.asArray();
  29167. serializationObject.diffuse = material.diffuseColor.asArray();
  29168. serializationObject.specular = material.specularColor.asArray();
  29169. serializationObject.specularPower = material.specularPower;
  29170. serializationObject.emissive = material.emissiveColor.asArray();
  29171. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29172. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29173. serializationObject.alpha = material.alpha;
  29174. serializationObject.id = material.id;
  29175. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29176. serializationObject.backFaceCulling = material.backFaceCulling;
  29177. if (material.diffuseTexture) {
  29178. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29179. }
  29180. if (material.diffuseFresnelParameters) {
  29181. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29182. }
  29183. if (material.ambientTexture) {
  29184. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29185. }
  29186. if (material.opacityTexture) {
  29187. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29188. }
  29189. if (material.opacityFresnelParameters) {
  29190. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29191. }
  29192. if (material.reflectionTexture) {
  29193. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29194. }
  29195. if (material.reflectionFresnelParameters) {
  29196. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29197. }
  29198. if (material.emissiveTexture) {
  29199. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29200. }
  29201. if (material.lightmapTexture) {
  29202. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29203. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29204. }
  29205. if (material.emissiveFresnelParameters) {
  29206. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29207. }
  29208. if (material.specularTexture) {
  29209. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29210. }
  29211. if (material.bumpTexture) {
  29212. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29213. }
  29214. return serializationObject;
  29215. };
  29216. serializeTexture = function (texture) {
  29217. var serializationObject = {};
  29218. if (!texture.name) {
  29219. return null;
  29220. }
  29221. if (texture instanceof BABYLON.CubeTexture) {
  29222. serializationObject.name = texture.name;
  29223. serializationObject.hasAlpha = texture.hasAlpha;
  29224. serializationObject.isCube = true;
  29225. serializationObject.level = texture.level;
  29226. serializationObject.coordinatesMode = texture.coordinatesMode;
  29227. return serializationObject;
  29228. }
  29229. var index;
  29230. if (texture instanceof BABYLON.MirrorTexture) {
  29231. var mirrorTexture = texture;
  29232. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29233. serializationObject.renderList = [];
  29234. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29235. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29236. }
  29237. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29238. }
  29239. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29240. var renderTargetTexture = texture;
  29241. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29242. serializationObject.renderList = [];
  29243. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29244. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29245. }
  29246. }
  29247. var regularTexture = texture;
  29248. serializationObject.name = texture.name;
  29249. serializationObject.hasAlpha = texture.hasAlpha;
  29250. serializationObject.level = texture.level;
  29251. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29252. serializationObject.coordinatesMode = texture.coordinatesMode;
  29253. serializationObject.uOffset = regularTexture.uOffset;
  29254. serializationObject.vOffset = regularTexture.vOffset;
  29255. serializationObject.uScale = regularTexture.uScale;
  29256. serializationObject.vScale = regularTexture.vScale;
  29257. serializationObject.uAng = regularTexture.uAng;
  29258. serializationObject.vAng = regularTexture.vAng;
  29259. serializationObject.wAng = regularTexture.wAng;
  29260. serializationObject.wrapU = texture.wrapU;
  29261. serializationObject.wrapV = texture.wrapV;
  29262. // Animations
  29263. appendAnimations(texture, serializationObject);
  29264. return serializationObject;
  29265. };
  29266. var serializeSkeleton = function (skeleton) {
  29267. var serializationObject = {};
  29268. serializationObject.name = skeleton.name;
  29269. serializationObject.id = skeleton.id;
  29270. serializationObject.bones = [];
  29271. for (var index = 0; index < skeleton.bones.length; index++) {
  29272. var bone = skeleton.bones[index];
  29273. var serializedBone = {
  29274. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29275. name: bone.name,
  29276. matrix: bone.getLocalMatrix().toArray()
  29277. };
  29278. serializationObject.bones.push(serializedBone);
  29279. if (bone.animations && bone.animations.length > 0) {
  29280. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29281. }
  29282. }
  29283. return serializationObject;
  29284. };
  29285. var serializeParticleSystem = function (particleSystem) {
  29286. var serializationObject = {};
  29287. serializationObject.emitterId = particleSystem.emitter.id;
  29288. serializationObject.capacity = particleSystem.getCapacity();
  29289. if (particleSystem.particleTexture) {
  29290. serializationObject.textureName = particleSystem.particleTexture.name;
  29291. }
  29292. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29293. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29294. serializationObject.minSize = particleSystem.minSize;
  29295. serializationObject.maxSize = particleSystem.maxSize;
  29296. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29297. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29298. serializationObject.emitRate = particleSystem.emitRate;
  29299. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29300. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29301. serializationObject.gravity = particleSystem.gravity.asArray();
  29302. serializationObject.direction1 = particleSystem.direction1.asArray();
  29303. serializationObject.direction2 = particleSystem.direction2.asArray();
  29304. serializationObject.color1 = particleSystem.color1.asArray();
  29305. serializationObject.color2 = particleSystem.color2.asArray();
  29306. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29307. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29308. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29309. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29310. serializationObject.blendMode = particleSystem.blendMode;
  29311. return serializationObject;
  29312. };
  29313. var serializeLensFlareSystem = function (lensFlareSystem) {
  29314. var serializationObject = {};
  29315. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29316. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29317. serializationObject.flares = [];
  29318. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29319. var flare = lensFlareSystem.lensFlares[index];
  29320. serializationObject.flares.push({
  29321. size: flare.size,
  29322. position: flare.position,
  29323. color: flare.color.asArray(),
  29324. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29325. });
  29326. }
  29327. return serializationObject;
  29328. };
  29329. var serializeShadowGenerator = function (light) {
  29330. var serializationObject = {};
  29331. var shadowGenerator = light.getShadowGenerator();
  29332. serializationObject.lightId = light.id;
  29333. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29334. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29335. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29336. serializationObject.renderList = [];
  29337. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29338. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29339. serializationObject.renderList.push(mesh.id);
  29340. }
  29341. return serializationObject;
  29342. };
  29343. var serializedGeometries = [];
  29344. var serializeVertexData;
  29345. var serializeTorusKnot;
  29346. var serializePlane;
  29347. var serializeGround;
  29348. var serializeTorus;
  29349. var serializeCylinder;
  29350. var serializeSphere;
  29351. var serializeBox;
  29352. var serializeGeometry = function (geometry, serializationGeometries) {
  29353. if (serializedGeometries[geometry.id]) {
  29354. return;
  29355. }
  29356. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29357. serializationGeometries.boxes.push(serializeBox(geometry));
  29358. }
  29359. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29360. serializationGeometries.spheres.push(serializeSphere(geometry));
  29361. }
  29362. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29363. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29364. }
  29365. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29366. serializationGeometries.toruses.push(serializeTorus(geometry));
  29367. }
  29368. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29369. serializationGeometries.grounds.push(serializeGround(geometry));
  29370. }
  29371. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29372. serializationGeometries.planes.push(serializePlane(geometry));
  29373. }
  29374. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29375. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29376. }
  29377. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29378. throw new Error("Unknown primitive type");
  29379. }
  29380. else {
  29381. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29382. }
  29383. serializedGeometries[geometry.id] = true;
  29384. };
  29385. var serializeGeometryBase = function (geometry) {
  29386. var serializationObject = {};
  29387. serializationObject.id = geometry.id;
  29388. if (BABYLON.Tags.HasTags(geometry)) {
  29389. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29390. }
  29391. return serializationObject;
  29392. };
  29393. serializeVertexData = function (vertexData) {
  29394. var serializationObject = serializeGeometryBase(vertexData);
  29395. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29396. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29397. }
  29398. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29399. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29400. }
  29401. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29402. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29403. }
  29404. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29405. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29406. }
  29407. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29408. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29409. }
  29410. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29411. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29412. }
  29413. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29414. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29415. }
  29416. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29417. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29418. }
  29419. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29420. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29421. }
  29422. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29423. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29424. serializationObject.matricesIndices._isExpanded = true;
  29425. }
  29426. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29427. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29428. }
  29429. serializationObject.indices = vertexData.getIndices();
  29430. return serializationObject;
  29431. };
  29432. var serializePrimitive = function (primitive) {
  29433. var serializationObject = serializeGeometryBase(primitive);
  29434. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29435. return serializationObject;
  29436. };
  29437. serializeBox = function (box) {
  29438. var serializationObject = serializePrimitive(box);
  29439. serializationObject.size = box.size;
  29440. return serializationObject;
  29441. };
  29442. serializeSphere = function (sphere) {
  29443. var serializationObject = serializePrimitive(sphere);
  29444. serializationObject.segments = sphere.segments;
  29445. serializationObject.diameter = sphere.diameter;
  29446. return serializationObject;
  29447. };
  29448. serializeCylinder = function (cylinder) {
  29449. var serializationObject = serializePrimitive(cylinder);
  29450. serializationObject.height = cylinder.height;
  29451. serializationObject.diameterTop = cylinder.diameterTop;
  29452. serializationObject.diameterBottom = cylinder.diameterBottom;
  29453. serializationObject.tessellation = cylinder.tessellation;
  29454. return serializationObject;
  29455. };
  29456. serializeTorus = function (torus) {
  29457. var serializationObject = serializePrimitive(torus);
  29458. serializationObject.diameter = torus.diameter;
  29459. serializationObject.thickness = torus.thickness;
  29460. serializationObject.tessellation = torus.tessellation;
  29461. return serializationObject;
  29462. };
  29463. serializeGround = function (ground) {
  29464. var serializationObject = serializePrimitive(ground);
  29465. serializationObject.width = ground.width;
  29466. serializationObject.height = ground.height;
  29467. serializationObject.subdivisions = ground.subdivisions;
  29468. return serializationObject;
  29469. };
  29470. serializePlane = function (plane) {
  29471. var serializationObject = serializePrimitive(plane);
  29472. serializationObject.size = plane.size;
  29473. return serializationObject;
  29474. };
  29475. serializeTorusKnot = function (torusKnot) {
  29476. var serializationObject = serializePrimitive(torusKnot);
  29477. serializationObject.radius = torusKnot.radius;
  29478. serializationObject.tube = torusKnot.tube;
  29479. serializationObject.radialSegments = torusKnot.radialSegments;
  29480. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29481. serializationObject.p = torusKnot.p;
  29482. serializationObject.q = torusKnot.q;
  29483. return serializationObject;
  29484. };
  29485. var serializeMesh = function (mesh, serializationScene) {
  29486. var serializationObject = {};
  29487. serializationObject.name = mesh.name;
  29488. serializationObject.id = mesh.id;
  29489. if (BABYLON.Tags.HasTags(mesh)) {
  29490. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29491. }
  29492. serializationObject.position = mesh.position.asArray();
  29493. if (mesh.rotationQuaternion) {
  29494. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29495. }
  29496. else if (mesh.rotation) {
  29497. serializationObject.rotation = mesh.rotation.asArray();
  29498. }
  29499. serializationObject.scaling = mesh.scaling.asArray();
  29500. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29501. serializationObject.isEnabled = mesh.isEnabled();
  29502. serializationObject.isVisible = mesh.isVisible;
  29503. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29504. serializationObject.pickable = mesh.isPickable;
  29505. serializationObject.receiveShadows = mesh.receiveShadows;
  29506. serializationObject.billboardMode = mesh.billboardMode;
  29507. serializationObject.visibility = mesh.visibility;
  29508. serializationObject.checkCollisions = mesh.checkCollisions;
  29509. // Parent
  29510. if (mesh.parent) {
  29511. serializationObject.parentId = mesh.parent.id;
  29512. }
  29513. // Geometry
  29514. var geometry = mesh._geometry;
  29515. if (geometry) {
  29516. var geometryId = geometry.id;
  29517. serializationObject.geometryId = geometryId;
  29518. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29519. // 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
  29520. serializeGeometry(geometry, serializationScene.geometries);
  29521. }
  29522. // SubMeshes
  29523. serializationObject.subMeshes = [];
  29524. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29525. var subMesh = mesh.subMeshes[subIndex];
  29526. serializationObject.subMeshes.push({
  29527. materialIndex: subMesh.materialIndex,
  29528. verticesStart: subMesh.verticesStart,
  29529. verticesCount: subMesh.verticesCount,
  29530. indexStart: subMesh.indexStart,
  29531. indexCount: subMesh.indexCount
  29532. });
  29533. }
  29534. }
  29535. // Material
  29536. if (mesh.material) {
  29537. serializationObject.materialId = mesh.material.id;
  29538. }
  29539. else {
  29540. mesh.material = null;
  29541. }
  29542. // Skeleton
  29543. if (mesh.skeleton) {
  29544. serializationObject.skeletonId = mesh.skeleton.id;
  29545. }
  29546. // Physics
  29547. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29548. serializationObject.physicsMass = mesh.getPhysicsMass();
  29549. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29550. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29551. switch (mesh.getPhysicsImpostor()) {
  29552. case BABYLON.PhysicsEngine.BoxImpostor:
  29553. serializationObject.physicsImpostor = 1;
  29554. break;
  29555. case BABYLON.PhysicsEngine.SphereImpostor:
  29556. serializationObject.physicsImpostor = 2;
  29557. break;
  29558. }
  29559. }
  29560. // Instances
  29561. serializationObject.instances = [];
  29562. for (var index = 0; index < mesh.instances.length; index++) {
  29563. var instance = mesh.instances[index];
  29564. var serializationInstance = {
  29565. name: instance.name,
  29566. position: instance.position.asArray(),
  29567. rotation: instance.rotation.asArray(),
  29568. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29569. scaling: instance.scaling.asArray()
  29570. };
  29571. serializationObject.instances.push(serializationInstance);
  29572. // Animations
  29573. appendAnimations(instance, serializationInstance);
  29574. }
  29575. // Animations
  29576. appendAnimations(mesh, serializationObject);
  29577. // Layer mask
  29578. serializationObject.layerMask = mesh.layerMask;
  29579. return serializationObject;
  29580. };
  29581. var finalizeSingleMesh = function (mesh, serializationObject) {
  29582. //only works if the mesh is already loaded
  29583. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29584. //serialize material
  29585. if (mesh.material) {
  29586. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29587. serializationObject.materials = serializationObject.materials || [];
  29588. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29589. serializationObject.materials.push(serializeMaterial(mesh.material));
  29590. }
  29591. }
  29592. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29593. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29594. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29595. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  29596. }
  29597. }
  29598. }
  29599. //serialize geometry
  29600. var geometry = mesh._geometry;
  29601. if (geometry) {
  29602. if (!serializationObject.geometries) {
  29603. serializationObject.geometries = {};
  29604. serializationObject.geometries.boxes = [];
  29605. serializationObject.geometries.spheres = [];
  29606. serializationObject.geometries.cylinders = [];
  29607. serializationObject.geometries.toruses = [];
  29608. serializationObject.geometries.grounds = [];
  29609. serializationObject.geometries.planes = [];
  29610. serializationObject.geometries.torusKnots = [];
  29611. serializationObject.geometries.vertexData = [];
  29612. }
  29613. serializeGeometry(geometry, serializationObject.geometries);
  29614. }
  29615. // Skeletons
  29616. if (mesh.skeleton) {
  29617. serializationObject.skeletons = serializationObject.skeletons || [];
  29618. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  29619. }
  29620. //serialize the actual mesh
  29621. serializationObject.meshes = serializationObject.meshes || [];
  29622. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29623. }
  29624. };
  29625. var SceneSerializer = (function () {
  29626. function SceneSerializer() {
  29627. }
  29628. SceneSerializer.Serialize = function (scene) {
  29629. var serializationObject = {};
  29630. // Scene
  29631. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  29632. serializationObject.autoClear = scene.autoClear;
  29633. serializationObject.clearColor = scene.clearColor.asArray();
  29634. serializationObject.ambientColor = scene.ambientColor.asArray();
  29635. serializationObject.gravity = scene.gravity.asArray();
  29636. // Fog
  29637. if (scene.fogMode && scene.fogMode !== 0) {
  29638. serializationObject.fogMode = scene.fogMode;
  29639. serializationObject.fogColor = scene.fogColor.asArray();
  29640. serializationObject.fogStart = scene.fogStart;
  29641. serializationObject.fogEnd = scene.fogEnd;
  29642. serializationObject.fogDensity = scene.fogDensity;
  29643. }
  29644. // Lights
  29645. serializationObject.lights = [];
  29646. var index;
  29647. var light;
  29648. for (index = 0; index < scene.lights.length; index++) {
  29649. light = scene.lights[index];
  29650. serializationObject.lights.push(serializeLight(light));
  29651. }
  29652. // Cameras
  29653. serializationObject.cameras = [];
  29654. for (index = 0; index < scene.cameras.length; index++) {
  29655. var camera = scene.cameras[index];
  29656. serializationObject.cameras.push(serializeCamera(camera));
  29657. }
  29658. if (scene.activeCamera) {
  29659. serializationObject.activeCameraID = scene.activeCamera.id;
  29660. }
  29661. // Materials
  29662. serializationObject.materials = [];
  29663. serializationObject.multiMaterials = [];
  29664. var material;
  29665. for (index = 0; index < scene.materials.length; index++) {
  29666. material = scene.materials[index];
  29667. serializationObject.materials.push(serializeMaterial(material));
  29668. }
  29669. // MultiMaterials
  29670. serializationObject.multiMaterials = [];
  29671. for (index = 0; index < scene.multiMaterials.length; index++) {
  29672. var multiMaterial = scene.multiMaterials[index];
  29673. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  29674. }
  29675. for (index = 0; index < scene.materials.length; index++) {
  29676. material = scene.materials[index];
  29677. if (material instanceof BABYLON.StandardMaterial) {
  29678. serializationObject.materials.push(serializeMaterial(material));
  29679. }
  29680. else if (material instanceof BABYLON.MultiMaterial) {
  29681. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  29682. }
  29683. }
  29684. // Skeletons
  29685. serializationObject.skeletons = [];
  29686. for (index = 0; index < scene.skeletons.length; index++) {
  29687. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  29688. }
  29689. // Geometries
  29690. serializationObject.geometries = {};
  29691. serializationObject.geometries.boxes = [];
  29692. serializationObject.geometries.spheres = [];
  29693. serializationObject.geometries.cylinders = [];
  29694. serializationObject.geometries.toruses = [];
  29695. serializationObject.geometries.grounds = [];
  29696. serializationObject.geometries.planes = [];
  29697. serializationObject.geometries.torusKnots = [];
  29698. serializationObject.geometries.vertexData = [];
  29699. serializedGeometries = [];
  29700. var geometries = scene.getGeometries();
  29701. for (index = 0; index < geometries.length; index++) {
  29702. var geometry = geometries[index];
  29703. if (geometry.isReady()) {
  29704. serializeGeometry(geometry, serializationObject.geometries);
  29705. }
  29706. }
  29707. // Meshes
  29708. serializationObject.meshes = [];
  29709. for (index = 0; index < scene.meshes.length; index++) {
  29710. var abstractMesh = scene.meshes[index];
  29711. if (abstractMesh instanceof BABYLON.Mesh) {
  29712. var mesh = abstractMesh;
  29713. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29714. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29715. }
  29716. }
  29717. }
  29718. // Particles Systems
  29719. serializationObject.particleSystems = [];
  29720. for (index = 0; index < scene.particleSystems.length; index++) {
  29721. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  29722. }
  29723. // Lens flares
  29724. serializationObject.lensFlareSystems = [];
  29725. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  29726. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  29727. }
  29728. // Shadows
  29729. serializationObject.shadowGenerators = [];
  29730. for (index = 0; index < scene.lights.length; index++) {
  29731. light = scene.lights[index];
  29732. if (light.getShadowGenerator()) {
  29733. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  29734. }
  29735. }
  29736. return serializationObject;
  29737. };
  29738. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  29739. if (withParents === void 0) { withParents = false; }
  29740. if (withChildren === void 0) { withChildren = false; }
  29741. var serializationObject = {};
  29742. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  29743. if (withParents || withChildren) {
  29744. //deliberate for loop! not for each, appended should be processed as well.
  29745. for (var i = 0; i < toSerialize.length; ++i) {
  29746. if (withChildren) {
  29747. toSerialize[i].getDescendants().forEach(function (node) {
  29748. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  29749. toSerialize.push(node);
  29750. }
  29751. });
  29752. }
  29753. //make sure the array doesn't contain the object already
  29754. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  29755. toSerialize.push(toSerialize[i].parent);
  29756. }
  29757. }
  29758. }
  29759. toSerialize.forEach(function (mesh) {
  29760. finalizeSingleMesh(mesh, serializationObject);
  29761. });
  29762. return serializationObject;
  29763. };
  29764. return SceneSerializer;
  29765. })();
  29766. BABYLON.SceneSerializer = SceneSerializer;
  29767. })(BABYLON || (BABYLON = {}));
  29768. var BABYLON;
  29769. (function (BABYLON) {
  29770. // Unique ID when we import meshes from Babylon to CSG
  29771. var currentCSGMeshId = 0;
  29772. // # class Vertex
  29773. // Represents a vertex of a polygon. Use your own vertex class instead of this
  29774. // one to provide additional features like texture coordinates and vertex
  29775. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  29776. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  29777. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  29778. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  29779. // is not used anywhere else.
  29780. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  29781. var Vertex = (function () {
  29782. function Vertex(pos, normal, uv) {
  29783. this.pos = pos;
  29784. this.normal = normal;
  29785. this.uv = uv;
  29786. }
  29787. Vertex.prototype.clone = function () {
  29788. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  29789. };
  29790. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  29791. // orientation of a polygon is flipped.
  29792. Vertex.prototype.flip = function () {
  29793. this.normal = this.normal.scale(-1);
  29794. };
  29795. // Create a new vertex between this vertex and `other` by linearly
  29796. // interpolating all properties using a parameter of `t`. Subclasses should
  29797. // override this to interpolate additional properties.
  29798. Vertex.prototype.interpolate = function (other, t) {
  29799. 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));
  29800. };
  29801. return Vertex;
  29802. })();
  29803. // # class Plane
  29804. // Represents a plane in 3D space.
  29805. var Plane = (function () {
  29806. function Plane(normal, w) {
  29807. this.normal = normal;
  29808. this.w = w;
  29809. }
  29810. Plane.FromPoints = function (a, b, c) {
  29811. var v0 = c.subtract(a);
  29812. var v1 = b.subtract(a);
  29813. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  29814. return null;
  29815. }
  29816. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  29817. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  29818. };
  29819. Plane.prototype.clone = function () {
  29820. return new Plane(this.normal.clone(), this.w);
  29821. };
  29822. Plane.prototype.flip = function () {
  29823. this.normal.scaleInPlace(-1);
  29824. this.w = -this.w;
  29825. };
  29826. // Split `polygon` by this plane if needed, then put the polygon or polygon
  29827. // fragments in the appropriate lists. Coplanar polygons go into either
  29828. // `coplanarFront` or `coplanarBack` depending on their orientation with
  29829. // respect to this plane. Polygons in front or in back of this plane go into
  29830. // either `front` or `back`.
  29831. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  29832. var COPLANAR = 0;
  29833. var FRONT = 1;
  29834. var BACK = 2;
  29835. var SPANNING = 3;
  29836. // Classify each point as well as the entire polygon into one of the above
  29837. // four classes.
  29838. var polygonType = 0;
  29839. var types = [];
  29840. var i;
  29841. var t;
  29842. for (i = 0; i < polygon.vertices.length; i++) {
  29843. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  29844. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  29845. polygonType |= type;
  29846. types.push(type);
  29847. }
  29848. // Put the polygon in the correct list, splitting it when necessary.
  29849. switch (polygonType) {
  29850. case COPLANAR:
  29851. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  29852. break;
  29853. case FRONT:
  29854. front.push(polygon);
  29855. break;
  29856. case BACK:
  29857. back.push(polygon);
  29858. break;
  29859. case SPANNING:
  29860. var f = [], b = [];
  29861. for (i = 0; i < polygon.vertices.length; i++) {
  29862. var j = (i + 1) % polygon.vertices.length;
  29863. var ti = types[i], tj = types[j];
  29864. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  29865. if (ti !== BACK)
  29866. f.push(vi);
  29867. if (ti !== FRONT)
  29868. b.push(ti !== BACK ? vi.clone() : vi);
  29869. if ((ti | tj) === SPANNING) {
  29870. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  29871. var v = vi.interpolate(vj, t);
  29872. f.push(v);
  29873. b.push(v.clone());
  29874. }
  29875. }
  29876. var poly;
  29877. if (f.length >= 3) {
  29878. poly = new Polygon(f, polygon.shared);
  29879. if (poly.plane)
  29880. front.push(poly);
  29881. }
  29882. if (b.length >= 3) {
  29883. poly = new Polygon(b, polygon.shared);
  29884. if (poly.plane)
  29885. back.push(poly);
  29886. }
  29887. break;
  29888. }
  29889. };
  29890. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  29891. // point is on the plane.
  29892. Plane.EPSILON = 1e-5;
  29893. return Plane;
  29894. })();
  29895. // # class Polygon
  29896. // Represents a convex polygon. The vertices used to initialize a polygon must
  29897. // be coplanar and form a convex loop.
  29898. //
  29899. // Each convex polygon has a `shared` property, which is shared between all
  29900. // polygons that are clones of each other or were split from the same polygon.
  29901. // This can be used to define per-polygon properties (such as surface color).
  29902. var Polygon = (function () {
  29903. function Polygon(vertices, shared) {
  29904. this.vertices = vertices;
  29905. this.shared = shared;
  29906. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  29907. }
  29908. Polygon.prototype.clone = function () {
  29909. var vertices = this.vertices.map(function (v) { return v.clone(); });
  29910. return new Polygon(vertices, this.shared);
  29911. };
  29912. Polygon.prototype.flip = function () {
  29913. this.vertices.reverse().map(function (v) { v.flip(); });
  29914. this.plane.flip();
  29915. };
  29916. return Polygon;
  29917. })();
  29918. // # class Node
  29919. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  29920. // by picking a polygon to split along. That polygon (and all other coplanar
  29921. // polygons) are added directly to that node and the other polygons are added to
  29922. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  29923. // no distinction between internal and leaf nodes.
  29924. var Node = (function () {
  29925. function Node(polygons) {
  29926. this.plane = null;
  29927. this.front = null;
  29928. this.back = null;
  29929. this.polygons = [];
  29930. if (polygons) {
  29931. this.build(polygons);
  29932. }
  29933. }
  29934. Node.prototype.clone = function () {
  29935. var node = new Node();
  29936. node.plane = this.plane && this.plane.clone();
  29937. node.front = this.front && this.front.clone();
  29938. node.back = this.back && this.back.clone();
  29939. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  29940. return node;
  29941. };
  29942. // Convert solid space to empty space and empty space to solid space.
  29943. Node.prototype.invert = function () {
  29944. for (var i = 0; i < this.polygons.length; i++) {
  29945. this.polygons[i].flip();
  29946. }
  29947. if (this.plane) {
  29948. this.plane.flip();
  29949. }
  29950. if (this.front) {
  29951. this.front.invert();
  29952. }
  29953. if (this.back) {
  29954. this.back.invert();
  29955. }
  29956. var temp = this.front;
  29957. this.front = this.back;
  29958. this.back = temp;
  29959. };
  29960. // Recursively remove all polygons in `polygons` that are inside this BSP
  29961. // tree.
  29962. Node.prototype.clipPolygons = function (polygons) {
  29963. if (!this.plane)
  29964. return polygons.slice();
  29965. var front = [], back = [];
  29966. for (var i = 0; i < polygons.length; i++) {
  29967. this.plane.splitPolygon(polygons[i], front, back, front, back);
  29968. }
  29969. if (this.front) {
  29970. front = this.front.clipPolygons(front);
  29971. }
  29972. if (this.back) {
  29973. back = this.back.clipPolygons(back);
  29974. }
  29975. else {
  29976. back = [];
  29977. }
  29978. return front.concat(back);
  29979. };
  29980. // Remove all polygons in this BSP tree that are inside the other BSP tree
  29981. // `bsp`.
  29982. Node.prototype.clipTo = function (bsp) {
  29983. this.polygons = bsp.clipPolygons(this.polygons);
  29984. if (this.front)
  29985. this.front.clipTo(bsp);
  29986. if (this.back)
  29987. this.back.clipTo(bsp);
  29988. };
  29989. // Return a list of all polygons in this BSP tree.
  29990. Node.prototype.allPolygons = function () {
  29991. var polygons = this.polygons.slice();
  29992. if (this.front)
  29993. polygons = polygons.concat(this.front.allPolygons());
  29994. if (this.back)
  29995. polygons = polygons.concat(this.back.allPolygons());
  29996. return polygons;
  29997. };
  29998. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  29999. // new polygons are filtered down to the bottom of the tree and become new
  30000. // nodes there. Each set of polygons is partitioned using the first polygon
  30001. // (no heuristic is used to pick a good split).
  30002. Node.prototype.build = function (polygons) {
  30003. if (!polygons.length)
  30004. return;
  30005. if (!this.plane)
  30006. this.plane = polygons[0].plane.clone();
  30007. var front = [], back = [];
  30008. for (var i = 0; i < polygons.length; i++) {
  30009. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30010. }
  30011. if (front.length) {
  30012. if (!this.front)
  30013. this.front = new Node();
  30014. this.front.build(front);
  30015. }
  30016. if (back.length) {
  30017. if (!this.back)
  30018. this.back = new Node();
  30019. this.back.build(back);
  30020. }
  30021. };
  30022. return Node;
  30023. })();
  30024. var CSG = (function () {
  30025. function CSG() {
  30026. this.polygons = new Array();
  30027. }
  30028. // Convert BABYLON.Mesh to BABYLON.CSG
  30029. CSG.FromMesh = function (mesh) {
  30030. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30031. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30032. if (mesh instanceof BABYLON.Mesh) {
  30033. mesh.computeWorldMatrix(true);
  30034. matrix = mesh.getWorldMatrix();
  30035. meshPosition = mesh.position.clone();
  30036. meshRotation = mesh.rotation.clone();
  30037. if (mesh.rotationQuaternion) {
  30038. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30039. }
  30040. meshScaling = mesh.scaling.clone();
  30041. }
  30042. else {
  30043. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30044. }
  30045. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30046. var subMeshes = mesh.subMeshes;
  30047. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30048. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30049. vertices = [];
  30050. for (var j = 0; j < 3; j++) {
  30051. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30052. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30053. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30054. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30055. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30056. vertex = new Vertex(position, normal, uv);
  30057. vertices.push(vertex);
  30058. }
  30059. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30060. // To handle the case of degenerated triangle
  30061. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30062. if (polygon.plane)
  30063. polygons.push(polygon);
  30064. }
  30065. }
  30066. var csg = CSG.FromPolygons(polygons);
  30067. csg.matrix = matrix;
  30068. csg.position = meshPosition;
  30069. csg.rotation = meshRotation;
  30070. csg.scaling = meshScaling;
  30071. csg.rotationQuaternion = meshRotationQuaternion;
  30072. currentCSGMeshId++;
  30073. return csg;
  30074. };
  30075. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30076. CSG.FromPolygons = function (polygons) {
  30077. var csg = new CSG();
  30078. csg.polygons = polygons;
  30079. return csg;
  30080. };
  30081. CSG.prototype.clone = function () {
  30082. var csg = new CSG();
  30083. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30084. csg.copyTransformAttributes(this);
  30085. return csg;
  30086. };
  30087. CSG.prototype.toPolygons = function () {
  30088. return this.polygons;
  30089. };
  30090. CSG.prototype.union = function (csg) {
  30091. var a = new Node(this.clone().polygons);
  30092. var b = new Node(csg.clone().polygons);
  30093. a.clipTo(b);
  30094. b.clipTo(a);
  30095. b.invert();
  30096. b.clipTo(a);
  30097. b.invert();
  30098. a.build(b.allPolygons());
  30099. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30100. };
  30101. CSG.prototype.unionInPlace = function (csg) {
  30102. var a = new Node(this.polygons);
  30103. var b = new Node(csg.polygons);
  30104. a.clipTo(b);
  30105. b.clipTo(a);
  30106. b.invert();
  30107. b.clipTo(a);
  30108. b.invert();
  30109. a.build(b.allPolygons());
  30110. this.polygons = a.allPolygons();
  30111. };
  30112. CSG.prototype.subtract = function (csg) {
  30113. var a = new Node(this.clone().polygons);
  30114. var b = new Node(csg.clone().polygons);
  30115. a.invert();
  30116. a.clipTo(b);
  30117. b.clipTo(a);
  30118. b.invert();
  30119. b.clipTo(a);
  30120. b.invert();
  30121. a.build(b.allPolygons());
  30122. a.invert();
  30123. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30124. };
  30125. CSG.prototype.subtractInPlace = function (csg) {
  30126. var a = new Node(this.polygons);
  30127. var b = new Node(csg.polygons);
  30128. a.invert();
  30129. a.clipTo(b);
  30130. b.clipTo(a);
  30131. b.invert();
  30132. b.clipTo(a);
  30133. b.invert();
  30134. a.build(b.allPolygons());
  30135. a.invert();
  30136. this.polygons = a.allPolygons();
  30137. };
  30138. CSG.prototype.intersect = function (csg) {
  30139. var a = new Node(this.clone().polygons);
  30140. var b = new Node(csg.clone().polygons);
  30141. a.invert();
  30142. b.clipTo(a);
  30143. b.invert();
  30144. a.clipTo(b);
  30145. b.clipTo(a);
  30146. a.build(b.allPolygons());
  30147. a.invert();
  30148. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30149. };
  30150. CSG.prototype.intersectInPlace = function (csg) {
  30151. var a = new Node(this.polygons);
  30152. var b = new Node(csg.polygons);
  30153. a.invert();
  30154. b.clipTo(a);
  30155. b.invert();
  30156. a.clipTo(b);
  30157. b.clipTo(a);
  30158. a.build(b.allPolygons());
  30159. a.invert();
  30160. this.polygons = a.allPolygons();
  30161. };
  30162. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30163. // not modified.
  30164. CSG.prototype.inverse = function () {
  30165. var csg = this.clone();
  30166. csg.inverseInPlace();
  30167. return csg;
  30168. };
  30169. CSG.prototype.inverseInPlace = function () {
  30170. this.polygons.map(function (p) { p.flip(); });
  30171. };
  30172. // This is used to keep meshes transformations so they can be restored
  30173. // when we build back a Babylon Mesh
  30174. // NB : All CSG operations are performed in world coordinates
  30175. CSG.prototype.copyTransformAttributes = function (csg) {
  30176. this.matrix = csg.matrix;
  30177. this.position = csg.position;
  30178. this.rotation = csg.rotation;
  30179. this.scaling = csg.scaling;
  30180. this.rotationQuaternion = csg.rotationQuaternion;
  30181. return this;
  30182. };
  30183. // Build Raw mesh from CSG
  30184. // Coordinates here are in world space
  30185. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30186. var matrix = this.matrix.clone();
  30187. matrix.invert();
  30188. 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;
  30189. if (keepSubMeshes) {
  30190. // Sort Polygons, since subMeshes are indices range
  30191. polygons.sort(function (a, b) {
  30192. if (a.shared.meshId === b.shared.meshId) {
  30193. return a.shared.subMeshId - b.shared.subMeshId;
  30194. }
  30195. else {
  30196. return a.shared.meshId - b.shared.meshId;
  30197. }
  30198. });
  30199. }
  30200. for (var i = 0, il = polygons.length; i < il; i++) {
  30201. polygon = polygons[i];
  30202. // Building SubMeshes
  30203. if (!subMesh_dict[polygon.shared.meshId]) {
  30204. subMesh_dict[polygon.shared.meshId] = {};
  30205. }
  30206. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30207. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30208. indexStart: +Infinity,
  30209. indexEnd: -Infinity,
  30210. materialIndex: polygon.shared.materialIndex
  30211. };
  30212. }
  30213. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30214. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30215. polygonIndices[0] = 0;
  30216. polygonIndices[1] = j - 1;
  30217. polygonIndices[2] = j;
  30218. for (var k = 0; k < 3; k++) {
  30219. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30220. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30221. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30222. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30223. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30224. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30225. // Check if 2 points can be merged
  30226. if (!(typeof vertex_idx !== 'undefined' &&
  30227. normals[vertex_idx * 3] === localNormal.x &&
  30228. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30229. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30230. uvs[vertex_idx * 2] === uv.x &&
  30231. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30232. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30233. uvs.push(uv.x, uv.y);
  30234. normals.push(normal.x, normal.y, normal.z);
  30235. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30236. }
  30237. indices.push(vertex_idx);
  30238. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30239. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30240. currentIndex++;
  30241. }
  30242. }
  30243. }
  30244. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30245. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30246. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30247. mesh.setIndices(indices);
  30248. if (keepSubMeshes) {
  30249. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30250. var materialIndexOffset = 0, materialMaxIndex;
  30251. mesh.subMeshes = new Array();
  30252. for (var m in subMesh_dict) {
  30253. materialMaxIndex = -1;
  30254. for (var sm in subMesh_dict[m]) {
  30255. subMesh_obj = subMesh_dict[m][sm];
  30256. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30257. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30258. }
  30259. materialIndexOffset += ++materialMaxIndex;
  30260. }
  30261. }
  30262. return mesh;
  30263. };
  30264. // Build Mesh from CSG taking material and transforms into account
  30265. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30266. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30267. mesh.material = material;
  30268. mesh.position.copyFrom(this.position);
  30269. mesh.rotation.copyFrom(this.rotation);
  30270. if (this.rotationQuaternion) {
  30271. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30272. }
  30273. mesh.scaling.copyFrom(this.scaling);
  30274. mesh.computeWorldMatrix(true);
  30275. return mesh;
  30276. };
  30277. return CSG;
  30278. })();
  30279. BABYLON.CSG = CSG;
  30280. })(BABYLON || (BABYLON = {}));
  30281. var BABYLON;
  30282. (function (BABYLON) {
  30283. var VRDistortionCorrectionPostProcess = (function (_super) {
  30284. __extends(VRDistortionCorrectionPostProcess, _super);
  30285. //ANY
  30286. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30287. var _this = this;
  30288. _super.call(this, name, "vrDistortionCorrection", [
  30289. 'LensCenter',
  30290. 'Scale',
  30291. 'ScaleIn',
  30292. 'HmdWarpParam'
  30293. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30294. this._isRightEye = isRightEye;
  30295. this._distortionFactors = vrMetrics.distortionK;
  30296. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30297. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30298. this.onSizeChanged = function () {
  30299. _this.aspectRatio = _this.width * .5 / _this.height;
  30300. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30301. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30302. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30303. };
  30304. this.onApply = function (effect) {
  30305. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30306. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30307. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30308. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30309. };
  30310. }
  30311. return VRDistortionCorrectionPostProcess;
  30312. })(BABYLON.PostProcess);
  30313. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30314. })(BABYLON || (BABYLON = {}));
  30315. // Mainly based on these 2 articles :
  30316. // 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
  30317. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30318. var BABYLON;
  30319. (function (BABYLON) {
  30320. (function (JoystickAxis) {
  30321. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30322. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30323. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30324. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30325. var JoystickAxis = BABYLON.JoystickAxis;
  30326. var VirtualJoystick = (function () {
  30327. function VirtualJoystick(leftJoystick) {
  30328. var _this = this;
  30329. if (leftJoystick) {
  30330. this._leftJoystick = true;
  30331. }
  30332. else {
  30333. this._leftJoystick = false;
  30334. }
  30335. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30336. VirtualJoystick._globalJoystickIndex++;
  30337. // By default left & right arrow keys are moving the X
  30338. // and up & down keys are moving the Y
  30339. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30340. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30341. this.reverseLeftRight = false;
  30342. this.reverseUpDown = false;
  30343. // collections of pointers
  30344. this._touches = new BABYLON.SmartCollection();
  30345. this.deltaPosition = BABYLON.Vector3.Zero();
  30346. this._joystickSensibility = 25;
  30347. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30348. this._rotationSpeed = 25;
  30349. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30350. this._rotateOnAxisRelativeToMesh = false;
  30351. this._onResize = function (evt) {
  30352. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30353. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30354. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30355. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30356. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30357. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30358. };
  30359. // injecting a canvas element on top of the canvas 3D game
  30360. if (!VirtualJoystick.vjCanvas) {
  30361. window.addEventListener("resize", this._onResize, false);
  30362. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30363. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30364. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30365. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30366. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30367. VirtualJoystick.vjCanvas.style.width = "100%";
  30368. VirtualJoystick.vjCanvas.style.height = "100%";
  30369. VirtualJoystick.vjCanvas.style.position = "absolute";
  30370. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30371. VirtualJoystick.vjCanvas.style.top = "0px";
  30372. VirtualJoystick.vjCanvas.style.left = "0px";
  30373. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30374. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30375. // Support for jQuery PEP polyfill
  30376. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30377. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30378. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30379. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30380. document.body.appendChild(VirtualJoystick.vjCanvas);
  30381. }
  30382. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30383. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30384. this.pressed = false;
  30385. // default joystick color
  30386. this._joystickColor = "cyan";
  30387. this._joystickPointerID = -1;
  30388. // current joystick position
  30389. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30390. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30391. // origin joystick position
  30392. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30393. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30394. this._onPointerDownHandlerRef = function (evt) {
  30395. _this._onPointerDown(evt);
  30396. };
  30397. this._onPointerMoveHandlerRef = function (evt) {
  30398. _this._onPointerMove(evt);
  30399. };
  30400. this._onPointerOutHandlerRef = function (evt) {
  30401. _this._onPointerUp(evt);
  30402. };
  30403. this._onPointerUpHandlerRef = function (evt) {
  30404. _this._onPointerUp(evt);
  30405. };
  30406. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30407. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30408. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30409. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30410. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30411. evt.preventDefault(); // Disables system menu
  30412. }, false);
  30413. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30414. }
  30415. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30416. this._joystickSensibility = newJoystickSensibility;
  30417. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30418. };
  30419. VirtualJoystick.prototype._onPointerDown = function (e) {
  30420. var positionOnScreenCondition;
  30421. e.preventDefault();
  30422. if (this._leftJoystick === true) {
  30423. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30424. }
  30425. else {
  30426. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30427. }
  30428. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30429. // First contact will be dedicated to the virtual joystick
  30430. this._joystickPointerID = e.pointerId;
  30431. this._joystickPointerStartPos.x = e.clientX;
  30432. this._joystickPointerStartPos.y = e.clientY;
  30433. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30434. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30435. this._deltaJoystickVector.x = 0;
  30436. this._deltaJoystickVector.y = 0;
  30437. this.pressed = true;
  30438. this._touches.add(e.pointerId.toString(), e);
  30439. }
  30440. else {
  30441. // You can only trigger the action buttons with a joystick declared
  30442. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30443. this._action();
  30444. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30445. }
  30446. }
  30447. };
  30448. VirtualJoystick.prototype._onPointerMove = function (e) {
  30449. // If the current pointer is the one associated to the joystick (first touch contact)
  30450. if (this._joystickPointerID == e.pointerId) {
  30451. this._joystickPointerPos.x = e.clientX;
  30452. this._joystickPointerPos.y = e.clientY;
  30453. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30454. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30455. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30456. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30457. switch (this._axisTargetedByLeftAndRight) {
  30458. case JoystickAxis.X:
  30459. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30460. break;
  30461. case JoystickAxis.Y:
  30462. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30463. break;
  30464. case JoystickAxis.Z:
  30465. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30466. break;
  30467. }
  30468. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30469. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30470. switch (this._axisTargetedByUpAndDown) {
  30471. case JoystickAxis.X:
  30472. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30473. break;
  30474. case JoystickAxis.Y:
  30475. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30476. break;
  30477. case JoystickAxis.Z:
  30478. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30479. break;
  30480. }
  30481. }
  30482. else {
  30483. if (this._touches.item(e.pointerId.toString())) {
  30484. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30485. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30486. }
  30487. }
  30488. };
  30489. VirtualJoystick.prototype._onPointerUp = function (e) {
  30490. if (this._joystickPointerID == e.pointerId) {
  30491. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30492. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30493. this._joystickPointerID = -1;
  30494. this.pressed = false;
  30495. }
  30496. else {
  30497. var touch = this._touches.item(e.pointerId.toString());
  30498. if (touch) {
  30499. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30500. }
  30501. }
  30502. this._deltaJoystickVector.x = 0;
  30503. this._deltaJoystickVector.y = 0;
  30504. this._touches.remove(e.pointerId.toString());
  30505. };
  30506. /**
  30507. * Change the color of the virtual joystick
  30508. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30509. */
  30510. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30511. this._joystickColor = newColor;
  30512. };
  30513. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30514. this._action = action;
  30515. };
  30516. // Define which axis you'd like to control for left & right
  30517. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30518. switch (axis) {
  30519. case JoystickAxis.X:
  30520. case JoystickAxis.Y:
  30521. case JoystickAxis.Z:
  30522. this._axisTargetedByLeftAndRight = axis;
  30523. break;
  30524. default:
  30525. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30526. break;
  30527. }
  30528. };
  30529. // Define which axis you'd like to control for up & down
  30530. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30531. switch (axis) {
  30532. case JoystickAxis.X:
  30533. case JoystickAxis.Y:
  30534. case JoystickAxis.Z:
  30535. this._axisTargetedByUpAndDown = axis;
  30536. break;
  30537. default:
  30538. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30539. break;
  30540. }
  30541. };
  30542. VirtualJoystick.prototype._clearCanvas = function () {
  30543. if (this._leftJoystick) {
  30544. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30545. }
  30546. else {
  30547. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30548. }
  30549. };
  30550. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30551. var _this = this;
  30552. if (this.pressed) {
  30553. this._touches.forEach(function (touch) {
  30554. if (touch.pointerId === _this._joystickPointerID) {
  30555. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30556. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30557. VirtualJoystick.vjCanvasContext.beginPath();
  30558. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30559. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30560. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30561. VirtualJoystick.vjCanvasContext.stroke();
  30562. VirtualJoystick.vjCanvasContext.closePath();
  30563. VirtualJoystick.vjCanvasContext.beginPath();
  30564. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30565. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30566. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30567. VirtualJoystick.vjCanvasContext.stroke();
  30568. VirtualJoystick.vjCanvasContext.closePath();
  30569. VirtualJoystick.vjCanvasContext.beginPath();
  30570. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30571. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30572. VirtualJoystick.vjCanvasContext.stroke();
  30573. VirtualJoystick.vjCanvasContext.closePath();
  30574. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30575. }
  30576. else {
  30577. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30578. VirtualJoystick.vjCanvasContext.beginPath();
  30579. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30580. VirtualJoystick.vjCanvasContext.beginPath();
  30581. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30582. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30583. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30584. VirtualJoystick.vjCanvasContext.stroke();
  30585. VirtualJoystick.vjCanvasContext.closePath();
  30586. touch.prevX = touch.x;
  30587. touch.prevY = touch.y;
  30588. }
  30589. ;
  30590. });
  30591. }
  30592. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30593. };
  30594. VirtualJoystick.prototype.releaseCanvas = function () {
  30595. if (VirtualJoystick.vjCanvas) {
  30596. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30597. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30598. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30599. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30600. window.removeEventListener("resize", this._onResize);
  30601. document.body.removeChild(VirtualJoystick.vjCanvas);
  30602. VirtualJoystick.vjCanvas = null;
  30603. }
  30604. };
  30605. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30606. VirtualJoystick._globalJoystickIndex = 0;
  30607. return VirtualJoystick;
  30608. })();
  30609. BABYLON.VirtualJoystick = VirtualJoystick;
  30610. })(BABYLON || (BABYLON = {}));
  30611. var BABYLON;
  30612. (function (BABYLON) {
  30613. // We're mainly based on the logic defined into the FreeCamera code
  30614. var VirtualJoysticksCamera = (function (_super) {
  30615. __extends(VirtualJoysticksCamera, _super);
  30616. function VirtualJoysticksCamera(name, position, scene) {
  30617. _super.call(this, name, position, scene);
  30618. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30619. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30620. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30621. this._leftjoystick.setJoystickSensibility(0.15);
  30622. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30623. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30624. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30625. this._rightjoystick.reverseUpDown = true;
  30626. this._rightjoystick.setJoystickSensibility(0.05);
  30627. this._rightjoystick.setJoystickColor("yellow");
  30628. }
  30629. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  30630. return this._leftjoystick;
  30631. };
  30632. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  30633. return this._rightjoystick;
  30634. };
  30635. VirtualJoysticksCamera.prototype._checkInputs = function () {
  30636. var speed = this._computeLocalCameraSpeed() * 50;
  30637. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  30638. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  30639. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  30640. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  30641. if (!this._leftjoystick.pressed) {
  30642. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  30643. }
  30644. if (!this._rightjoystick.pressed) {
  30645. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  30646. }
  30647. _super.prototype._checkInputs.call(this);
  30648. };
  30649. VirtualJoysticksCamera.prototype.dispose = function () {
  30650. this._leftjoystick.releaseCanvas();
  30651. _super.prototype.dispose.call(this);
  30652. };
  30653. return VirtualJoysticksCamera;
  30654. })(BABYLON.FreeCamera);
  30655. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  30656. })(BABYLON || (BABYLON = {}));
  30657. var BABYLON;
  30658. (function (BABYLON) {
  30659. var AnaglyphPostProcess = (function (_super) {
  30660. __extends(AnaglyphPostProcess, _super);
  30661. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30662. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  30663. }
  30664. return AnaglyphPostProcess;
  30665. })(BABYLON.PostProcess);
  30666. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  30667. })(BABYLON || (BABYLON = {}));
  30668. var BABYLON;
  30669. (function (BABYLON) {
  30670. var OutlineRenderer = (function () {
  30671. function OutlineRenderer(scene) {
  30672. this._scene = scene;
  30673. }
  30674. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  30675. var _this = this;
  30676. if (useOverlay === void 0) { useOverlay = false; }
  30677. var scene = this._scene;
  30678. var engine = this._scene.getEngine();
  30679. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  30680. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  30681. return;
  30682. }
  30683. var mesh = subMesh.getRenderingMesh();
  30684. var material = subMesh.getMaterial();
  30685. engine.enableEffect(this._effect);
  30686. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  30687. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  30688. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30689. // Bones
  30690. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30691. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30692. }
  30693. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  30694. // Alpha test
  30695. if (material && material.needAlphaTesting()) {
  30696. var alphaTexture = material.getAlphaTestTexture();
  30697. this._effect.setTexture("diffuseSampler", alphaTexture);
  30698. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30699. }
  30700. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  30701. };
  30702. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  30703. var defines = [];
  30704. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  30705. var mesh = subMesh.getMesh();
  30706. var material = subMesh.getMaterial();
  30707. // Alpha test
  30708. if (material && material.needAlphaTesting()) {
  30709. defines.push("#define ALPHATEST");
  30710. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30711. attribs.push(BABYLON.VertexBuffer.UVKind);
  30712. defines.push("#define UV1");
  30713. }
  30714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30715. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30716. defines.push("#define UV2");
  30717. }
  30718. }
  30719. // Bones
  30720. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30721. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30722. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30723. defines.push("#define BONES");
  30724. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30725. }
  30726. // Instances
  30727. if (useInstances) {
  30728. defines.push("#define INSTANCES");
  30729. attribs.push("world0");
  30730. attribs.push("world1");
  30731. attribs.push("world2");
  30732. attribs.push("world3");
  30733. }
  30734. // Get correct effect
  30735. var join = defines.join("\n");
  30736. if (this._cachedDefines !== join) {
  30737. this._cachedDefines = join;
  30738. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  30739. }
  30740. return this._effect.isReady();
  30741. };
  30742. return OutlineRenderer;
  30743. })();
  30744. BABYLON.OutlineRenderer = OutlineRenderer;
  30745. })(BABYLON || (BABYLON = {}));
  30746. var BABYLON;
  30747. (function (BABYLON) {
  30748. var MeshAssetTask = (function () {
  30749. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  30750. this.name = name;
  30751. this.meshesNames = meshesNames;
  30752. this.rootUrl = rootUrl;
  30753. this.sceneFilename = sceneFilename;
  30754. this.isCompleted = false;
  30755. }
  30756. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30757. var _this = this;
  30758. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  30759. _this.loadedMeshes = meshes;
  30760. _this.loadedParticleSystems = particleSystems;
  30761. _this.loadedSkeletons = skeletons;
  30762. _this.isCompleted = true;
  30763. if (_this.onSuccess) {
  30764. _this.onSuccess(_this);
  30765. }
  30766. onSuccess();
  30767. }, null, function () {
  30768. if (_this.onError) {
  30769. _this.onError(_this);
  30770. }
  30771. onError();
  30772. });
  30773. };
  30774. return MeshAssetTask;
  30775. })();
  30776. BABYLON.MeshAssetTask = MeshAssetTask;
  30777. var TextFileAssetTask = (function () {
  30778. function TextFileAssetTask(name, url) {
  30779. this.name = name;
  30780. this.url = url;
  30781. this.isCompleted = false;
  30782. }
  30783. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30784. var _this = this;
  30785. BABYLON.Tools.LoadFile(this.url, function (data) {
  30786. _this.text = data;
  30787. _this.isCompleted = true;
  30788. if (_this.onSuccess) {
  30789. _this.onSuccess(_this);
  30790. }
  30791. onSuccess();
  30792. }, null, scene.database, false, function () {
  30793. if (_this.onError) {
  30794. _this.onError(_this);
  30795. }
  30796. onError();
  30797. });
  30798. };
  30799. return TextFileAssetTask;
  30800. })();
  30801. BABYLON.TextFileAssetTask = TextFileAssetTask;
  30802. var BinaryFileAssetTask = (function () {
  30803. function BinaryFileAssetTask(name, url) {
  30804. this.name = name;
  30805. this.url = url;
  30806. this.isCompleted = false;
  30807. }
  30808. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30809. var _this = this;
  30810. BABYLON.Tools.LoadFile(this.url, function (data) {
  30811. _this.data = data;
  30812. _this.isCompleted = true;
  30813. if (_this.onSuccess) {
  30814. _this.onSuccess(_this);
  30815. }
  30816. onSuccess();
  30817. }, null, scene.database, true, function () {
  30818. if (_this.onError) {
  30819. _this.onError(_this);
  30820. }
  30821. onError();
  30822. });
  30823. };
  30824. return BinaryFileAssetTask;
  30825. })();
  30826. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  30827. var ImageAssetTask = (function () {
  30828. function ImageAssetTask(name, url) {
  30829. this.name = name;
  30830. this.url = url;
  30831. this.isCompleted = false;
  30832. }
  30833. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30834. var _this = this;
  30835. var img = new Image();
  30836. img.onload = function () {
  30837. _this.image = img;
  30838. _this.isCompleted = true;
  30839. if (_this.onSuccess) {
  30840. _this.onSuccess(_this);
  30841. }
  30842. onSuccess();
  30843. };
  30844. img.onerror = function () {
  30845. if (_this.onError) {
  30846. _this.onError(_this);
  30847. }
  30848. onError();
  30849. };
  30850. img.src = this.url;
  30851. };
  30852. return ImageAssetTask;
  30853. })();
  30854. BABYLON.ImageAssetTask = ImageAssetTask;
  30855. var TextureAssetTask = (function () {
  30856. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  30857. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30858. this.name = name;
  30859. this.url = url;
  30860. this.noMipmap = noMipmap;
  30861. this.invertY = invertY;
  30862. this.samplingMode = samplingMode;
  30863. this.isCompleted = false;
  30864. }
  30865. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30866. var _this = this;
  30867. var onload = function () {
  30868. _this.isCompleted = true;
  30869. if (_this.onSuccess) {
  30870. _this.onSuccess(_this);
  30871. }
  30872. onSuccess();
  30873. };
  30874. var onerror = function () {
  30875. if (_this.onError) {
  30876. _this.onError(_this);
  30877. }
  30878. onError();
  30879. };
  30880. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  30881. };
  30882. return TextureAssetTask;
  30883. })();
  30884. BABYLON.TextureAssetTask = TextureAssetTask;
  30885. var AssetsManager = (function () {
  30886. function AssetsManager(scene) {
  30887. this._tasks = new Array();
  30888. this._waitingTasksCount = 0;
  30889. this.useDefaultLoadingScreen = true;
  30890. this._scene = scene;
  30891. }
  30892. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  30893. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  30894. this._tasks.push(task);
  30895. return task;
  30896. };
  30897. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  30898. var task = new TextFileAssetTask(taskName, url);
  30899. this._tasks.push(task);
  30900. return task;
  30901. };
  30902. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  30903. var task = new BinaryFileAssetTask(taskName, url);
  30904. this._tasks.push(task);
  30905. return task;
  30906. };
  30907. AssetsManager.prototype.addImageTask = function (taskName, url) {
  30908. var task = new ImageAssetTask(taskName, url);
  30909. this._tasks.push(task);
  30910. return task;
  30911. };
  30912. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  30913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30914. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  30915. this._tasks.push(task);
  30916. return task;
  30917. };
  30918. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  30919. this._waitingTasksCount--;
  30920. if (this._waitingTasksCount === 0) {
  30921. if (this.onFinish) {
  30922. this.onFinish(this._tasks);
  30923. }
  30924. this._scene.getEngine().hideLoadingUI();
  30925. }
  30926. };
  30927. AssetsManager.prototype._runTask = function (task) {
  30928. var _this = this;
  30929. task.run(this._scene, function () {
  30930. if (_this.onTaskSuccess) {
  30931. _this.onTaskSuccess(task);
  30932. }
  30933. _this._decreaseWaitingTasksCount();
  30934. }, function () {
  30935. if (_this.onTaskError) {
  30936. _this.onTaskError(task);
  30937. }
  30938. _this._decreaseWaitingTasksCount();
  30939. });
  30940. };
  30941. AssetsManager.prototype.reset = function () {
  30942. this._tasks = new Array();
  30943. return this;
  30944. };
  30945. AssetsManager.prototype.load = function () {
  30946. this._waitingTasksCount = this._tasks.length;
  30947. if (this._waitingTasksCount === 0) {
  30948. if (this.onFinish) {
  30949. this.onFinish(this._tasks);
  30950. }
  30951. return this;
  30952. }
  30953. if (this.useDefaultLoadingScreen) {
  30954. this._scene.getEngine().displayLoadingUI();
  30955. }
  30956. for (var index = 0; index < this._tasks.length; index++) {
  30957. var task = this._tasks[index];
  30958. this._runTask(task);
  30959. }
  30960. return this;
  30961. };
  30962. return AssetsManager;
  30963. })();
  30964. BABYLON.AssetsManager = AssetsManager;
  30965. })(BABYLON || (BABYLON = {}));
  30966. var BABYLON;
  30967. (function (BABYLON) {
  30968. var VRDeviceOrientationFreeCamera = (function (_super) {
  30969. __extends(VRDeviceOrientationFreeCamera, _super);
  30970. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  30971. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30972. _super.call(this, name, position, scene);
  30973. this._alpha = 0;
  30974. this._beta = 0;
  30975. this._gamma = 0;
  30976. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30977. metrics.compensateDistortion = compensateDistortion;
  30978. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30979. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30980. }
  30981. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30982. this._alpha = +evt.alpha | 0;
  30983. this._beta = +evt.beta | 0;
  30984. this._gamma = +evt.gamma | 0;
  30985. if (this._gamma < 0) {
  30986. this._gamma = 90 + this._gamma;
  30987. }
  30988. else {
  30989. // Incline it in the correct angle.
  30990. this._gamma = 270 - this._gamma;
  30991. }
  30992. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30993. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30994. this.rotation.z = this._beta / 180.0 * Math.PI;
  30995. };
  30996. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30997. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30998. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30999. };
  31000. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31001. _super.prototype.detachControl.call(this, element);
  31002. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31003. };
  31004. return VRDeviceOrientationFreeCamera;
  31005. })(BABYLON.FreeCamera);
  31006. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31007. })(BABYLON || (BABYLON = {}));
  31008. var BABYLON;
  31009. (function (BABYLON) {
  31010. var WebVRFreeCamera = (function (_super) {
  31011. __extends(WebVRFreeCamera, _super);
  31012. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31013. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31014. _super.call(this, name, position, scene);
  31015. this._hmdDevice = null;
  31016. this._sensorDevice = null;
  31017. this._cacheState = null;
  31018. this._cacheQuaternion = new BABYLON.Quaternion();
  31019. this._cacheRotation = BABYLON.Vector3.Zero();
  31020. this._vrEnabled = false;
  31021. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31022. metrics.compensateDistortion = compensateDistortion;
  31023. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31024. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31025. }
  31026. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31027. var size = devices.length;
  31028. var i = 0;
  31029. // Reset devices.
  31030. this._sensorDevice = null;
  31031. this._hmdDevice = null;
  31032. // Search for a HmdDevice.
  31033. while (i < size && this._hmdDevice === null) {
  31034. if (devices[i] instanceof HMDVRDevice) {
  31035. this._hmdDevice = devices[i];
  31036. }
  31037. i++;
  31038. }
  31039. i = 0;
  31040. while (i < size && this._sensorDevice === null) {
  31041. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31042. this._sensorDevice = devices[i];
  31043. }
  31044. i++;
  31045. }
  31046. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31047. };
  31048. WebVRFreeCamera.prototype._checkInputs = function () {
  31049. if (this._vrEnabled) {
  31050. this._cacheState = this._sensorDevice.getState();
  31051. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31052. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31053. this.rotation.x = -this._cacheRotation.z;
  31054. this.rotation.y = -this._cacheRotation.y;
  31055. this.rotation.z = this._cacheRotation.x;
  31056. }
  31057. _super.prototype._checkInputs.call(this);
  31058. };
  31059. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31060. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31061. if (navigator.getVRDevices) {
  31062. navigator.getVRDevices().then(this._getWebVRDevices);
  31063. }
  31064. else if (navigator.mozGetVRDevices) {
  31065. navigator.mozGetVRDevices(this._getWebVRDevices);
  31066. }
  31067. };
  31068. WebVRFreeCamera.prototype.detachControl = function (element) {
  31069. _super.prototype.detachControl.call(this, element);
  31070. this._vrEnabled = false;
  31071. };
  31072. return WebVRFreeCamera;
  31073. })(BABYLON.FreeCamera);
  31074. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31075. })(BABYLON || (BABYLON = {}));
  31076. var BABYLON;
  31077. (function (BABYLON) {
  31078. // Standard optimizations
  31079. var SceneOptimization = (function () {
  31080. function SceneOptimization(priority) {
  31081. if (priority === void 0) { priority = 0; }
  31082. this.priority = priority;
  31083. this.apply = function (scene) {
  31084. return true; // Return true if everything that can be done was applied
  31085. };
  31086. }
  31087. return SceneOptimization;
  31088. })();
  31089. BABYLON.SceneOptimization = SceneOptimization;
  31090. var TextureOptimization = (function (_super) {
  31091. __extends(TextureOptimization, _super);
  31092. function TextureOptimization(priority, maximumSize) {
  31093. var _this = this;
  31094. if (priority === void 0) { priority = 0; }
  31095. if (maximumSize === void 0) { maximumSize = 1024; }
  31096. _super.call(this, priority);
  31097. this.priority = priority;
  31098. this.maximumSize = maximumSize;
  31099. this.apply = function (scene) {
  31100. var allDone = true;
  31101. for (var index = 0; index < scene.textures.length; index++) {
  31102. var texture = scene.textures[index];
  31103. if (!texture.canRescale) {
  31104. continue;
  31105. }
  31106. var currentSize = texture.getSize();
  31107. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31108. if (maxDimension > _this.maximumSize) {
  31109. texture.scale(0.5);
  31110. allDone = false;
  31111. }
  31112. }
  31113. return allDone;
  31114. };
  31115. }
  31116. return TextureOptimization;
  31117. })(SceneOptimization);
  31118. BABYLON.TextureOptimization = TextureOptimization;
  31119. var HardwareScalingOptimization = (function (_super) {
  31120. __extends(HardwareScalingOptimization, _super);
  31121. function HardwareScalingOptimization(priority, maximumScale) {
  31122. var _this = this;
  31123. if (priority === void 0) { priority = 0; }
  31124. if (maximumScale === void 0) { maximumScale = 2; }
  31125. _super.call(this, priority);
  31126. this.priority = priority;
  31127. this.maximumScale = maximumScale;
  31128. this._currentScale = 1;
  31129. this.apply = function (scene) {
  31130. _this._currentScale++;
  31131. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31132. return _this._currentScale >= _this.maximumScale;
  31133. };
  31134. }
  31135. return HardwareScalingOptimization;
  31136. })(SceneOptimization);
  31137. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31138. var ShadowsOptimization = (function (_super) {
  31139. __extends(ShadowsOptimization, _super);
  31140. function ShadowsOptimization() {
  31141. _super.apply(this, arguments);
  31142. this.apply = function (scene) {
  31143. scene.shadowsEnabled = false;
  31144. return true;
  31145. };
  31146. }
  31147. return ShadowsOptimization;
  31148. })(SceneOptimization);
  31149. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31150. var PostProcessesOptimization = (function (_super) {
  31151. __extends(PostProcessesOptimization, _super);
  31152. function PostProcessesOptimization() {
  31153. _super.apply(this, arguments);
  31154. this.apply = function (scene) {
  31155. scene.postProcessesEnabled = false;
  31156. return true;
  31157. };
  31158. }
  31159. return PostProcessesOptimization;
  31160. })(SceneOptimization);
  31161. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31162. var LensFlaresOptimization = (function (_super) {
  31163. __extends(LensFlaresOptimization, _super);
  31164. function LensFlaresOptimization() {
  31165. _super.apply(this, arguments);
  31166. this.apply = function (scene) {
  31167. scene.lensFlaresEnabled = false;
  31168. return true;
  31169. };
  31170. }
  31171. return LensFlaresOptimization;
  31172. })(SceneOptimization);
  31173. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31174. var ParticlesOptimization = (function (_super) {
  31175. __extends(ParticlesOptimization, _super);
  31176. function ParticlesOptimization() {
  31177. _super.apply(this, arguments);
  31178. this.apply = function (scene) {
  31179. scene.particlesEnabled = false;
  31180. return true;
  31181. };
  31182. }
  31183. return ParticlesOptimization;
  31184. })(SceneOptimization);
  31185. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31186. var RenderTargetsOptimization = (function (_super) {
  31187. __extends(RenderTargetsOptimization, _super);
  31188. function RenderTargetsOptimization() {
  31189. _super.apply(this, arguments);
  31190. this.apply = function (scene) {
  31191. scene.renderTargetsEnabled = false;
  31192. return true;
  31193. };
  31194. }
  31195. return RenderTargetsOptimization;
  31196. })(SceneOptimization);
  31197. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31198. var MergeMeshesOptimization = (function (_super) {
  31199. __extends(MergeMeshesOptimization, _super);
  31200. function MergeMeshesOptimization() {
  31201. var _this = this;
  31202. _super.apply(this, arguments);
  31203. this._canBeMerged = function (abstractMesh) {
  31204. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31205. return false;
  31206. }
  31207. var mesh = abstractMesh;
  31208. if (!mesh.isVisible || !mesh.isEnabled()) {
  31209. return false;
  31210. }
  31211. if (mesh.instances.length > 0) {
  31212. return false;
  31213. }
  31214. if (mesh.skeleton || mesh.hasLODLevels) {
  31215. return false;
  31216. }
  31217. return true;
  31218. };
  31219. this.apply = function (scene, updateSelectionTree) {
  31220. var globalPool = scene.meshes.slice(0);
  31221. var globalLength = globalPool.length;
  31222. for (var index = 0; index < globalLength; index++) {
  31223. var currentPool = new Array();
  31224. var current = globalPool[index];
  31225. // Checks
  31226. if (!_this._canBeMerged(current)) {
  31227. continue;
  31228. }
  31229. currentPool.push(current);
  31230. // Find compatible meshes
  31231. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31232. var otherMesh = globalPool[subIndex];
  31233. if (!_this._canBeMerged(otherMesh)) {
  31234. continue;
  31235. }
  31236. if (otherMesh.material !== current.material) {
  31237. continue;
  31238. }
  31239. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31240. continue;
  31241. }
  31242. currentPool.push(otherMesh);
  31243. globalLength--;
  31244. globalPool.splice(subIndex, 1);
  31245. subIndex--;
  31246. }
  31247. if (currentPool.length < 2) {
  31248. continue;
  31249. }
  31250. // Merge meshes
  31251. BABYLON.Mesh.MergeMeshes(currentPool);
  31252. }
  31253. if (updateSelectionTree != undefined) {
  31254. if (updateSelectionTree) {
  31255. scene.createOrUpdateSelectionOctree();
  31256. }
  31257. }
  31258. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31259. scene.createOrUpdateSelectionOctree();
  31260. }
  31261. return true;
  31262. };
  31263. }
  31264. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31265. get: function () {
  31266. return MergeMeshesOptimization._UpdateSelectionTree;
  31267. },
  31268. set: function (value) {
  31269. MergeMeshesOptimization._UpdateSelectionTree = value;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. MergeMeshesOptimization._UpdateSelectionTree = false;
  31275. return MergeMeshesOptimization;
  31276. })(SceneOptimization);
  31277. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31278. // Options
  31279. var SceneOptimizerOptions = (function () {
  31280. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31281. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31282. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31283. this.targetFrameRate = targetFrameRate;
  31284. this.trackerDuration = trackerDuration;
  31285. this.optimizations = new Array();
  31286. }
  31287. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31288. var result = new SceneOptimizerOptions(targetFrameRate);
  31289. var priority = 0;
  31290. result.optimizations.push(new MergeMeshesOptimization(priority));
  31291. result.optimizations.push(new ShadowsOptimization(priority));
  31292. result.optimizations.push(new LensFlaresOptimization(priority));
  31293. // Next priority
  31294. priority++;
  31295. result.optimizations.push(new PostProcessesOptimization(priority));
  31296. result.optimizations.push(new ParticlesOptimization(priority));
  31297. // Next priority
  31298. priority++;
  31299. result.optimizations.push(new TextureOptimization(priority, 1024));
  31300. return result;
  31301. };
  31302. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31303. var result = new SceneOptimizerOptions(targetFrameRate);
  31304. var priority = 0;
  31305. result.optimizations.push(new MergeMeshesOptimization(priority));
  31306. result.optimizations.push(new ShadowsOptimization(priority));
  31307. result.optimizations.push(new LensFlaresOptimization(priority));
  31308. // Next priority
  31309. priority++;
  31310. result.optimizations.push(new PostProcessesOptimization(priority));
  31311. result.optimizations.push(new ParticlesOptimization(priority));
  31312. // Next priority
  31313. priority++;
  31314. result.optimizations.push(new TextureOptimization(priority, 512));
  31315. // Next priority
  31316. priority++;
  31317. result.optimizations.push(new RenderTargetsOptimization(priority));
  31318. // Next priority
  31319. priority++;
  31320. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31321. return result;
  31322. };
  31323. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31324. var result = new SceneOptimizerOptions(targetFrameRate);
  31325. var priority = 0;
  31326. result.optimizations.push(new MergeMeshesOptimization(priority));
  31327. result.optimizations.push(new ShadowsOptimization(priority));
  31328. result.optimizations.push(new LensFlaresOptimization(priority));
  31329. // Next priority
  31330. priority++;
  31331. result.optimizations.push(new PostProcessesOptimization(priority));
  31332. result.optimizations.push(new ParticlesOptimization(priority));
  31333. // Next priority
  31334. priority++;
  31335. result.optimizations.push(new TextureOptimization(priority, 256));
  31336. // Next priority
  31337. priority++;
  31338. result.optimizations.push(new RenderTargetsOptimization(priority));
  31339. // Next priority
  31340. priority++;
  31341. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31342. return result;
  31343. };
  31344. return SceneOptimizerOptions;
  31345. })();
  31346. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31347. // Scene optimizer tool
  31348. var SceneOptimizer = (function () {
  31349. function SceneOptimizer() {
  31350. }
  31351. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31352. // TODO: add an epsilon
  31353. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31354. if (onSuccess) {
  31355. onSuccess();
  31356. }
  31357. return;
  31358. }
  31359. // Apply current level of optimizations
  31360. var allDone = true;
  31361. var noOptimizationApplied = true;
  31362. for (var index = 0; index < options.optimizations.length; index++) {
  31363. var optimization = options.optimizations[index];
  31364. if (optimization.priority === currentPriorityLevel) {
  31365. noOptimizationApplied = false;
  31366. allDone = allDone && optimization.apply(scene);
  31367. }
  31368. }
  31369. // If no optimization was applied, this is a failure :(
  31370. if (noOptimizationApplied) {
  31371. if (onFailure) {
  31372. onFailure();
  31373. }
  31374. return;
  31375. }
  31376. // If all optimizations were done, move to next level
  31377. if (allDone) {
  31378. currentPriorityLevel++;
  31379. }
  31380. // Let's the system running for a specific amount of time before checking FPS
  31381. scene.executeWhenReady(function () {
  31382. setTimeout(function () {
  31383. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31384. }, options.trackerDuration);
  31385. });
  31386. };
  31387. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31388. if (!options) {
  31389. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31390. }
  31391. // Let's the system running for a specific amount of time before checking FPS
  31392. scene.executeWhenReady(function () {
  31393. setTimeout(function () {
  31394. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31395. }, options.trackerDuration);
  31396. });
  31397. };
  31398. return SceneOptimizer;
  31399. })();
  31400. BABYLON.SceneOptimizer = SceneOptimizer;
  31401. })(BABYLON || (BABYLON = {}));
  31402. var BABYLON;
  31403. (function (BABYLON) {
  31404. var Internals;
  31405. (function (Internals) {
  31406. var MeshLODLevel = (function () {
  31407. function MeshLODLevel(distance, mesh) {
  31408. this.distance = distance;
  31409. this.mesh = mesh;
  31410. }
  31411. return MeshLODLevel;
  31412. })();
  31413. Internals.MeshLODLevel = MeshLODLevel;
  31414. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31415. })(BABYLON || (BABYLON = {}));
  31416. var BABYLON;
  31417. (function (BABYLON) {
  31418. var RawTexture = (function (_super) {
  31419. __extends(RawTexture, _super);
  31420. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31421. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31422. if (invertY === void 0) { invertY = false; }
  31423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31424. _super.call(this, null, scene, !generateMipMaps, invertY);
  31425. this.format = format;
  31426. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31427. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31428. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31429. }
  31430. RawTexture.prototype.update = function (data) {
  31431. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31432. };
  31433. // Statics
  31434. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31435. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31436. if (invertY === void 0) { invertY = false; }
  31437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31438. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31439. };
  31440. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31441. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31442. if (invertY === void 0) { invertY = false; }
  31443. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31444. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31445. };
  31446. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31447. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31448. if (invertY === void 0) { invertY = false; }
  31449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31450. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31451. };
  31452. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31453. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31454. if (invertY === void 0) { invertY = false; }
  31455. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31456. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31457. };
  31458. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31459. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31460. if (invertY === void 0) { invertY = false; }
  31461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31462. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31463. };
  31464. return RawTexture;
  31465. })(BABYLON.Texture);
  31466. BABYLON.RawTexture = RawTexture;
  31467. })(BABYLON || (BABYLON = {}));
  31468. var BABYLON;
  31469. (function (BABYLON) {
  31470. var IndexedVector2 = (function (_super) {
  31471. __extends(IndexedVector2, _super);
  31472. function IndexedVector2(original, index) {
  31473. _super.call(this, original.x, original.y);
  31474. this.index = index;
  31475. }
  31476. return IndexedVector2;
  31477. })(BABYLON.Vector2);
  31478. var PolygonPoints = (function () {
  31479. function PolygonPoints() {
  31480. this.elements = new Array();
  31481. }
  31482. PolygonPoints.prototype.add = function (originalPoints) {
  31483. var _this = this;
  31484. var result = new Array();
  31485. originalPoints.forEach(function (point) {
  31486. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31487. var newPoint = new IndexedVector2(point, _this.elements.length);
  31488. result.push(newPoint);
  31489. _this.elements.push(newPoint);
  31490. }
  31491. });
  31492. return result;
  31493. };
  31494. PolygonPoints.prototype.computeBounds = function () {
  31495. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31496. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31497. this.elements.forEach(function (point) {
  31498. // x
  31499. if (point.x < lmin.x) {
  31500. lmin.x = point.x;
  31501. }
  31502. else if (point.x > lmax.x) {
  31503. lmax.x = point.x;
  31504. }
  31505. // y
  31506. if (point.y < lmin.y) {
  31507. lmin.y = point.y;
  31508. }
  31509. else if (point.y > lmax.y) {
  31510. lmax.y = point.y;
  31511. }
  31512. });
  31513. return {
  31514. min: lmin,
  31515. max: lmax,
  31516. width: lmax.x - lmin.x,
  31517. height: lmax.y - lmin.y
  31518. };
  31519. };
  31520. return PolygonPoints;
  31521. })();
  31522. var Polygon = (function () {
  31523. function Polygon() {
  31524. }
  31525. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31526. return [
  31527. new BABYLON.Vector2(xmin, ymin),
  31528. new BABYLON.Vector2(xmax, ymin),
  31529. new BABYLON.Vector2(xmax, ymax),
  31530. new BABYLON.Vector2(xmin, ymax)
  31531. ];
  31532. };
  31533. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31534. if (cx === void 0) { cx = 0; }
  31535. if (cy === void 0) { cy = 0; }
  31536. if (numberOfSides === void 0) { numberOfSides = 32; }
  31537. var result = new Array();
  31538. var angle = 0;
  31539. var increment = (Math.PI * 2) / numberOfSides;
  31540. for (var i = 0; i < numberOfSides; i++) {
  31541. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31542. angle -= increment;
  31543. }
  31544. return result;
  31545. };
  31546. Polygon.Parse = function (input) {
  31547. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31548. var i, result = [];
  31549. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31550. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31551. }
  31552. return result;
  31553. };
  31554. Polygon.StartingAt = function (x, y) {
  31555. return BABYLON.Path2.StartingAt(x, y);
  31556. };
  31557. return Polygon;
  31558. })();
  31559. BABYLON.Polygon = Polygon;
  31560. var PolygonMeshBuilder = (function () {
  31561. function PolygonMeshBuilder(name, contours, scene) {
  31562. this._points = new PolygonPoints();
  31563. this._outlinepoints = new PolygonPoints();
  31564. this._holes = [];
  31565. if (!("poly2tri" in window)) {
  31566. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31567. }
  31568. this._name = name;
  31569. this._scene = scene;
  31570. var points;
  31571. if (contours instanceof BABYLON.Path2) {
  31572. points = contours.getPoints();
  31573. }
  31574. else {
  31575. points = contours;
  31576. }
  31577. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31578. this._outlinepoints.add(points);
  31579. }
  31580. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31581. this._swctx.addHole(this._points.add(hole));
  31582. var holepoints = new PolygonPoints();
  31583. holepoints.add(hole);
  31584. this._holes.push(holepoints);
  31585. return this;
  31586. };
  31587. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31588. var _this = this;
  31589. if (updatable === void 0) { updatable = false; }
  31590. var result = new BABYLON.Mesh(this._name, this._scene);
  31591. var normals = [];
  31592. var positions = [];
  31593. var uvs = [];
  31594. var bounds = this._points.computeBounds();
  31595. this._points.elements.forEach(function (p) {
  31596. normals.push(0, 1.0, 0);
  31597. positions.push(p.x, 0, p.y);
  31598. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31599. });
  31600. var indices = [];
  31601. this._swctx.triangulate();
  31602. this._swctx.getTriangles().forEach(function (triangle) {
  31603. triangle.getPoints().forEach(function (point) {
  31604. indices.push(point.index);
  31605. });
  31606. });
  31607. if (depth > 0) {
  31608. var positionscount = (positions.length / 3); //get the current pointcount
  31609. this._points.elements.forEach(function (p) {
  31610. normals.push(0, -1.0, 0);
  31611. positions.push(p.x, -depth, p.y);
  31612. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31613. });
  31614. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31615. var p2;
  31616. var poscounter = 0;
  31617. this._swctx.getTriangles().forEach(function (triangle) {
  31618. triangle.getPoints().forEach(function (point) {
  31619. switch (poscounter) {
  31620. case 0:
  31621. p1 = point;
  31622. break;
  31623. case 1:
  31624. p2 = point;
  31625. break;
  31626. case 2:
  31627. indices.push(point.index + positionscount);
  31628. indices.push(p2.index + positionscount);
  31629. indices.push(p1.index + positionscount);
  31630. poscounter = -1;
  31631. break;
  31632. }
  31633. poscounter++;
  31634. //indices.push((<IndexedVector2>point).index + positionscount);
  31635. });
  31636. });
  31637. //Add the sides
  31638. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31639. this._holes.forEach(function (hole) {
  31640. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31641. });
  31642. }
  31643. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31644. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31645. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31646. result.setIndices(indices);
  31647. return result;
  31648. };
  31649. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31650. var StartIndex = positions.length / 3;
  31651. var ulength = 0;
  31652. for (var i = 0; i < points.elements.length; i++) {
  31653. var p = points.elements[i];
  31654. var p1;
  31655. if ((i + 1) > points.elements.length - 1) {
  31656. p1 = points.elements[0];
  31657. }
  31658. else {
  31659. p1 = points.elements[i + 1];
  31660. }
  31661. positions.push(p.x, 0, p.y);
  31662. positions.push(p.x, -depth, p.y);
  31663. positions.push(p1.x, 0, p1.y);
  31664. positions.push(p1.x, -depth, p1.y);
  31665. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31666. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31667. var v3 = v2.subtract(v1);
  31668. var v4 = new BABYLON.Vector3(0, 1, 0);
  31669. var vn = BABYLON.Vector3.Cross(v3, v4);
  31670. vn = vn.normalize();
  31671. uvs.push(ulength / bounds.width, 0);
  31672. uvs.push(ulength / bounds.width, 1);
  31673. ulength += v3.length();
  31674. uvs.push((ulength / bounds.width), 0);
  31675. uvs.push((ulength / bounds.width), 1);
  31676. if (!flip) {
  31677. normals.push(-vn.x, -vn.y, -vn.z);
  31678. normals.push(-vn.x, -vn.y, -vn.z);
  31679. normals.push(-vn.x, -vn.y, -vn.z);
  31680. normals.push(-vn.x, -vn.y, -vn.z);
  31681. indices.push(StartIndex);
  31682. indices.push(StartIndex + 1);
  31683. indices.push(StartIndex + 2);
  31684. indices.push(StartIndex + 1);
  31685. indices.push(StartIndex + 3);
  31686. indices.push(StartIndex + 2);
  31687. }
  31688. else {
  31689. normals.push(vn.x, vn.y, vn.z);
  31690. normals.push(vn.x, vn.y, vn.z);
  31691. normals.push(vn.x, vn.y, vn.z);
  31692. normals.push(vn.x, vn.y, vn.z);
  31693. indices.push(StartIndex);
  31694. indices.push(StartIndex + 2);
  31695. indices.push(StartIndex + 1);
  31696. indices.push(StartIndex + 1);
  31697. indices.push(StartIndex + 2);
  31698. indices.push(StartIndex + 3);
  31699. }
  31700. StartIndex += 4;
  31701. }
  31702. ;
  31703. };
  31704. return PolygonMeshBuilder;
  31705. })();
  31706. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31707. })(BABYLON || (BABYLON = {}));
  31708. var BABYLON;
  31709. (function (BABYLON) {
  31710. var Octree = (function () {
  31711. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  31712. if (maxDepth === void 0) { maxDepth = 2; }
  31713. this.maxDepth = maxDepth;
  31714. this.dynamicContent = new Array();
  31715. this._maxBlockCapacity = maxBlockCapacity || 64;
  31716. this._selectionContent = new BABYLON.SmartArray(1024);
  31717. this._creationFunc = creationFunc;
  31718. }
  31719. // Methods
  31720. Octree.prototype.update = function (worldMin, worldMax, entries) {
  31721. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  31722. };
  31723. Octree.prototype.addMesh = function (entry) {
  31724. for (var index = 0; index < this.blocks.length; index++) {
  31725. var block = this.blocks[index];
  31726. block.addEntry(entry);
  31727. }
  31728. };
  31729. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  31730. this._selectionContent.reset();
  31731. for (var index = 0; index < this.blocks.length; index++) {
  31732. var block = this.blocks[index];
  31733. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  31734. }
  31735. if (allowDuplicate) {
  31736. this._selectionContent.concat(this.dynamicContent);
  31737. }
  31738. else {
  31739. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31740. }
  31741. return this._selectionContent;
  31742. };
  31743. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  31744. this._selectionContent.reset();
  31745. for (var index = 0; index < this.blocks.length; index++) {
  31746. var block = this.blocks[index];
  31747. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  31748. }
  31749. if (allowDuplicate) {
  31750. this._selectionContent.concat(this.dynamicContent);
  31751. }
  31752. else {
  31753. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31754. }
  31755. return this._selectionContent;
  31756. };
  31757. Octree.prototype.intersectsRay = function (ray) {
  31758. this._selectionContent.reset();
  31759. for (var index = 0; index < this.blocks.length; index++) {
  31760. var block = this.blocks[index];
  31761. block.intersectsRay(ray, this._selectionContent);
  31762. }
  31763. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31764. return this._selectionContent;
  31765. };
  31766. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  31767. target.blocks = new Array();
  31768. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  31769. // Segmenting space
  31770. for (var x = 0; x < 2; x++) {
  31771. for (var y = 0; y < 2; y++) {
  31772. for (var z = 0; z < 2; z++) {
  31773. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  31774. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  31775. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  31776. block.addEntries(entries);
  31777. target.blocks.push(block);
  31778. }
  31779. }
  31780. }
  31781. };
  31782. Octree.CreationFuncForMeshes = function (entry, block) {
  31783. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31784. block.entries.push(entry);
  31785. }
  31786. };
  31787. Octree.CreationFuncForSubMeshes = function (entry, block) {
  31788. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31789. block.entries.push(entry);
  31790. }
  31791. };
  31792. return Octree;
  31793. })();
  31794. BABYLON.Octree = Octree;
  31795. })(BABYLON || (BABYLON = {}));
  31796. var BABYLON;
  31797. (function (BABYLON) {
  31798. var OctreeBlock = (function () {
  31799. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  31800. this.entries = new Array();
  31801. this._boundingVectors = new Array();
  31802. this._capacity = capacity;
  31803. this._depth = depth;
  31804. this._maxDepth = maxDepth;
  31805. this._creationFunc = creationFunc;
  31806. this._minPoint = minPoint;
  31807. this._maxPoint = maxPoint;
  31808. this._boundingVectors.push(minPoint.clone());
  31809. this._boundingVectors.push(maxPoint.clone());
  31810. this._boundingVectors.push(minPoint.clone());
  31811. this._boundingVectors[2].x = maxPoint.x;
  31812. this._boundingVectors.push(minPoint.clone());
  31813. this._boundingVectors[3].y = maxPoint.y;
  31814. this._boundingVectors.push(minPoint.clone());
  31815. this._boundingVectors[4].z = maxPoint.z;
  31816. this._boundingVectors.push(maxPoint.clone());
  31817. this._boundingVectors[5].z = minPoint.z;
  31818. this._boundingVectors.push(maxPoint.clone());
  31819. this._boundingVectors[6].x = minPoint.x;
  31820. this._boundingVectors.push(maxPoint.clone());
  31821. this._boundingVectors[7].y = minPoint.y;
  31822. }
  31823. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  31824. // Property
  31825. get: function () {
  31826. return this._capacity;
  31827. },
  31828. enumerable: true,
  31829. configurable: true
  31830. });
  31831. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  31832. get: function () {
  31833. return this._minPoint;
  31834. },
  31835. enumerable: true,
  31836. configurable: true
  31837. });
  31838. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  31839. get: function () {
  31840. return this._maxPoint;
  31841. },
  31842. enumerable: true,
  31843. configurable: true
  31844. });
  31845. // Methods
  31846. OctreeBlock.prototype.addEntry = function (entry) {
  31847. if (this.blocks) {
  31848. for (var index = 0; index < this.blocks.length; index++) {
  31849. var block = this.blocks[index];
  31850. block.addEntry(entry);
  31851. }
  31852. return;
  31853. }
  31854. this._creationFunc(entry, this);
  31855. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  31856. this.createInnerBlocks();
  31857. }
  31858. };
  31859. OctreeBlock.prototype.addEntries = function (entries) {
  31860. for (var index = 0; index < entries.length; index++) {
  31861. var mesh = entries[index];
  31862. this.addEntry(mesh);
  31863. }
  31864. };
  31865. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  31866. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  31867. if (this.blocks) {
  31868. for (var index = 0; index < this.blocks.length; index++) {
  31869. var block = this.blocks[index];
  31870. block.select(frustumPlanes, selection, allowDuplicate);
  31871. }
  31872. return;
  31873. }
  31874. if (allowDuplicate) {
  31875. selection.concat(this.entries);
  31876. }
  31877. else {
  31878. selection.concatWithNoDuplicate(this.entries);
  31879. }
  31880. }
  31881. };
  31882. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  31883. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  31884. if (this.blocks) {
  31885. for (var index = 0; index < this.blocks.length; index++) {
  31886. var block = this.blocks[index];
  31887. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  31888. }
  31889. return;
  31890. }
  31891. if (allowDuplicate) {
  31892. selection.concat(this.entries);
  31893. }
  31894. else {
  31895. selection.concatWithNoDuplicate(this.entries);
  31896. }
  31897. }
  31898. };
  31899. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  31900. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  31901. if (this.blocks) {
  31902. for (var index = 0; index < this.blocks.length; index++) {
  31903. var block = this.blocks[index];
  31904. block.intersectsRay(ray, selection);
  31905. }
  31906. return;
  31907. }
  31908. selection.concatWithNoDuplicate(this.entries);
  31909. }
  31910. };
  31911. OctreeBlock.prototype.createInnerBlocks = function () {
  31912. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  31913. };
  31914. return OctreeBlock;
  31915. })();
  31916. BABYLON.OctreeBlock = OctreeBlock;
  31917. })(BABYLON || (BABYLON = {}));
  31918. var BABYLON;
  31919. (function (BABYLON) {
  31920. var BlurPostProcess = (function (_super) {
  31921. __extends(BlurPostProcess, _super);
  31922. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  31923. var _this = this;
  31924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31925. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  31926. this.direction = direction;
  31927. this.blurWidth = blurWidth;
  31928. this.onApply = function (effect) {
  31929. effect.setFloat2("screenSize", _this.width, _this.height);
  31930. effect.setVector2("direction", _this.direction);
  31931. effect.setFloat("blurWidth", _this.blurWidth);
  31932. };
  31933. }
  31934. return BlurPostProcess;
  31935. })(BABYLON.PostProcess);
  31936. BABYLON.BlurPostProcess = BlurPostProcess;
  31937. })(BABYLON || (BABYLON = {}));
  31938. var BABYLON;
  31939. (function (BABYLON) {
  31940. var RefractionPostProcess = (function (_super) {
  31941. __extends(RefractionPostProcess, _super);
  31942. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  31943. var _this = this;
  31944. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  31945. this.color = color;
  31946. this.depth = depth;
  31947. this.colorLevel = colorLevel;
  31948. this.onActivate = function (cam) {
  31949. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  31950. };
  31951. this.onApply = function (effect) {
  31952. effect.setColor3("baseColor", _this.color);
  31953. effect.setFloat("depth", _this.depth);
  31954. effect.setFloat("colorLevel", _this.colorLevel);
  31955. effect.setTexture("refractionSampler", _this._refRexture);
  31956. };
  31957. }
  31958. // Methods
  31959. RefractionPostProcess.prototype.dispose = function (camera) {
  31960. if (this._refRexture) {
  31961. this._refRexture.dispose();
  31962. }
  31963. _super.prototype.dispose.call(this, camera);
  31964. };
  31965. return RefractionPostProcess;
  31966. })(BABYLON.PostProcess);
  31967. BABYLON.RefractionPostProcess = RefractionPostProcess;
  31968. })(BABYLON || (BABYLON = {}));
  31969. var BABYLON;
  31970. (function (BABYLON) {
  31971. var BlackAndWhitePostProcess = (function (_super) {
  31972. __extends(BlackAndWhitePostProcess, _super);
  31973. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31974. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  31975. }
  31976. return BlackAndWhitePostProcess;
  31977. })(BABYLON.PostProcess);
  31978. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  31979. })(BABYLON || (BABYLON = {}));
  31980. var BABYLON;
  31981. (function (BABYLON) {
  31982. var ConvolutionPostProcess = (function (_super) {
  31983. __extends(ConvolutionPostProcess, _super);
  31984. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  31985. var _this = this;
  31986. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  31987. this.kernel = kernel;
  31988. this.onApply = function (effect) {
  31989. effect.setFloat2("screenSize", _this.width, _this.height);
  31990. effect.setArray("kernel", _this.kernel);
  31991. };
  31992. }
  31993. // Statics
  31994. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  31995. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  31996. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  31997. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  31998. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  31999. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32000. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32001. return ConvolutionPostProcess;
  32002. })(BABYLON.PostProcess);
  32003. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32004. })(BABYLON || (BABYLON = {}));
  32005. var BABYLON;
  32006. (function (BABYLON) {
  32007. var FilterPostProcess = (function (_super) {
  32008. __extends(FilterPostProcess, _super);
  32009. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32010. var _this = this;
  32011. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32012. this.kernelMatrix = kernelMatrix;
  32013. this.onApply = function (effect) {
  32014. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32015. };
  32016. }
  32017. return FilterPostProcess;
  32018. })(BABYLON.PostProcess);
  32019. BABYLON.FilterPostProcess = FilterPostProcess;
  32020. })(BABYLON || (BABYLON = {}));
  32021. var BABYLON;
  32022. (function (BABYLON) {
  32023. var FxaaPostProcess = (function (_super) {
  32024. __extends(FxaaPostProcess, _super);
  32025. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32026. var _this = this;
  32027. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32028. this.onSizeChanged = function () {
  32029. _this.texelWidth = 1.0 / _this.width;
  32030. _this.texelHeight = 1.0 / _this.height;
  32031. };
  32032. this.onApply = function (effect) {
  32033. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32034. };
  32035. }
  32036. return FxaaPostProcess;
  32037. })(BABYLON.PostProcess);
  32038. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32039. })(BABYLON || (BABYLON = {}));
  32040. var BABYLON;
  32041. (function (BABYLON) {
  32042. var StereoscopicInterlacePostProcess = (function (_super) {
  32043. __extends(StereoscopicInterlacePostProcess, _super);
  32044. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32045. var _this = this;
  32046. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32047. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32048. this.onSizeChanged = function () {
  32049. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32050. };
  32051. this.onApply = function (effect) {
  32052. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32053. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32054. };
  32055. }
  32056. return StereoscopicInterlacePostProcess;
  32057. })(BABYLON.PostProcess);
  32058. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32059. })(BABYLON || (BABYLON = {}));
  32060. var BABYLON;
  32061. (function (BABYLON) {
  32062. var LensFlare = (function () {
  32063. function LensFlare(size, position, color, imgUrl, system) {
  32064. this.size = size;
  32065. this.position = position;
  32066. this.dispose = function () {
  32067. if (this.texture) {
  32068. this.texture.dispose();
  32069. }
  32070. // Remove from scene
  32071. var index = this._system.lensFlares.indexOf(this);
  32072. this._system.lensFlares.splice(index, 1);
  32073. };
  32074. this.color = color || new BABYLON.Color3(1, 1, 1);
  32075. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32076. this._system = system;
  32077. system.lensFlares.push(this);
  32078. }
  32079. return LensFlare;
  32080. })();
  32081. BABYLON.LensFlare = LensFlare;
  32082. })(BABYLON || (BABYLON = {}));
  32083. var BABYLON;
  32084. (function (BABYLON) {
  32085. var LensFlareSystem = (function () {
  32086. function LensFlareSystem(name, emitter, scene) {
  32087. this.name = name;
  32088. this.lensFlares = new Array();
  32089. this.borderLimit = 300;
  32090. this.layerMask = 0x0FFFFFFF;
  32091. this._vertexDeclaration = [2];
  32092. this._vertexStrideSize = 2 * 4;
  32093. this._isEnabled = true;
  32094. this._scene = scene;
  32095. this._emitter = emitter;
  32096. scene.lensFlareSystems.push(this);
  32097. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32098. // VBO
  32099. var vertices = [];
  32100. vertices.push(1, 1);
  32101. vertices.push(-1, 1);
  32102. vertices.push(-1, -1);
  32103. vertices.push(1, -1);
  32104. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32105. // Indices
  32106. var indices = [];
  32107. indices.push(0);
  32108. indices.push(1);
  32109. indices.push(2);
  32110. indices.push(0);
  32111. indices.push(2);
  32112. indices.push(3);
  32113. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32114. // Effects
  32115. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32116. }
  32117. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32118. get: function () {
  32119. return this._isEnabled;
  32120. },
  32121. set: function (value) {
  32122. this._isEnabled = value;
  32123. },
  32124. enumerable: true,
  32125. configurable: true
  32126. });
  32127. LensFlareSystem.prototype.getScene = function () {
  32128. return this._scene;
  32129. };
  32130. LensFlareSystem.prototype.getEmitter = function () {
  32131. return this._emitter;
  32132. };
  32133. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32134. this._emitter = newEmitter;
  32135. };
  32136. LensFlareSystem.prototype.getEmitterPosition = function () {
  32137. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32138. };
  32139. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32140. var position = this.getEmitterPosition();
  32141. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32142. this._positionX = position.x;
  32143. this._positionY = position.y;
  32144. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32145. if (position.z > 0) {
  32146. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32147. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32148. return true;
  32149. }
  32150. }
  32151. return false;
  32152. };
  32153. LensFlareSystem.prototype._isVisible = function () {
  32154. if (!this._isEnabled) {
  32155. return false;
  32156. }
  32157. var emitterPosition = this.getEmitterPosition();
  32158. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32159. var distance = direction.length();
  32160. direction.normalize();
  32161. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32162. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32163. return !pickInfo.hit || pickInfo.distance > distance;
  32164. };
  32165. LensFlareSystem.prototype.render = function () {
  32166. if (!this._effect.isReady())
  32167. return false;
  32168. var engine = this._scene.getEngine();
  32169. var viewport = this._scene.activeCamera.viewport;
  32170. var globalViewport = viewport.toGlobal(engine);
  32171. // Position
  32172. if (!this.computeEffectivePosition(globalViewport)) {
  32173. return false;
  32174. }
  32175. // Visibility
  32176. if (!this._isVisible()) {
  32177. return false;
  32178. }
  32179. // Intensity
  32180. var awayX;
  32181. var awayY;
  32182. if (this._positionX < this.borderLimit + globalViewport.x) {
  32183. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32184. }
  32185. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32186. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32187. }
  32188. else {
  32189. awayX = 0;
  32190. }
  32191. if (this._positionY < this.borderLimit + globalViewport.y) {
  32192. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32193. }
  32194. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32195. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32196. }
  32197. else {
  32198. awayY = 0;
  32199. }
  32200. var away = (awayX > awayY) ? awayX : awayY;
  32201. if (away > this.borderLimit) {
  32202. away = this.borderLimit;
  32203. }
  32204. var intensity = 1.0 - (away / this.borderLimit);
  32205. if (intensity < 0) {
  32206. return false;
  32207. }
  32208. if (intensity > 1.0) {
  32209. intensity = 1.0;
  32210. }
  32211. // Position
  32212. var centerX = globalViewport.x + globalViewport.width / 2;
  32213. var centerY = globalViewport.y + globalViewport.height / 2;
  32214. var distX = centerX - this._positionX;
  32215. var distY = centerY - this._positionY;
  32216. // Effects
  32217. engine.enableEffect(this._effect);
  32218. engine.setState(false);
  32219. engine.setDepthBuffer(false);
  32220. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32221. // VBOs
  32222. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32223. // Flares
  32224. for (var index = 0; index < this.lensFlares.length; index++) {
  32225. var flare = this.lensFlares[index];
  32226. var x = centerX - (distX * flare.position);
  32227. var y = centerY - (distY * flare.position);
  32228. var cw = flare.size;
  32229. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32230. var cx = 2 * (x / globalViewport.width) - 1.0;
  32231. var cy = 1.0 - 2 * (y / globalViewport.height);
  32232. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32233. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32234. // Texture
  32235. this._effect.setTexture("textureSampler", flare.texture);
  32236. // Color
  32237. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32238. // Draw order
  32239. engine.draw(true, 0, 6);
  32240. }
  32241. engine.setDepthBuffer(true);
  32242. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32243. return true;
  32244. };
  32245. LensFlareSystem.prototype.dispose = function () {
  32246. if (this._vertexBuffer) {
  32247. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32248. this._vertexBuffer = null;
  32249. }
  32250. if (this._indexBuffer) {
  32251. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32252. this._indexBuffer = null;
  32253. }
  32254. while (this.lensFlares.length) {
  32255. this.lensFlares[0].dispose();
  32256. }
  32257. // Remove from scene
  32258. var index = this._scene.lensFlareSystems.indexOf(this);
  32259. this._scene.lensFlareSystems.splice(index, 1);
  32260. };
  32261. return LensFlareSystem;
  32262. })();
  32263. BABYLON.LensFlareSystem = LensFlareSystem;
  32264. })(BABYLON || (BABYLON = {}));
  32265. var BABYLON;
  32266. (function (BABYLON) {
  32267. // We're mainly based on the logic defined into the FreeCamera code
  32268. var DeviceOrientationCamera = (function (_super) {
  32269. __extends(DeviceOrientationCamera, _super);
  32270. function DeviceOrientationCamera(name, position, scene) {
  32271. var _this = this;
  32272. _super.call(this, name, position, scene);
  32273. this._offsetX = null;
  32274. this._offsetY = null;
  32275. this._orientationGamma = 0;
  32276. this._orientationBeta = 0;
  32277. this._initialOrientationGamma = 0;
  32278. this._initialOrientationBeta = 0;
  32279. this.angularSensibility = 10000.0;
  32280. this.moveSensibility = 50.0;
  32281. window.addEventListener("resize", function () {
  32282. _this._initialOrientationGamma = null;
  32283. }, false);
  32284. }
  32285. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32286. var _this = this;
  32287. if (this._attachedCanvas) {
  32288. return;
  32289. }
  32290. this._attachedCanvas = canvas;
  32291. if (!this._orientationChanged) {
  32292. this._orientationChanged = function (evt) {
  32293. if (!_this._initialOrientationGamma) {
  32294. _this._initialOrientationGamma = evt.gamma;
  32295. _this._initialOrientationBeta = evt.beta;
  32296. }
  32297. _this._orientationGamma = evt.gamma;
  32298. _this._orientationBeta = evt.beta;
  32299. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32300. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32301. };
  32302. }
  32303. window.addEventListener("deviceorientation", this._orientationChanged);
  32304. };
  32305. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32306. if (this._attachedCanvas != canvas) {
  32307. return;
  32308. }
  32309. window.removeEventListener("deviceorientation", this._orientationChanged);
  32310. this._attachedCanvas = null;
  32311. this._orientationGamma = 0;
  32312. this._orientationBeta = 0;
  32313. this._initialOrientationGamma = 0;
  32314. this._initialOrientationBeta = 0;
  32315. };
  32316. DeviceOrientationCamera.prototype._checkInputs = function () {
  32317. if (!this._offsetX) {
  32318. return;
  32319. }
  32320. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32321. var speed = this._computeLocalCameraSpeed();
  32322. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32323. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32324. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32325. _super.prototype._checkInputs.call(this);
  32326. };
  32327. return DeviceOrientationCamera;
  32328. })(BABYLON.FreeCamera);
  32329. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32330. })(BABYLON || (BABYLON = {}));
  32331. var BABYLON;
  32332. (function (BABYLON) {
  32333. var Gamepads = (function () {
  32334. function Gamepads(ongamedpadconnected) {
  32335. var _this = this;
  32336. this.babylonGamepads = [];
  32337. this.oneGamepadConnected = false;
  32338. this.isMonitoring = false;
  32339. this.gamepadEventSupported = 'GamepadEvent' in window;
  32340. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32341. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32342. 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=";
  32343. this._callbackGamepadConnected = ongamedpadconnected;
  32344. if (this.gamepadSupportAvailable) {
  32345. // Checking if the gamepad connected event is supported (like in Firefox)
  32346. if (this.gamepadEventSupported) {
  32347. window.addEventListener('gamepadconnected', function (evt) {
  32348. _this._onGamepadConnected(evt);
  32349. }, false);
  32350. window.addEventListener('gamepaddisconnected', function (evt) {
  32351. _this._onGamepadDisconnected(evt);
  32352. }, false);
  32353. }
  32354. else {
  32355. this._startMonitoringGamepads();
  32356. }
  32357. if (!this.oneGamepadConnected) {
  32358. this._insertGamepadDOMInstructions();
  32359. }
  32360. }
  32361. else {
  32362. this._insertGamepadDOMNotSupported();
  32363. }
  32364. }
  32365. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32366. Gamepads.gamepadDOMInfo = document.createElement("div");
  32367. var buttonAImage = document.createElement("img");
  32368. buttonAImage.src = this.buttonADataURL;
  32369. var spanMessage = document.createElement("span");
  32370. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32371. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32372. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32373. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32374. Gamepads.gamepadDOMInfo.style.width = "100%";
  32375. Gamepads.gamepadDOMInfo.style.height = "48px";
  32376. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32377. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32378. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32379. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32380. buttonAImage.style.position = "relative";
  32381. buttonAImage.style.bottom = "8px";
  32382. spanMessage.style.position = "relative";
  32383. spanMessage.style.fontSize = "32px";
  32384. spanMessage.style.bottom = "32px";
  32385. spanMessage.style.color = "green";
  32386. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32387. };
  32388. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32389. Gamepads.gamepadDOMInfo = document.createElement("div");
  32390. var spanMessage = document.createElement("span");
  32391. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32392. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32393. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32394. Gamepads.gamepadDOMInfo.style.width = "100%";
  32395. Gamepads.gamepadDOMInfo.style.height = "40px";
  32396. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32397. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32398. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32399. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32400. spanMessage.style.position = "relative";
  32401. spanMessage.style.fontSize = "32px";
  32402. spanMessage.style.color = "red";
  32403. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32404. };
  32405. Gamepads.prototype.dispose = function () {
  32406. if (Gamepads.gamepadDOMInfo) {
  32407. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32408. }
  32409. };
  32410. Gamepads.prototype._onGamepadConnected = function (evt) {
  32411. var newGamepad = this._addNewGamepad(evt.gamepad);
  32412. if (this._callbackGamepadConnected)
  32413. this._callbackGamepadConnected(newGamepad);
  32414. this._startMonitoringGamepads();
  32415. };
  32416. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32417. if (!this.oneGamepadConnected) {
  32418. this.oneGamepadConnected = true;
  32419. if (Gamepads.gamepadDOMInfo) {
  32420. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32421. Gamepads.gamepadDOMInfo = null;
  32422. }
  32423. }
  32424. var newGamepad;
  32425. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32426. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32427. }
  32428. else {
  32429. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32430. }
  32431. this.babylonGamepads.push(newGamepad);
  32432. return newGamepad;
  32433. };
  32434. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32435. // Remove the gamepad from the list of gamepads to monitor.
  32436. for (var i in this.babylonGamepads) {
  32437. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32438. this.babylonGamepads.splice(i, 1);
  32439. break;
  32440. }
  32441. }
  32442. // If no gamepads are left, stop the polling loop.
  32443. if (this.babylonGamepads.length == 0) {
  32444. this._stopMonitoringGamepads();
  32445. }
  32446. };
  32447. Gamepads.prototype._startMonitoringGamepads = function () {
  32448. if (!this.isMonitoring) {
  32449. this.isMonitoring = true;
  32450. this._checkGamepadsStatus();
  32451. }
  32452. };
  32453. Gamepads.prototype._stopMonitoringGamepads = function () {
  32454. this.isMonitoring = false;
  32455. };
  32456. Gamepads.prototype._checkGamepadsStatus = function () {
  32457. var _this = this;
  32458. // updating gamepad objects
  32459. this._updateGamepadObjects();
  32460. for (var i in this.babylonGamepads) {
  32461. this.babylonGamepads[i].update();
  32462. }
  32463. if (this.isMonitoring) {
  32464. if (window.requestAnimationFrame) {
  32465. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32466. }
  32467. else if (window.mozRequestAnimationFrame) {
  32468. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32469. }
  32470. else if (window.webkitRequestAnimationFrame) {
  32471. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32472. }
  32473. }
  32474. };
  32475. // This function is called only on Chrome, which does not yet support
  32476. // connection/disconnection events, but requires you to monitor
  32477. // an array for changes.
  32478. Gamepads.prototype._updateGamepadObjects = function () {
  32479. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32480. for (var i = 0; i < gamepads.length; i++) {
  32481. if (gamepads[i]) {
  32482. if (!(gamepads[i].index in this.babylonGamepads)) {
  32483. var newGamepad = this._addNewGamepad(gamepads[i]);
  32484. if (this._callbackGamepadConnected) {
  32485. this._callbackGamepadConnected(newGamepad);
  32486. }
  32487. }
  32488. else {
  32489. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32490. }
  32491. }
  32492. }
  32493. };
  32494. return Gamepads;
  32495. })();
  32496. BABYLON.Gamepads = Gamepads;
  32497. var StickValues = (function () {
  32498. function StickValues(x, y) {
  32499. this.x = x;
  32500. this.y = y;
  32501. }
  32502. return StickValues;
  32503. })();
  32504. BABYLON.StickValues = StickValues;
  32505. var Gamepad = (function () {
  32506. function Gamepad(id, index, browserGamepad) {
  32507. this.id = id;
  32508. this.index = index;
  32509. this.browserGamepad = browserGamepad;
  32510. if (this.browserGamepad.axes.length >= 2) {
  32511. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32512. }
  32513. if (this.browserGamepad.axes.length >= 4) {
  32514. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32515. }
  32516. }
  32517. Gamepad.prototype.onleftstickchanged = function (callback) {
  32518. this._onleftstickchanged = callback;
  32519. };
  32520. Gamepad.prototype.onrightstickchanged = function (callback) {
  32521. this._onrightstickchanged = callback;
  32522. };
  32523. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32524. get: function () {
  32525. return this._leftStick;
  32526. },
  32527. set: function (newValues) {
  32528. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32529. this._onleftstickchanged(newValues);
  32530. }
  32531. this._leftStick = newValues;
  32532. },
  32533. enumerable: true,
  32534. configurable: true
  32535. });
  32536. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32537. get: function () {
  32538. return this._rightStick;
  32539. },
  32540. set: function (newValues) {
  32541. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32542. this._onrightstickchanged(newValues);
  32543. }
  32544. this._rightStick = newValues;
  32545. },
  32546. enumerable: true,
  32547. configurable: true
  32548. });
  32549. Gamepad.prototype.update = function () {
  32550. if (this._leftStick) {
  32551. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32552. }
  32553. if (this._rightStick) {
  32554. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32555. }
  32556. };
  32557. return Gamepad;
  32558. })();
  32559. BABYLON.Gamepad = Gamepad;
  32560. var GenericPad = (function (_super) {
  32561. __extends(GenericPad, _super);
  32562. function GenericPad(id, index, gamepad) {
  32563. _super.call(this, id, index, gamepad);
  32564. this.id = id;
  32565. this.index = index;
  32566. this.gamepad = gamepad;
  32567. this._buttons = new Array(gamepad.buttons.length);
  32568. }
  32569. GenericPad.prototype.onbuttondown = function (callback) {
  32570. this._onbuttondown = callback;
  32571. };
  32572. GenericPad.prototype.onbuttonup = function (callback) {
  32573. this._onbuttonup = callback;
  32574. };
  32575. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32576. if (newValue !== currentValue) {
  32577. if (this._onbuttondown && newValue === 1) {
  32578. this._onbuttondown(buttonIndex);
  32579. }
  32580. if (this._onbuttonup && newValue === 0) {
  32581. this._onbuttonup(buttonIndex);
  32582. }
  32583. }
  32584. return newValue;
  32585. };
  32586. GenericPad.prototype.update = function () {
  32587. _super.prototype.update.call(this);
  32588. for (var index = 0; index < this._buttons.length; index++) {
  32589. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32590. }
  32591. };
  32592. return GenericPad;
  32593. })(Gamepad);
  32594. BABYLON.GenericPad = GenericPad;
  32595. (function (Xbox360Button) {
  32596. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32597. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32598. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  32599. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  32600. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  32601. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  32602. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  32603. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  32604. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  32605. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  32606. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  32607. var Xbox360Button = BABYLON.Xbox360Button;
  32608. (function (Xbox360Dpad) {
  32609. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  32610. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  32611. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  32612. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  32613. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  32614. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  32615. var Xbox360Pad = (function (_super) {
  32616. __extends(Xbox360Pad, _super);
  32617. function Xbox360Pad() {
  32618. _super.apply(this, arguments);
  32619. this._leftTrigger = 0;
  32620. this._rightTrigger = 0;
  32621. this._buttonA = 0;
  32622. this._buttonB = 0;
  32623. this._buttonX = 0;
  32624. this._buttonY = 0;
  32625. this._buttonBack = 0;
  32626. this._buttonStart = 0;
  32627. this._buttonLB = 0;
  32628. this._buttonRB = 0;
  32629. this._buttonLeftStick = 0;
  32630. this._buttonRightStick = 0;
  32631. this._dPadUp = 0;
  32632. this._dPadDown = 0;
  32633. this._dPadLeft = 0;
  32634. this._dPadRight = 0;
  32635. }
  32636. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  32637. this._onlefttriggerchanged = callback;
  32638. };
  32639. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  32640. this._onrighttriggerchanged = callback;
  32641. };
  32642. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  32643. get: function () {
  32644. return this._leftTrigger;
  32645. },
  32646. set: function (newValue) {
  32647. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  32648. this._onlefttriggerchanged(newValue);
  32649. }
  32650. this._leftTrigger = newValue;
  32651. },
  32652. enumerable: true,
  32653. configurable: true
  32654. });
  32655. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  32656. get: function () {
  32657. return this._rightTrigger;
  32658. },
  32659. set: function (newValue) {
  32660. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  32661. this._onrighttriggerchanged(newValue);
  32662. }
  32663. this._rightTrigger = newValue;
  32664. },
  32665. enumerable: true,
  32666. configurable: true
  32667. });
  32668. Xbox360Pad.prototype.onbuttondown = function (callback) {
  32669. this._onbuttondown = callback;
  32670. };
  32671. Xbox360Pad.prototype.onbuttonup = function (callback) {
  32672. this._onbuttonup = callback;
  32673. };
  32674. Xbox360Pad.prototype.ondpaddown = function (callback) {
  32675. this._ondpaddown = callback;
  32676. };
  32677. Xbox360Pad.prototype.ondpadup = function (callback) {
  32678. this._ondpadup = callback;
  32679. };
  32680. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  32681. if (newValue !== currentValue) {
  32682. if (this._onbuttondown && newValue === 1) {
  32683. this._onbuttondown(buttonType);
  32684. }
  32685. if (this._onbuttonup && newValue === 0) {
  32686. this._onbuttonup(buttonType);
  32687. }
  32688. }
  32689. return newValue;
  32690. };
  32691. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  32692. if (newValue !== currentValue) {
  32693. if (this._ondpaddown && newValue === 1) {
  32694. this._ondpaddown(buttonType);
  32695. }
  32696. if (this._ondpadup && newValue === 0) {
  32697. this._ondpadup(buttonType);
  32698. }
  32699. }
  32700. return newValue;
  32701. };
  32702. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  32703. get: function () {
  32704. return this._buttonA;
  32705. },
  32706. set: function (value) {
  32707. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  32708. },
  32709. enumerable: true,
  32710. configurable: true
  32711. });
  32712. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  32713. get: function () {
  32714. return this._buttonB;
  32715. },
  32716. set: function (value) {
  32717. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  32718. },
  32719. enumerable: true,
  32720. configurable: true
  32721. });
  32722. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  32723. get: function () {
  32724. return this._buttonX;
  32725. },
  32726. set: function (value) {
  32727. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  32728. },
  32729. enumerable: true,
  32730. configurable: true
  32731. });
  32732. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  32733. get: function () {
  32734. return this._buttonY;
  32735. },
  32736. set: function (value) {
  32737. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  32738. },
  32739. enumerable: true,
  32740. configurable: true
  32741. });
  32742. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  32743. get: function () {
  32744. return this._buttonStart;
  32745. },
  32746. set: function (value) {
  32747. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  32748. },
  32749. enumerable: true,
  32750. configurable: true
  32751. });
  32752. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  32753. get: function () {
  32754. return this._buttonBack;
  32755. },
  32756. set: function (value) {
  32757. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  32758. },
  32759. enumerable: true,
  32760. configurable: true
  32761. });
  32762. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  32763. get: function () {
  32764. return this._buttonLB;
  32765. },
  32766. set: function (value) {
  32767. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  32768. },
  32769. enumerable: true,
  32770. configurable: true
  32771. });
  32772. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  32773. get: function () {
  32774. return this._buttonRB;
  32775. },
  32776. set: function (value) {
  32777. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  32778. },
  32779. enumerable: true,
  32780. configurable: true
  32781. });
  32782. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  32783. get: function () {
  32784. return this._buttonLeftStick;
  32785. },
  32786. set: function (value) {
  32787. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  32788. },
  32789. enumerable: true,
  32790. configurable: true
  32791. });
  32792. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  32793. get: function () {
  32794. return this._buttonRightStick;
  32795. },
  32796. set: function (value) {
  32797. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  32798. },
  32799. enumerable: true,
  32800. configurable: true
  32801. });
  32802. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  32803. get: function () {
  32804. return this._dPadUp;
  32805. },
  32806. set: function (value) {
  32807. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  32808. },
  32809. enumerable: true,
  32810. configurable: true
  32811. });
  32812. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  32813. get: function () {
  32814. return this._dPadDown;
  32815. },
  32816. set: function (value) {
  32817. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  32818. },
  32819. enumerable: true,
  32820. configurable: true
  32821. });
  32822. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  32823. get: function () {
  32824. return this._dPadLeft;
  32825. },
  32826. set: function (value) {
  32827. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  32828. },
  32829. enumerable: true,
  32830. configurable: true
  32831. });
  32832. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  32833. get: function () {
  32834. return this._dPadRight;
  32835. },
  32836. set: function (value) {
  32837. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  32838. },
  32839. enumerable: true,
  32840. configurable: true
  32841. });
  32842. Xbox360Pad.prototype.update = function () {
  32843. _super.prototype.update.call(this);
  32844. this.buttonA = this.browserGamepad.buttons[0].value;
  32845. this.buttonB = this.browserGamepad.buttons[1].value;
  32846. this.buttonX = this.browserGamepad.buttons[2].value;
  32847. this.buttonY = this.browserGamepad.buttons[3].value;
  32848. this.buttonLB = this.browserGamepad.buttons[4].value;
  32849. this.buttonRB = this.browserGamepad.buttons[5].value;
  32850. this.leftTrigger = this.browserGamepad.buttons[6].value;
  32851. this.rightTrigger = this.browserGamepad.buttons[7].value;
  32852. this.buttonBack = this.browserGamepad.buttons[8].value;
  32853. this.buttonStart = this.browserGamepad.buttons[9].value;
  32854. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  32855. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  32856. this.dPadUp = this.browserGamepad.buttons[12].value;
  32857. this.dPadDown = this.browserGamepad.buttons[13].value;
  32858. this.dPadLeft = this.browserGamepad.buttons[14].value;
  32859. this.dPadRight = this.browserGamepad.buttons[15].value;
  32860. };
  32861. return Xbox360Pad;
  32862. })(Gamepad);
  32863. BABYLON.Xbox360Pad = Xbox360Pad;
  32864. })(BABYLON || (BABYLON = {}));
  32865. var BABYLON;
  32866. (function (BABYLON) {
  32867. // We're mainly based on the logic defined into the FreeCamera code
  32868. var GamepadCamera = (function (_super) {
  32869. __extends(GamepadCamera, _super);
  32870. function GamepadCamera(name, position, scene) {
  32871. var _this = this;
  32872. _super.call(this, name, position, scene);
  32873. this.angularSensibility = 200;
  32874. this.moveSensibility = 75;
  32875. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  32876. }
  32877. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  32878. // Only the first gamepad can control the camera
  32879. if (gamepad.index === 0) {
  32880. this._gamepad = gamepad;
  32881. }
  32882. };
  32883. GamepadCamera.prototype._checkInputs = function () {
  32884. if (this._gamepad) {
  32885. var LSValues = this._gamepad.leftStick;
  32886. var normalizedLX = LSValues.x / this.moveSensibility;
  32887. var normalizedLY = LSValues.y / this.moveSensibility;
  32888. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  32889. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  32890. var RSValues = this._gamepad.rightStick;
  32891. var normalizedRX = RSValues.x / this.angularSensibility;
  32892. var normalizedRY = RSValues.y / this.angularSensibility;
  32893. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  32894. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  32895. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32896. var speed = this._computeLocalCameraSpeed() * 50.0;
  32897. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  32898. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32899. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  32900. }
  32901. _super.prototype._checkInputs.call(this);
  32902. };
  32903. GamepadCamera.prototype.dispose = function () {
  32904. this._gamepads.dispose();
  32905. _super.prototype.dispose.call(this);
  32906. };
  32907. return GamepadCamera;
  32908. })(BABYLON.FreeCamera);
  32909. BABYLON.GamepadCamera = GamepadCamera;
  32910. })(BABYLON || (BABYLON = {}));
  32911. var BABYLON;
  32912. (function (BABYLON) {
  32913. var Analyser = (function () {
  32914. function Analyser(scene) {
  32915. this.SMOOTHING = 0.75;
  32916. this.FFT_SIZE = 512;
  32917. this.BARGRAPHAMPLITUDE = 256;
  32918. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32919. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32920. this._scene = scene;
  32921. this._audioEngine = BABYLON.Engine.audioEngine;
  32922. if (this._audioEngine.canUseWebAudio) {
  32923. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32924. this._webAudioAnalyser.minDecibels = -140;
  32925. this._webAudioAnalyser.maxDecibels = 0;
  32926. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32927. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32928. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32929. }
  32930. }
  32931. Analyser.prototype.getFrequencyBinCount = function () {
  32932. if (this._audioEngine.canUseWebAudio) {
  32933. return this._webAudioAnalyser.frequencyBinCount;
  32934. }
  32935. else {
  32936. return 0;
  32937. }
  32938. };
  32939. Analyser.prototype.getByteFrequencyData = function () {
  32940. if (this._audioEngine.canUseWebAudio) {
  32941. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32942. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32943. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32944. }
  32945. return this._byteFreqs;
  32946. };
  32947. Analyser.prototype.getByteTimeDomainData = function () {
  32948. if (this._audioEngine.canUseWebAudio) {
  32949. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32950. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32951. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32952. }
  32953. return this._byteTime;
  32954. };
  32955. Analyser.prototype.getFloatFrequencyData = function () {
  32956. if (this._audioEngine.canUseWebAudio) {
  32957. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32958. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32959. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32960. }
  32961. return this._floatFreqs;
  32962. };
  32963. Analyser.prototype.drawDebugCanvas = function () {
  32964. var _this = this;
  32965. if (this._audioEngine.canUseWebAudio) {
  32966. if (!this._debugCanvas) {
  32967. this._debugCanvas = document.createElement("canvas");
  32968. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32969. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32970. this._debugCanvas.style.position = "absolute";
  32971. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32972. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32973. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32974. document.body.appendChild(this._debugCanvas);
  32975. this._registerFunc = function () {
  32976. _this.drawDebugCanvas();
  32977. };
  32978. this._scene.registerBeforeRender(this._registerFunc);
  32979. }
  32980. if (this._registerFunc) {
  32981. var workingArray = this.getByteFrequencyData();
  32982. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32983. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32984. // Draw the frequency domain chart.
  32985. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32986. var value = workingArray[i];
  32987. var percent = value / this.BARGRAPHAMPLITUDE;
  32988. var height = this.DEBUGCANVASSIZE.height * percent;
  32989. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32990. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32991. var hue = i / this.getFrequencyBinCount() * 360;
  32992. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32993. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32994. }
  32995. }
  32996. }
  32997. };
  32998. Analyser.prototype.stopDebugCanvas = function () {
  32999. if (this._debugCanvas) {
  33000. this._scene.unregisterBeforeRender(this._registerFunc);
  33001. this._registerFunc = null;
  33002. document.body.removeChild(this._debugCanvas);
  33003. this._debugCanvas = null;
  33004. this._debugCanvasContext = null;
  33005. }
  33006. };
  33007. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33008. if (this._audioEngine.canUseWebAudio) {
  33009. inputAudioNode.connect(this._webAudioAnalyser);
  33010. this._webAudioAnalyser.connect(outputAudioNode);
  33011. }
  33012. };
  33013. Analyser.prototype.dispose = function () {
  33014. if (this._audioEngine.canUseWebAudio) {
  33015. this._webAudioAnalyser.disconnect();
  33016. }
  33017. };
  33018. return Analyser;
  33019. })();
  33020. BABYLON.Analyser = Analyser;
  33021. })(BABYLON || (BABYLON = {}));
  33022. var BABYLON;
  33023. (function (BABYLON) {
  33024. var AudioEngine = (function () {
  33025. function AudioEngine() {
  33026. this._audioContext = null;
  33027. this._audioContextInitialized = false;
  33028. this.canUseWebAudio = false;
  33029. this.WarnedWebAudioUnsupported = false;
  33030. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33031. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33032. this.canUseWebAudio = true;
  33033. }
  33034. }
  33035. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33036. get: function () {
  33037. if (!this._audioContextInitialized) {
  33038. this._initializeAudioContext();
  33039. }
  33040. return this._audioContext;
  33041. },
  33042. enumerable: true,
  33043. configurable: true
  33044. });
  33045. AudioEngine.prototype._initializeAudioContext = function () {
  33046. try {
  33047. if (this.canUseWebAudio) {
  33048. this._audioContext = new AudioContext();
  33049. // create a global volume gain node
  33050. this.masterGain = this._audioContext.createGain();
  33051. this.masterGain.gain.value = 1;
  33052. this.masterGain.connect(this._audioContext.destination);
  33053. this._audioContextInitialized = true;
  33054. }
  33055. }
  33056. catch (e) {
  33057. this.canUseWebAudio = false;
  33058. BABYLON.Tools.Error("Web Audio: " + e.message);
  33059. }
  33060. };
  33061. AudioEngine.prototype.dispose = function () {
  33062. if (this.canUseWebAudio && this._audioContextInitialized) {
  33063. if (this._connectedAnalyser) {
  33064. this._connectedAnalyser.stopDebugCanvas();
  33065. this._connectedAnalyser.dispose();
  33066. this.masterGain.disconnect();
  33067. this.masterGain.connect(this._audioContext.destination);
  33068. this._connectedAnalyser = null;
  33069. }
  33070. this.masterGain.gain.value = 1;
  33071. }
  33072. this.WarnedWebAudioUnsupported = false;
  33073. };
  33074. AudioEngine.prototype.getGlobalVolume = function () {
  33075. if (this.canUseWebAudio && this._audioContextInitialized) {
  33076. return this.masterGain.gain.value;
  33077. }
  33078. else {
  33079. return -1;
  33080. }
  33081. };
  33082. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33083. if (this.canUseWebAudio && this._audioContextInitialized) {
  33084. this.masterGain.gain.value = newVolume;
  33085. }
  33086. };
  33087. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33088. if (this._connectedAnalyser) {
  33089. this._connectedAnalyser.stopDebugCanvas();
  33090. }
  33091. if (this.canUseWebAudio && this._audioContextInitialized) {
  33092. this._connectedAnalyser = analyser;
  33093. this.masterGain.disconnect();
  33094. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33095. }
  33096. };
  33097. return AudioEngine;
  33098. })();
  33099. BABYLON.AudioEngine = AudioEngine;
  33100. })(BABYLON || (BABYLON = {}));
  33101. var BABYLON;
  33102. (function (BABYLON) {
  33103. var Sound = (function () {
  33104. /**
  33105. * Create a sound and attach it to a scene
  33106. * @param name Name of your sound
  33107. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33108. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33109. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33110. */
  33111. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33112. var _this = this;
  33113. this.autoplay = false;
  33114. this.loop = false;
  33115. this.useCustomAttenuation = false;
  33116. this.spatialSound = false;
  33117. this.refDistance = 1;
  33118. this.rolloffFactor = 1;
  33119. this.maxDistance = 100;
  33120. this.distanceModel = "linear";
  33121. this._panningModel = "equalpower";
  33122. this._playbackRate = 1;
  33123. this._streaming = false;
  33124. this._startTime = 0;
  33125. this._startOffset = 0;
  33126. this._position = BABYLON.Vector3.Zero();
  33127. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33128. this._volume = 1;
  33129. this._isLoaded = false;
  33130. this._isReadyToPlay = false;
  33131. this.isPlaying = false;
  33132. this.isPaused = false;
  33133. this._isDirectional = false;
  33134. // Used if you'd like to create a directional sound.
  33135. // If not set, the sound will be omnidirectional
  33136. this._coneInnerAngle = 360;
  33137. this._coneOuterAngle = 360;
  33138. this._coneOuterGain = 0;
  33139. this._isOutputConnected = false;
  33140. this.name = name;
  33141. this._scene = scene;
  33142. this._readyToPlayCallback = readyToPlayCallback;
  33143. // Default custom attenuation function is a linear attenuation
  33144. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33145. if (currentDistance < maxDistance) {
  33146. return currentVolume * (1 - currentDistance / maxDistance);
  33147. }
  33148. else {
  33149. return 0;
  33150. }
  33151. };
  33152. if (options) {
  33153. this.autoplay = options.autoplay || false;
  33154. this.loop = options.loop || false;
  33155. // if volume === 0, we need another way to check this option
  33156. if (options.volume !== undefined) {
  33157. this._volume = options.volume;
  33158. }
  33159. this.spatialSound = options.spatialSound || false;
  33160. this.maxDistance = options.maxDistance || 100;
  33161. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33162. this.rolloffFactor = options.rolloffFactor || 1;
  33163. this.refDistance = options.refDistance || 1;
  33164. this.distanceModel = options.distanceModel || "linear";
  33165. this._playbackRate = options.playbackRate || 1;
  33166. this._streaming = options.streaming || false;
  33167. }
  33168. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33169. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33170. this._soundGain.gain.value = this._volume;
  33171. this._inputAudioNode = this._soundGain;
  33172. this._ouputAudioNode = this._soundGain;
  33173. if (this.spatialSound) {
  33174. this._createSpatialParameters();
  33175. }
  33176. this._scene.mainSoundTrack.AddSound(this);
  33177. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33178. if (urlOrArrayBuffer) {
  33179. // If it's an URL
  33180. if (typeof (urlOrArrayBuffer) === "string") {
  33181. // Loading sound using XHR2
  33182. if (!this._streaming) {
  33183. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33184. }
  33185. else {
  33186. this._htmlAudioElement = new Audio();
  33187. this._htmlAudioElement.src = urlOrArrayBuffer;
  33188. this._htmlAudioElement.controls = false;
  33189. this._htmlAudioElement.loop = this.loop;
  33190. this._isReadyToPlay = true;
  33191. document.body.appendChild(this._htmlAudioElement);
  33192. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33193. if (this._readyToPlayCallback) {
  33194. window.setTimeout(function () {
  33195. _this._readyToPlayCallback();
  33196. }, 1000);
  33197. }
  33198. if (this.autoplay) {
  33199. this.play();
  33200. }
  33201. }
  33202. }
  33203. else {
  33204. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33205. this._soundLoaded(urlOrArrayBuffer);
  33206. }
  33207. else {
  33208. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33209. }
  33210. }
  33211. }
  33212. }
  33213. else {
  33214. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33215. this._scene.mainSoundTrack.AddSound(this);
  33216. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33217. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33218. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33219. }
  33220. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33221. if (this._readyToPlayCallback) {
  33222. window.setTimeout(function () {
  33223. _this._readyToPlayCallback();
  33224. }, 1000);
  33225. }
  33226. }
  33227. }
  33228. Sound.prototype.dispose = function () {
  33229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33230. if (this.isPlaying) {
  33231. this.stop();
  33232. }
  33233. this._isReadyToPlay = false;
  33234. if (this.soundTrackId === -1) {
  33235. this._scene.mainSoundTrack.RemoveSound(this);
  33236. }
  33237. else {
  33238. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33239. }
  33240. if (this._soundGain) {
  33241. this._soundGain.disconnect();
  33242. this._soundGain = null;
  33243. }
  33244. if (this._soundPanner) {
  33245. this._soundPanner.disconnect();
  33246. this._soundPanner = null;
  33247. }
  33248. if (this._soundSource) {
  33249. this._soundSource.disconnect();
  33250. this._soundSource = null;
  33251. }
  33252. this._audioBuffer = null;
  33253. if (this._htmlAudioElement) {
  33254. this._htmlAudioElement.pause();
  33255. this._htmlAudioElement.src = "";
  33256. document.body.removeChild(this._htmlAudioElement);
  33257. }
  33258. if (this._connectedMesh) {
  33259. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33260. this._connectedMesh = null;
  33261. }
  33262. }
  33263. };
  33264. Sound.prototype._soundLoaded = function (audioData) {
  33265. var _this = this;
  33266. this._isLoaded = true;
  33267. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33268. _this._audioBuffer = buffer;
  33269. _this._isReadyToPlay = true;
  33270. if (_this.autoplay) {
  33271. _this.play();
  33272. }
  33273. if (_this._readyToPlayCallback) {
  33274. _this._readyToPlayCallback();
  33275. }
  33276. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33277. };
  33278. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33280. this._audioBuffer = audioBuffer;
  33281. this._isReadyToPlay = true;
  33282. }
  33283. };
  33284. Sound.prototype.updateOptions = function (options) {
  33285. if (options) {
  33286. this.loop = options.loop || this.loop;
  33287. this.maxDistance = options.maxDistance || this.maxDistance;
  33288. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33289. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33290. this.refDistance = options.refDistance || this.refDistance;
  33291. this.distanceModel = options.distanceModel || this.distanceModel;
  33292. this._playbackRate = options.playbackRate || this._playbackRate;
  33293. this._updateSpatialParameters();
  33294. if (this.isPlaying) {
  33295. if (this._streaming) {
  33296. this._htmlAudioElement.playbackRate = this._playbackRate;
  33297. }
  33298. else {
  33299. this._soundSource.playbackRate.value = this._playbackRate;
  33300. }
  33301. }
  33302. }
  33303. };
  33304. Sound.prototype._createSpatialParameters = function () {
  33305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33306. if (this._scene.headphone) {
  33307. this._panningModel = "HRTF";
  33308. }
  33309. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33310. this._updateSpatialParameters();
  33311. this._soundPanner.connect(this._ouputAudioNode);
  33312. this._inputAudioNode = this._soundPanner;
  33313. }
  33314. };
  33315. Sound.prototype._updateSpatialParameters = function () {
  33316. if (this.spatialSound) {
  33317. if (this.useCustomAttenuation) {
  33318. // Tricks to disable in a way embedded Web Audio attenuation
  33319. this._soundPanner.distanceModel = "linear";
  33320. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33321. this._soundPanner.refDistance = 1;
  33322. this._soundPanner.rolloffFactor = 1;
  33323. this._soundPanner.panningModel = this._panningModel;
  33324. }
  33325. else {
  33326. this._soundPanner.distanceModel = this.distanceModel;
  33327. this._soundPanner.maxDistance = this.maxDistance;
  33328. this._soundPanner.refDistance = this.refDistance;
  33329. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33330. this._soundPanner.panningModel = this._panningModel;
  33331. }
  33332. }
  33333. };
  33334. Sound.prototype.switchPanningModelToHRTF = function () {
  33335. this._panningModel = "HRTF";
  33336. this._switchPanningModel();
  33337. };
  33338. Sound.prototype.switchPanningModelToEqualPower = function () {
  33339. this._panningModel = "equalpower";
  33340. this._switchPanningModel();
  33341. };
  33342. Sound.prototype._switchPanningModel = function () {
  33343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33344. this._soundPanner.panningModel = this._panningModel;
  33345. }
  33346. };
  33347. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33348. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33349. if (this._isOutputConnected) {
  33350. this._ouputAudioNode.disconnect();
  33351. }
  33352. this._ouputAudioNode.connect(soundTrackAudioNode);
  33353. this._isOutputConnected = true;
  33354. }
  33355. };
  33356. /**
  33357. * Transform this sound into a directional source
  33358. * @param coneInnerAngle Size of the inner cone in degree
  33359. * @param coneOuterAngle Size of the outer cone in degree
  33360. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33361. */
  33362. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33363. if (coneOuterAngle < coneInnerAngle) {
  33364. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33365. return;
  33366. }
  33367. this._coneInnerAngle = coneInnerAngle;
  33368. this._coneOuterAngle = coneOuterAngle;
  33369. this._coneOuterGain = coneOuterGain;
  33370. this._isDirectional = true;
  33371. if (this.isPlaying && this.loop) {
  33372. this.stop();
  33373. this.play();
  33374. }
  33375. };
  33376. Sound.prototype.setPosition = function (newPosition) {
  33377. this._position = newPosition;
  33378. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33379. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33380. }
  33381. };
  33382. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33383. this._localDirection = newLocalDirection;
  33384. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33385. this._updateDirection();
  33386. }
  33387. };
  33388. Sound.prototype._updateDirection = function () {
  33389. var mat = this._connectedMesh.getWorldMatrix();
  33390. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33391. direction.normalize();
  33392. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33393. };
  33394. Sound.prototype.updateDistanceFromListener = function () {
  33395. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33396. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33397. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33398. }
  33399. };
  33400. Sound.prototype.setAttenuationFunction = function (callback) {
  33401. this._customAttenuationFunction = callback;
  33402. };
  33403. /**
  33404. * Play the sound
  33405. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33406. */
  33407. Sound.prototype.play = function (time) {
  33408. var _this = this;
  33409. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33410. try {
  33411. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33412. if (!this._soundSource || !this._streamingSource) {
  33413. if (this.spatialSound) {
  33414. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33415. if (this._isDirectional) {
  33416. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33417. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33418. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33419. if (this._connectedMesh) {
  33420. this._updateDirection();
  33421. }
  33422. else {
  33423. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33424. }
  33425. }
  33426. }
  33427. }
  33428. if (this._streaming) {
  33429. if (!this._streamingSource) {
  33430. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33431. this._htmlAudioElement.onended = function () { _this._onended(); };
  33432. this._htmlAudioElement.playbackRate = this._playbackRate;
  33433. }
  33434. this._streamingSource.disconnect();
  33435. this._streamingSource.connect(this._inputAudioNode);
  33436. this._htmlAudioElement.play();
  33437. }
  33438. else {
  33439. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33440. this._soundSource.buffer = this._audioBuffer;
  33441. this._soundSource.connect(this._inputAudioNode);
  33442. this._soundSource.loop = this.loop;
  33443. this._soundSource.playbackRate.value = this._playbackRate;
  33444. this._soundSource.onended = function () { _this._onended(); };
  33445. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33446. }
  33447. this._startTime = startTime;
  33448. this.isPlaying = true;
  33449. this.isPaused = false;
  33450. }
  33451. catch (ex) {
  33452. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33453. }
  33454. }
  33455. };
  33456. Sound.prototype._onended = function () {
  33457. this.isPlaying = false;
  33458. if (this.onended) {
  33459. this.onended();
  33460. }
  33461. };
  33462. /**
  33463. * Stop the sound
  33464. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33465. */
  33466. Sound.prototype.stop = function (time) {
  33467. if (this.isPlaying) {
  33468. if (this._streaming) {
  33469. this._htmlAudioElement.pause();
  33470. // Test needed for Firefox or it will generate an Invalid State Error
  33471. if (this._htmlAudioElement.currentTime > 0) {
  33472. this._htmlAudioElement.currentTime = 0;
  33473. }
  33474. }
  33475. else {
  33476. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33477. this._soundSource.stop(stopTime);
  33478. }
  33479. this.isPlaying = false;
  33480. }
  33481. };
  33482. Sound.prototype.pause = function () {
  33483. if (this.isPlaying) {
  33484. if (this._streaming) {
  33485. this._htmlAudioElement.pause();
  33486. }
  33487. else {
  33488. this.stop(0);
  33489. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33490. }
  33491. this.isPaused = true;
  33492. }
  33493. };
  33494. Sound.prototype.setVolume = function (newVolume, time) {
  33495. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33496. if (time) {
  33497. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33498. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33499. }
  33500. else {
  33501. this._soundGain.gain.value = newVolume;
  33502. }
  33503. }
  33504. this._volume = newVolume;
  33505. };
  33506. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33507. this._playbackRate = newPlaybackRate;
  33508. if (this.isPlaying) {
  33509. if (this._streaming) {
  33510. this._htmlAudioElement.playbackRate = this._playbackRate;
  33511. }
  33512. else {
  33513. this._soundSource.playbackRate.value = this._playbackRate;
  33514. }
  33515. }
  33516. };
  33517. Sound.prototype.getVolume = function () {
  33518. return this._volume;
  33519. };
  33520. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33521. var _this = this;
  33522. this._connectedMesh = meshToConnectTo;
  33523. if (!this.spatialSound) {
  33524. this.spatialSound = true;
  33525. this._createSpatialParameters();
  33526. if (this.isPlaying && this.loop) {
  33527. this.stop();
  33528. this.play();
  33529. }
  33530. }
  33531. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33532. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33533. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33534. };
  33535. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33536. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33537. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33538. this._updateDirection();
  33539. }
  33540. };
  33541. return Sound;
  33542. })();
  33543. BABYLON.Sound = Sound;
  33544. })(BABYLON || (BABYLON = {}));
  33545. var BABYLON;
  33546. (function (BABYLON) {
  33547. var SoundTrack = (function () {
  33548. function SoundTrack(scene, options) {
  33549. this.id = -1;
  33550. this._isMainTrack = false;
  33551. this._isInitialized = false;
  33552. this._scene = scene;
  33553. this.soundCollection = new Array();
  33554. this._options = options;
  33555. if (!this._isMainTrack) {
  33556. this._scene.soundTracks.push(this);
  33557. this.id = this._scene.soundTracks.length - 1;
  33558. }
  33559. }
  33560. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33561. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33562. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33563. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33564. if (this._options) {
  33565. if (this._options.volume) {
  33566. this._outputAudioNode.gain.value = this._options.volume;
  33567. }
  33568. if (this._options.mainTrack) {
  33569. this._isMainTrack = this._options.mainTrack;
  33570. }
  33571. }
  33572. this._isInitialized = true;
  33573. }
  33574. };
  33575. SoundTrack.prototype.dispose = function () {
  33576. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33577. if (this._connectedAnalyser) {
  33578. this._connectedAnalyser.stopDebugCanvas();
  33579. }
  33580. while (this.soundCollection.length) {
  33581. this.soundCollection[0].dispose();
  33582. }
  33583. if (this._outputAudioNode) {
  33584. this._outputAudioNode.disconnect();
  33585. }
  33586. this._outputAudioNode = null;
  33587. }
  33588. };
  33589. SoundTrack.prototype.AddSound = function (sound) {
  33590. if (!this._isInitialized) {
  33591. this._initializeSoundTrackAudioGraph();
  33592. }
  33593. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33594. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33595. }
  33596. if (sound.soundTrackId) {
  33597. if (sound.soundTrackId === -1) {
  33598. this._scene.mainSoundTrack.RemoveSound(sound);
  33599. }
  33600. else {
  33601. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33602. }
  33603. }
  33604. this.soundCollection.push(sound);
  33605. sound.soundTrackId = this.id;
  33606. };
  33607. SoundTrack.prototype.RemoveSound = function (sound) {
  33608. var index = this.soundCollection.indexOf(sound);
  33609. if (index !== -1) {
  33610. this.soundCollection.splice(index, 1);
  33611. }
  33612. };
  33613. SoundTrack.prototype.setVolume = function (newVolume) {
  33614. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33615. this._outputAudioNode.gain.value = newVolume;
  33616. }
  33617. };
  33618. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33620. for (var i = 0; i < this.soundCollection.length; i++) {
  33621. this.soundCollection[i].switchPanningModelToHRTF();
  33622. }
  33623. }
  33624. };
  33625. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33626. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33627. for (var i = 0; i < this.soundCollection.length; i++) {
  33628. this.soundCollection[i].switchPanningModelToEqualPower();
  33629. }
  33630. }
  33631. };
  33632. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33633. if (this._connectedAnalyser) {
  33634. this._connectedAnalyser.stopDebugCanvas();
  33635. }
  33636. this._connectedAnalyser = analyser;
  33637. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33638. this._outputAudioNode.disconnect();
  33639. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33640. }
  33641. };
  33642. return SoundTrack;
  33643. })();
  33644. BABYLON.SoundTrack = SoundTrack;
  33645. })(BABYLON || (BABYLON = {}));
  33646. var BABYLON;
  33647. (function (BABYLON) {
  33648. var DepthRenderer = (function () {
  33649. function DepthRenderer(scene, type) {
  33650. var _this = this;
  33651. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  33652. this._viewMatrix = BABYLON.Matrix.Zero();
  33653. this._projectionMatrix = BABYLON.Matrix.Zero();
  33654. this._transformMatrix = BABYLON.Matrix.Zero();
  33655. this._worldViewProjection = BABYLON.Matrix.Zero();
  33656. this._scene = scene;
  33657. var engine = scene.getEngine();
  33658. // Render target
  33659. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  33660. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33661. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33662. this._depthMap.refreshRate = 1;
  33663. this._depthMap.renderParticles = false;
  33664. this._depthMap.renderList = null;
  33665. // set default depth value to 1.0 (far away)
  33666. this._depthMap.onClear = function (engine) {
  33667. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  33668. };
  33669. // Custom render function
  33670. var renderSubMesh = function (subMesh) {
  33671. var mesh = subMesh.getRenderingMesh();
  33672. var scene = _this._scene;
  33673. var engine = scene.getEngine();
  33674. // Culling
  33675. engine.setState(subMesh.getMaterial().backFaceCulling);
  33676. // Managing instances
  33677. var batch = mesh._getInstancesRenderList(subMesh._id);
  33678. if (batch.mustReturn) {
  33679. return;
  33680. }
  33681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33682. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33683. engine.enableEffect(_this._effect);
  33684. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  33685. var material = subMesh.getMaterial();
  33686. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33687. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  33688. // Alpha test
  33689. if (material && material.needAlphaTesting()) {
  33690. var alphaTexture = material.getAlphaTestTexture();
  33691. _this._effect.setTexture("diffuseSampler", alphaTexture);
  33692. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33693. }
  33694. // Bones
  33695. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33696. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33697. }
  33698. // Draw
  33699. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33700. }
  33701. };
  33702. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  33703. var index;
  33704. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33705. renderSubMesh(opaqueSubMeshes.data[index]);
  33706. }
  33707. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33708. renderSubMesh(alphaTestSubMeshes.data[index]);
  33709. }
  33710. };
  33711. }
  33712. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  33713. var defines = [];
  33714. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33715. var mesh = subMesh.getMesh();
  33716. var scene = mesh.getScene();
  33717. var material = subMesh.getMaterial();
  33718. // Alpha test
  33719. if (material && material.needAlphaTesting()) {
  33720. defines.push("#define ALPHATEST");
  33721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33722. attribs.push(BABYLON.VertexBuffer.UVKind);
  33723. defines.push("#define UV1");
  33724. }
  33725. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33726. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33727. defines.push("#define UV2");
  33728. }
  33729. }
  33730. // Bones
  33731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33734. defines.push("#define BONES");
  33735. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33736. }
  33737. // Instances
  33738. if (useInstances) {
  33739. defines.push("#define INSTANCES");
  33740. attribs.push("world0");
  33741. attribs.push("world1");
  33742. attribs.push("world2");
  33743. attribs.push("world3");
  33744. }
  33745. // Get correct effect
  33746. var join = defines.join("\n");
  33747. if (this._cachedDefines !== join) {
  33748. this._cachedDefines = join;
  33749. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  33750. }
  33751. return this._effect.isReady();
  33752. };
  33753. DepthRenderer.prototype.getDepthMap = function () {
  33754. return this._depthMap;
  33755. };
  33756. // Methods
  33757. DepthRenderer.prototype.dispose = function () {
  33758. this._depthMap.dispose();
  33759. };
  33760. return DepthRenderer;
  33761. })();
  33762. BABYLON.DepthRenderer = DepthRenderer;
  33763. })(BABYLON || (BABYLON = {}));
  33764. var BABYLON;
  33765. (function (BABYLON) {
  33766. var SSAORenderingPipeline = (function (_super) {
  33767. __extends(SSAORenderingPipeline, _super);
  33768. /**
  33769. * @constructor
  33770. * @param {string} name - The rendering pipeline name
  33771. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33772. * @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 }
  33773. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33774. */
  33775. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  33776. var _this = this;
  33777. _super.call(this, scene.getEngine(), name);
  33778. // Members
  33779. /**
  33780. * The PassPostProcess id in the pipeline that contains the original scene color
  33781. * @type {string}
  33782. */
  33783. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  33784. /**
  33785. * The SSAO PostProcess id in the pipeline
  33786. * @type {string}
  33787. */
  33788. this.SSAORenderEffect = "SSAORenderEffect";
  33789. /**
  33790. * The horizontal blur PostProcess id in the pipeline
  33791. * @type {string}
  33792. */
  33793. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  33794. /**
  33795. * The vertical blur PostProcess id in the pipeline
  33796. * @type {string}
  33797. */
  33798. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  33799. /**
  33800. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  33801. * @type {string}
  33802. */
  33803. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  33804. /**
  33805. * The output strength of the SSAO post-process. Default value is 1.0.
  33806. * @type {number}
  33807. */
  33808. this.totalStrength = 1.0;
  33809. /**
  33810. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  33811. * @type {number}
  33812. */
  33813. this.radius = 0.0002;
  33814. /**
  33815. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  33816. * Must not be equal to fallOff and superior to fallOff.
  33817. * Default value is 0.0075
  33818. * @type {number}
  33819. */
  33820. this.area = 0.0075;
  33821. /**
  33822. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  33823. * Must not be equal to area and inferior to area.
  33824. * Default value is 0.0002
  33825. * @type {number}
  33826. */
  33827. this.fallOff = 0.0002;
  33828. this._firstUpdate = true;
  33829. this._scene = scene;
  33830. // Set up assets
  33831. this._createRandomTexture();
  33832. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33833. var ssaoRatio = ratio.ssaoRatio || ratio;
  33834. var combineRatio = ratio.combineRatio || ratio;
  33835. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33836. this._createSSAOPostProcess(ssaoRatio);
  33837. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 4.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33838. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 4.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33839. this._createSSAOCombinePostProcess(combineRatio);
  33840. // Set up pipeline
  33841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  33842. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  33843. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  33844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  33845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  33846. // Finish
  33847. scene.postProcessRenderPipelineManager.addPipeline(this);
  33848. if (cameras)
  33849. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33850. }
  33851. // Public Methods
  33852. /**
  33853. * Returns the horizontal blur PostProcess
  33854. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  33855. */
  33856. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  33857. return this._blurHPostProcess;
  33858. };
  33859. /**
  33860. * Returns the vertical blur PostProcess
  33861. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  33862. */
  33863. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  33864. return this._blurVPostProcess;
  33865. };
  33866. /**
  33867. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  33868. */
  33869. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33870. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33871. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33872. this._originalColorPostProcess = undefined;
  33873. this._ssaoPostProcess = undefined;
  33874. this._blurHPostProcess = undefined;
  33875. this._blurVPostProcess = undefined;
  33876. this._ssaoCombinePostProcess = undefined;
  33877. this._randomTexture.dispose();
  33878. if (disableDepthRender)
  33879. this._scene.disableDepthRenderer();
  33880. };
  33881. // Private Methods
  33882. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  33883. var _this = this;
  33884. var sampleSphere = [
  33885. 0.5381, 0.1856, -0.4319,
  33886. 0.1379, 0.2486, 0.4430,
  33887. 0.3371, 0.5679, -0.0057,
  33888. -0.6999, -0.0451, -0.0019,
  33889. 0.0689, -0.1598, -0.8547,
  33890. 0.0560, 0.0069, -0.1843,
  33891. -0.0146, 0.1402, 0.0762,
  33892. 0.0100, -0.1924, -0.0344,
  33893. -0.3577, -0.5301, -0.4358,
  33894. -0.3169, 0.1063, 0.0158,
  33895. 0.0103, -0.5869, 0.0046,
  33896. -0.0897, -0.4940, 0.3287,
  33897. 0.7119, -0.0154, -0.0918,
  33898. -0.0533, 0.0596, -0.5411,
  33899. 0.0352, -0.0631, 0.5460,
  33900. -0.4776, 0.2847, -0.0271
  33901. ];
  33902. var samplesFactor = 1.0 / 16.0;
  33903. 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);
  33904. this._ssaoPostProcess.onApply = function (effect) {
  33905. if (_this._firstUpdate) {
  33906. effect.setArray3("sampleSphere", sampleSphere);
  33907. effect.setFloat("samplesFactor", samplesFactor);
  33908. effect.setFloat("randTextureTiles", 4.0);
  33909. _this._firstUpdate = false;
  33910. }
  33911. effect.setFloat("totalStrength", _this.totalStrength);
  33912. effect.setFloat("radius", _this.radius);
  33913. effect.setFloat("area", _this.area);
  33914. effect.setFloat("fallOff", _this.fallOff);
  33915. effect.setTexture("textureSampler", _this._depthTexture);
  33916. effect.setTexture("randomSampler", _this._randomTexture);
  33917. };
  33918. };
  33919. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  33920. var _this = this;
  33921. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33922. this._ssaoCombinePostProcess.onApply = function (effect) {
  33923. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  33924. };
  33925. };
  33926. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  33927. var size = 512;
  33928. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33929. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33930. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33931. var context = this._randomTexture.getContext();
  33932. var rand = function (min, max) {
  33933. return Math.random() * (max - min) + min;
  33934. };
  33935. for (var x = 0; x < size; x++) {
  33936. for (var y = 0; y < size; y++) {
  33937. var randVector = BABYLON.Vector3.Zero();
  33938. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33939. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33940. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33941. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33942. context.fillRect(x, y, 1, 1);
  33943. }
  33944. }
  33945. this._randomTexture.update(false);
  33946. };
  33947. return SSAORenderingPipeline;
  33948. })(BABYLON.PostProcessRenderPipeline);
  33949. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33950. })(BABYLON || (BABYLON = {}));
  33951. var BABYLON;
  33952. (function (BABYLON) {
  33953. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33954. var VolumetricLightScatteringPostProcess = (function (_super) {
  33955. __extends(VolumetricLightScatteringPostProcess, _super);
  33956. /**
  33957. * @constructor
  33958. * @param {string} name - The post-process name
  33959. * @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)
  33960. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33961. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33962. * @param {number} samples - The post-process quality, default 100
  33963. * @param {number} samplingMode - The post-process filtering mode
  33964. * @param {BABYLON.Engine} engine - The babylon engine
  33965. * @param {boolean} reusable - If the post-process is reusable
  33966. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33967. */
  33968. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33969. var _this = this;
  33970. if (samples === void 0) { samples = 100; }
  33971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33972. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33973. this._screenCoordinates = BABYLON.Vector2.Zero();
  33974. /**
  33975. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33976. * @type {boolean}
  33977. */
  33978. this.useCustomMeshPosition = false;
  33979. /**
  33980. * If the post-process should inverse the light scattering direction
  33981. * @type {boolean}
  33982. */
  33983. this.invert = true;
  33984. /**
  33985. * Set to true to use the diffuseColor instead of the diffuseTexture
  33986. * @type {boolean}
  33987. */
  33988. this.useDiffuseColor = false;
  33989. /**
  33990. * Array containing the excluded meshes not rendered in the internal pass
  33991. */
  33992. this.excludedMeshes = new Array();
  33993. /**
  33994. * Controls the overall intensity of the post-process
  33995. * @type {number}
  33996. */
  33997. this.exposure = 0.3;
  33998. /**
  33999. * Dissipates each sample's contribution in range [0, 1]
  34000. * @type {number}
  34001. */
  34002. this.decay = 0.96815;
  34003. /**
  34004. * Controls the overall intensity of each sample
  34005. * @type {number}
  34006. */
  34007. this.weight = 0.58767;
  34008. /**
  34009. * Controls the density of each sample
  34010. * @type {number}
  34011. */
  34012. this.density = 0.926;
  34013. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34014. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34015. // Configure mesh
  34016. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34017. // Configure
  34018. this._createPass(scene, ratio.passRatio || ratio);
  34019. this.onApply = function (effect) {
  34020. _this._updateMeshScreenCoordinates(scene);
  34021. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34022. effect.setFloat("exposure", _this.exposure);
  34023. effect.setFloat("decay", _this.decay);
  34024. effect.setFloat("weight", _this.weight);
  34025. effect.setFloat("density", _this.density);
  34026. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34027. };
  34028. }
  34029. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34030. var mesh = subMesh.getMesh();
  34031. var defines = [];
  34032. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34033. var material = subMesh.getMaterial();
  34034. var needUV = false;
  34035. // Render this.mesh as default
  34036. if (mesh === this.mesh) {
  34037. if (this.useDiffuseColor) {
  34038. defines.push("#define DIFFUSE_COLOR_RENDER");
  34039. }
  34040. else if (material) {
  34041. if (material.diffuseTexture !== undefined) {
  34042. defines.push("#define BASIC_RENDER");
  34043. }
  34044. else {
  34045. defines.push("#define DIFFUSE_COLOR_RENDER");
  34046. }
  34047. }
  34048. defines.push("#define NEED_UV");
  34049. needUV = true;
  34050. }
  34051. // Alpha test
  34052. if (material) {
  34053. if (material.needAlphaTesting()) {
  34054. defines.push("#define ALPHATEST");
  34055. }
  34056. if (material.opacityTexture !== undefined) {
  34057. defines.push("#define OPACITY");
  34058. if (material.opacityTexture.getAlphaFromRGB) {
  34059. defines.push("#define OPACITYRGB");
  34060. }
  34061. if (!needUV) {
  34062. defines.push("#define NEED_UV");
  34063. }
  34064. }
  34065. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34066. attribs.push(BABYLON.VertexBuffer.UVKind);
  34067. defines.push("#define UV1");
  34068. }
  34069. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34070. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34071. defines.push("#define UV2");
  34072. }
  34073. }
  34074. // Bones
  34075. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34078. defines.push("#define BONES");
  34079. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34080. }
  34081. // Instances
  34082. if (useInstances) {
  34083. defines.push("#define INSTANCES");
  34084. attribs.push("world0");
  34085. attribs.push("world1");
  34086. attribs.push("world2");
  34087. attribs.push("world3");
  34088. }
  34089. // Get correct effect
  34090. var join = defines.join("\n");
  34091. if (this._cachedDefines !== join) {
  34092. this._cachedDefines = join;
  34093. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34094. }
  34095. return this._volumetricLightScatteringPass.isReady();
  34096. };
  34097. /**
  34098. * Sets the new light position for light scattering effect
  34099. * @param {BABYLON.Vector3} The new custom light position
  34100. */
  34101. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34102. this._customMeshPosition = position;
  34103. };
  34104. /**
  34105. * Returns the light position for light scattering effect
  34106. * @return {BABYLON.Vector3} The custom light position
  34107. */
  34108. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34109. return this._customMeshPosition;
  34110. };
  34111. /**
  34112. * Disposes the internal assets and detaches the post-process from the camera
  34113. */
  34114. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34115. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34116. if (rttIndex !== -1) {
  34117. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34118. }
  34119. this._volumetricLightScatteringRTT.dispose();
  34120. _super.prototype.dispose.call(this, camera);
  34121. };
  34122. /**
  34123. * Returns the render target texture used by the post-process
  34124. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34125. */
  34126. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34127. return this._volumetricLightScatteringRTT;
  34128. };
  34129. // Private methods
  34130. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34131. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34132. return true;
  34133. }
  34134. return false;
  34135. };
  34136. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34137. var _this = this;
  34138. var engine = scene.getEngine();
  34139. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34140. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34141. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34142. this._volumetricLightScatteringRTT.renderList = null;
  34143. this._volumetricLightScatteringRTT.renderParticles = false;
  34144. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34145. // Custom render function for submeshes
  34146. var renderSubMesh = function (subMesh) {
  34147. var mesh = subMesh.getRenderingMesh();
  34148. if (_this._meshExcluded(mesh)) {
  34149. return;
  34150. }
  34151. var scene = mesh.getScene();
  34152. var engine = scene.getEngine();
  34153. // Culling
  34154. engine.setState(subMesh.getMaterial().backFaceCulling);
  34155. // Managing instances
  34156. var batch = mesh._getInstancesRenderList(subMesh._id);
  34157. if (batch.mustReturn) {
  34158. return;
  34159. }
  34160. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34161. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34162. engine.enableEffect(_this._volumetricLightScatteringPass);
  34163. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34164. var material = subMesh.getMaterial();
  34165. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34166. // Alpha test
  34167. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34168. var alphaTexture = material.getAlphaTestTexture();
  34169. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34170. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34171. }
  34172. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34173. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34174. if (alphaTexture) {
  34175. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34176. }
  34177. }
  34178. if (material.opacityTexture !== undefined) {
  34179. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34180. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34181. }
  34182. }
  34183. // Bones
  34184. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34185. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34186. }
  34187. // Draw
  34188. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34189. }
  34190. };
  34191. // Render target texture callbacks
  34192. var savedSceneClearColor;
  34193. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34194. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34195. savedSceneClearColor = scene.clearColor;
  34196. scene.clearColor = sceneClearColor;
  34197. };
  34198. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34199. scene.clearColor = savedSceneClearColor;
  34200. };
  34201. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34202. var engine = scene.getEngine();
  34203. var index;
  34204. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34205. renderSubMesh(opaqueSubMeshes.data[index]);
  34206. }
  34207. engine.setAlphaTesting(true);
  34208. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34209. renderSubMesh(alphaTestSubMeshes.data[index]);
  34210. }
  34211. engine.setAlphaTesting(false);
  34212. if (transparentSubMeshes.length) {
  34213. // Sort sub meshes
  34214. for (index = 0; index < transparentSubMeshes.length; index++) {
  34215. var submesh = transparentSubMeshes.data[index];
  34216. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34217. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34218. }
  34219. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34220. sortedArray.sort(function (a, b) {
  34221. // Alpha index first
  34222. if (a._alphaIndex > b._alphaIndex) {
  34223. return 1;
  34224. }
  34225. if (a._alphaIndex < b._alphaIndex) {
  34226. return -1;
  34227. }
  34228. // Then distance to camera
  34229. if (a._distanceToCamera < b._distanceToCamera) {
  34230. return 1;
  34231. }
  34232. if (a._distanceToCamera > b._distanceToCamera) {
  34233. return -1;
  34234. }
  34235. return 0;
  34236. });
  34237. // Render sub meshes
  34238. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34239. for (index = 0; index < sortedArray.length; index++) {
  34240. renderSubMesh(sortedArray[index]);
  34241. }
  34242. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34243. }
  34244. };
  34245. };
  34246. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34247. var transform = scene.getTransformMatrix();
  34248. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34249. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34250. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34251. if (this.invert)
  34252. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34253. };
  34254. // Static methods
  34255. /**
  34256. * Creates a default mesh for the Volumeric Light Scattering post-process
  34257. * @param {string} The mesh name
  34258. * @param {BABYLON.Scene} The scene where to create the mesh
  34259. * @return {BABYLON.Mesh} the default mesh
  34260. */
  34261. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34262. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34263. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34264. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34265. return mesh;
  34266. };
  34267. return VolumetricLightScatteringPostProcess;
  34268. })(BABYLON.PostProcess);
  34269. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34270. })(BABYLON || (BABYLON = {}));
  34271. var BABYLON;
  34272. (function (BABYLON) {
  34273. var LensRenderingPipeline = (function (_super) {
  34274. __extends(LensRenderingPipeline, _super);
  34275. /**
  34276. * @constructor
  34277. *
  34278. * Effect parameters are as follow:
  34279. * {
  34280. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34281. * edge_blur: number; // from 0 to x (1 for realism)
  34282. * distortion: number; // from 0 to x (1 for realism)
  34283. * grain_amount: number; // from 0 to 1
  34284. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34285. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34286. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34287. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34288. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34289. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34290. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34291. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34292. * }
  34293. * Note: if an effect parameter is unset, effect is disabled
  34294. *
  34295. * @param {string} name - The rendering pipeline name
  34296. * @param {object} parameters - An object containing all parameters (see above)
  34297. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34298. * @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)
  34299. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34300. */
  34301. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34302. var _this = this;
  34303. if (ratio === void 0) { ratio = 1.0; }
  34304. _super.call(this, scene.getEngine(), name);
  34305. // Lens effects can be of the following:
  34306. // - chromatic aberration (slight shift of RGB colors)
  34307. // - blur on the edge of the lens
  34308. // - lens distortion
  34309. // - depth-of-field blur & highlights enhancing
  34310. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34311. // - grain effect (noise or custom texture)
  34312. // Two additional texture samplers are needed:
  34313. // - depth map (for depth-of-field)
  34314. // - grain texture
  34315. /**
  34316. * The chromatic aberration PostProcess id in the pipeline
  34317. * @type {string}
  34318. */
  34319. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34320. /**
  34321. * The highlights enhancing PostProcess id in the pipeline
  34322. * @type {string}
  34323. */
  34324. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34325. /**
  34326. * The depth-of-field PostProcess id in the pipeline
  34327. * @type {string}
  34328. */
  34329. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34330. this._scene = scene;
  34331. // Fetch texture samplers
  34332. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34333. if (parameters.grain_texture) {
  34334. this._grainTexture = parameters.grain_texture;
  34335. }
  34336. else {
  34337. this._createGrainTexture();
  34338. }
  34339. // save parameters
  34340. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34341. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34342. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34343. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34344. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34345. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34346. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34347. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34348. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34349. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34350. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34351. // Create effects
  34352. this._createChromaticAberrationPostProcess(ratio);
  34353. this._createHighlightsPostProcess(ratio);
  34354. this._createDepthOfFieldPostProcess(ratio / 4);
  34355. // Set up pipeline
  34356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34359. if (this._highlightsGain === -1) {
  34360. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34361. }
  34362. // Finish
  34363. scene.postProcessRenderPipelineManager.addPipeline(this);
  34364. if (cameras) {
  34365. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34366. }
  34367. }
  34368. // public methods (self explanatory)
  34369. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34370. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34371. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34372. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34373. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34374. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34375. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34376. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34377. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34378. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34379. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34380. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34381. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  34382. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  34383. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34384. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34385. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34386. this._highlightsGain = amount;
  34387. };
  34388. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34389. if (this._highlightsGain === -1) {
  34390. this._highlightsGain = 1.0;
  34391. }
  34392. this._highlightsThreshold = amount;
  34393. };
  34394. LensRenderingPipeline.prototype.disableHighlights = function () {
  34395. this._highlightsGain = -1;
  34396. };
  34397. /**
  34398. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34399. */
  34400. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34401. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34402. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34403. this._chromaticAberrationPostProcess = undefined;
  34404. this._highlightsPostProcess = undefined;
  34405. this._depthOfFieldPostProcess = undefined;
  34406. this._grainTexture.dispose();
  34407. if (disableDepthRender)
  34408. this._scene.disableDepthRenderer();
  34409. };
  34410. // colors shifting and distortion
  34411. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34412. var _this = this;
  34413. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34414. [], // samplers
  34415. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34416. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34417. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34418. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34419. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34420. };
  34421. };
  34422. // highlights enhancing
  34423. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34424. var _this = this;
  34425. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  34426. [], // samplers
  34427. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34428. this._highlightsPostProcess.onApply = function (effect) {
  34429. effect.setFloat('gain', _this._highlightsGain);
  34430. effect.setFloat('threshold', _this._highlightsThreshold);
  34431. effect.setBool('pentagon', _this._dofPentagon);
  34432. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34433. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34434. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34435. };
  34436. };
  34437. // colors shifting and distortion
  34438. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34439. var _this = this;
  34440. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34441. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34442. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34443. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34444. this._depthOfFieldPostProcess.onApply = function (effect) {
  34445. effect.setTexture("depthSampler", _this._depthTexture);
  34446. effect.setTexture("grainSampler", _this._grainTexture);
  34447. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34448. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34449. effect.setFloat('grain_amount', _this._grainAmount);
  34450. effect.setBool('blur_noise', _this._blurNoise);
  34451. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34452. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34453. effect.setFloat('distortion', _this._distortion);
  34454. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34455. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34456. effect.setFloat('aperture', _this._dofAperture);
  34457. effect.setFloat('darken', _this._dofDarken);
  34458. effect.setFloat('edge_blur', _this._edgeBlur);
  34459. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34460. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34461. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34462. };
  34463. };
  34464. // creates a black and white random noise texture, 512x512
  34465. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34466. var size = 512;
  34467. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34468. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34469. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34470. var context = this._grainTexture.getContext();
  34471. var rand = function (min, max) {
  34472. return Math.random() * (max - min) + min;
  34473. };
  34474. var value;
  34475. for (var x = 0; x < size; x++) {
  34476. for (var y = 0; y < size; y++) {
  34477. value = Math.floor(rand(0.42, 0.58) * 255);
  34478. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34479. context.fillRect(x, y, 1, 1);
  34480. }
  34481. }
  34482. this._grainTexture.update(false);
  34483. };
  34484. return LensRenderingPipeline;
  34485. })(BABYLON.PostProcessRenderPipeline);
  34486. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34487. })(BABYLON || (BABYLON = {}));
  34488. //
  34489. // This post-process allows the modification of rendered colors by using
  34490. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34491. //
  34492. // The object needs to be provided an url to a texture containing the color
  34493. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34494. // Use an image editing software to tweak the LUT to match your needs.
  34495. //
  34496. // For an example of a color LUT, see here:
  34497. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34498. // For explanations on color grading, see here:
  34499. // http://udn.epicgames.com/Three/ColorGrading.html
  34500. //
  34501. var BABYLON;
  34502. (function (BABYLON) {
  34503. var ColorCorrectionPostProcess = (function (_super) {
  34504. __extends(ColorCorrectionPostProcess, _super);
  34505. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34506. var _this = this;
  34507. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34508. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34509. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34510. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34511. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34512. this.onApply = function (effect) {
  34513. effect.setTexture("colorTable", _this._colorTableTexture);
  34514. };
  34515. }
  34516. return ColorCorrectionPostProcess;
  34517. })(BABYLON.PostProcess);
  34518. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34519. })(BABYLON || (BABYLON = {}));
  34520. var BABYLON;
  34521. (function (BABYLON) {
  34522. var AnaglyphFreeCamera = (function (_super) {
  34523. __extends(AnaglyphFreeCamera, _super);
  34524. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34525. _super.call(this, name, position, scene);
  34526. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34527. }
  34528. return AnaglyphFreeCamera;
  34529. })(BABYLON.FreeCamera);
  34530. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  34531. var AnaglyphArcRotateCamera = (function (_super) {
  34532. __extends(AnaglyphArcRotateCamera, _super);
  34533. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  34534. _super.call(this, name, alpha, beta, radius, target, scene);
  34535. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34536. }
  34537. return AnaglyphArcRotateCamera;
  34538. })(BABYLON.ArcRotateCamera);
  34539. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  34540. var AnaglyphGamepadCamera = (function (_super) {
  34541. __extends(AnaglyphGamepadCamera, _super);
  34542. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  34543. _super.call(this, name, position, scene);
  34544. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34545. }
  34546. return AnaglyphGamepadCamera;
  34547. })(BABYLON.GamepadCamera);
  34548. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  34549. var StereoscopicFreeCamera = (function (_super) {
  34550. __extends(StereoscopicFreeCamera, _super);
  34551. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34552. _super.call(this, name, position, scene);
  34553. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34554. }
  34555. return StereoscopicFreeCamera;
  34556. })(BABYLON.FreeCamera);
  34557. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  34558. var StereoscopicArcRotateCamera = (function (_super) {
  34559. __extends(StereoscopicArcRotateCamera, _super);
  34560. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  34561. _super.call(this, name, alpha, beta, radius, target, scene);
  34562. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34563. }
  34564. return StereoscopicArcRotateCamera;
  34565. })(BABYLON.ArcRotateCamera);
  34566. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  34567. var StereoscopicGamepadCamera = (function (_super) {
  34568. __extends(StereoscopicGamepadCamera, _super);
  34569. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34570. _super.call(this, name, position, scene);
  34571. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34572. }
  34573. return StereoscopicGamepadCamera;
  34574. })(BABYLON.GamepadCamera);
  34575. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  34576. })(BABYLON || (BABYLON = {}));
  34577. var BABYLON;
  34578. (function (BABYLON) {
  34579. var HDRRenderingPipeline = (function (_super) {
  34580. __extends(HDRRenderingPipeline, _super);
  34581. /**
  34582. * @constructor
  34583. * @param {string} name - The rendering pipeline name
  34584. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34585. * @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)
  34586. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  34587. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34588. */
  34589. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  34590. var _this = this;
  34591. if (originalPostProcess === void 0) { originalPostProcess = null; }
  34592. _super.call(this, scene.getEngine(), name);
  34593. /**
  34594. * Public members
  34595. */
  34596. // Gaussian Blur
  34597. /**
  34598. * Gaussian blur coefficient
  34599. * @type {number}
  34600. */
  34601. this.gaussCoeff = 0.3;
  34602. /**
  34603. * Gaussian blur mean
  34604. * @type {number}
  34605. */
  34606. this.gaussMean = 1.0;
  34607. /**
  34608. * Gaussian blur standard deviation
  34609. * @type {number}
  34610. */
  34611. this.gaussStandDev = 0.8;
  34612. // HDR
  34613. /**
  34614. * Exposure, controls the overall intensity of the pipeline
  34615. * @type {number}
  34616. */
  34617. this.exposure = 1.0;
  34618. /**
  34619. * Minimum luminance that the post-process can output. Luminance is >= 0
  34620. * @type {number}
  34621. */
  34622. this.minimumLuminance = 1.0;
  34623. /**
  34624. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  34625. * @type {number}
  34626. */
  34627. this.maximumLuminance = 1e20;
  34628. /**
  34629. * Increase rate for luminance: eye adaptation speed to dark
  34630. * @type {number}
  34631. */
  34632. this.luminanceIncreaserate = 0.5;
  34633. /**
  34634. * Decrease rate for luminance: eye adaptation speed to bright
  34635. * @type {number}
  34636. */
  34637. this.luminanceDecreaseRate = 0.5;
  34638. // Bright pass
  34639. /**
  34640. * Minimum luminance needed to compute HDR
  34641. * @type {number}
  34642. */
  34643. this.brightThreshold = 0.8;
  34644. this._needUpdate = true;
  34645. this._scene = scene;
  34646. // Bright pass
  34647. this._createBrightPassPostProcess(scene, ratio);
  34648. // Down sample X4
  34649. this._createDownSampleX4PostProcess(scene, ratio);
  34650. // Create gaussian blur post-processes
  34651. this._createGaussianBlurPostProcess(scene, ratio);
  34652. // Texture adder
  34653. this._createTextureAdderPostProcess(scene, ratio);
  34654. // Luminance generator
  34655. this._createLuminanceGeneratorPostProcess(scene);
  34656. // HDR
  34657. this._createHDRPostProcess(scene, ratio);
  34658. // Pass postprocess
  34659. if (originalPostProcess === null) {
  34660. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34661. }
  34662. else {
  34663. this._originalPostProcess = originalPostProcess;
  34664. }
  34665. // Configure pipeline
  34666. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  34667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  34668. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  34669. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  34670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  34671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  34672. var addDownSamplerPostProcess = function (id) {
  34673. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  34674. };
  34675. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34676. addDownSamplerPostProcess(i);
  34677. }
  34678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  34679. // Finish
  34680. scene.postProcessRenderPipelineManager.addPipeline(this);
  34681. if (cameras !== null) {
  34682. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34683. }
  34684. this.update();
  34685. }
  34686. /**
  34687. * Tells the pipeline to update its post-processes
  34688. */
  34689. HDRRenderingPipeline.prototype.update = function () {
  34690. this._needUpdate = true;
  34691. };
  34692. /**
  34693. * Returns the current calculated luminance
  34694. */
  34695. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  34696. return this._hdrCurrentLuminance;
  34697. };
  34698. /**
  34699. * Returns the currently drawn luminance
  34700. */
  34701. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  34702. return this._hdrOutputLuminance;
  34703. };
  34704. /**
  34705. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  34706. */
  34707. HDRRenderingPipeline.prototype.dispose = function () {
  34708. this._originalPostProcess = undefined;
  34709. this._brightPassPostProcess = undefined;
  34710. this._downSampleX4PostProcess = undefined;
  34711. this._guassianBlurHPostProcess = undefined;
  34712. this._guassianBlurVPostProcess = undefined;
  34713. this._textureAdderPostProcess = undefined;
  34714. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34715. this._downSamplePostProcesses[i] = undefined;
  34716. }
  34717. this._hdrPostProcess = undefined;
  34718. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34719. };
  34720. /**
  34721. * Creates the HDR post-process and computes the luminance adaptation
  34722. */
  34723. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  34724. var _this = this;
  34725. var hdrLastLuminance = 0.0;
  34726. this._hdrOutputLuminance = -1.0;
  34727. this._hdrCurrentLuminance = 1.0;
  34728. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  34729. this._hdrPostProcess.onApply = function (effect) {
  34730. if (_this._hdrOutputLuminance < 0.0) {
  34731. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34732. }
  34733. else {
  34734. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  34735. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  34736. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  34737. }
  34738. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  34739. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  34740. }
  34741. else {
  34742. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34743. }
  34744. }
  34745. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  34746. hdrLastLuminance += scene.getEngine().getDeltaTime();
  34747. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34748. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34749. effect.setFloat("exposure", _this.exposure);
  34750. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  34751. _this._needUpdate = false;
  34752. };
  34753. };
  34754. /**
  34755. * Texture Adder post-process
  34756. */
  34757. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  34758. var _this = this;
  34759. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  34760. this._textureAdderPostProcess.onApply = function (effect) {
  34761. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34762. };
  34763. };
  34764. /**
  34765. * Down sample X4 post-process
  34766. */
  34767. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  34768. var _this = this;
  34769. var downSampleX4Offsets = new Array(32);
  34770. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  34771. this._downSampleX4PostProcess.onApply = function (effect) {
  34772. if (_this._needUpdate) {
  34773. var id = 0;
  34774. for (var i = -2; i < 2; i++) {
  34775. for (var j = -2; j < 2; j++) {
  34776. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  34777. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  34778. id += 2;
  34779. }
  34780. }
  34781. }
  34782. effect.setArray2("dsOffsets", downSampleX4Offsets);
  34783. };
  34784. };
  34785. /**
  34786. * Bright pass post-process
  34787. */
  34788. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  34789. var _this = this;
  34790. var brightOffsets = new Array(8);
  34791. var brightPassCallback = function (effect) {
  34792. if (_this._needUpdate) {
  34793. var sU = (1.0 / _this._brightPassPostProcess.width);
  34794. var sV = (1.0 / _this._brightPassPostProcess.height);
  34795. brightOffsets[0] = -0.5 * sU;
  34796. brightOffsets[1] = 0.5 * sV;
  34797. brightOffsets[2] = 0.5 * sU;
  34798. brightOffsets[3] = 0.5 * sV;
  34799. brightOffsets[4] = -0.5 * sU;
  34800. brightOffsets[5] = -0.5 * sV;
  34801. brightOffsets[6] = 0.5 * sU;
  34802. brightOffsets[7] = -0.5 * sV;
  34803. }
  34804. effect.setArray2("dsOffsets", brightOffsets);
  34805. effect.setFloat("brightThreshold", _this.brightThreshold);
  34806. };
  34807. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  34808. this._brightPassPostProcess.onApply = brightPassCallback;
  34809. };
  34810. /**
  34811. * Luminance generator. Creates the luminance post-process and down sample post-processes
  34812. */
  34813. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  34814. var _this = this;
  34815. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  34816. var luminanceOffsets = new Array(8);
  34817. var downSampleOffsets = new Array(18);
  34818. var halfDestPixelSize;
  34819. this._downSamplePostProcesses = new Array(lumSteps);
  34820. // Utils for luminance
  34821. var luminanceUpdateSourceOffsets = function (width, height) {
  34822. var sU = (1.0 / width);
  34823. var sV = (1.0 / height);
  34824. luminanceOffsets[0] = -0.5 * sU;
  34825. luminanceOffsets[1] = 0.5 * sV;
  34826. luminanceOffsets[2] = 0.5 * sU;
  34827. luminanceOffsets[3] = 0.5 * sV;
  34828. luminanceOffsets[4] = -0.5 * sU;
  34829. luminanceOffsets[5] = -0.5 * sV;
  34830. luminanceOffsets[6] = 0.5 * sU;
  34831. luminanceOffsets[7] = -0.5 * sV;
  34832. };
  34833. var luminanceUpdateDestOffsets = function (width, height) {
  34834. var id = 0;
  34835. for (var x = -1; x < 2; x++) {
  34836. for (var y = -1; y < 2; y++) {
  34837. downSampleOffsets[id] = (x) / width;
  34838. downSampleOffsets[id + 1] = (y) / height;
  34839. id += 2;
  34840. }
  34841. }
  34842. };
  34843. // Luminance callback
  34844. var luminanceCallback = function (effect) {
  34845. if (_this._needUpdate) {
  34846. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  34847. }
  34848. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34849. effect.setArray2("lumOffsets", luminanceOffsets);
  34850. };
  34851. // Down sample callbacks
  34852. var downSampleCallback = function (indice) {
  34853. var i = indice;
  34854. return function (effect) {
  34855. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34856. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34857. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  34858. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  34859. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  34860. effect.setArray2("dsOffsets", downSampleOffsets);
  34861. };
  34862. };
  34863. var downSampleAfterRenderCallback = function (effect) {
  34864. // Unpack result
  34865. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  34866. 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);
  34867. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  34868. };
  34869. // Create luminance post-process
  34870. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  34871. 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);
  34872. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  34873. // Create down sample post-processes
  34874. for (var i = lumSteps - 2; i >= 0; i--) {
  34875. var length = Math.pow(3, i);
  34876. ratio = { width: length, height: length };
  34877. var defines = "#define DOWN_SAMPLE\n";
  34878. if (i === 0) {
  34879. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  34880. }
  34881. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  34882. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  34883. if (i === 0) {
  34884. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  34885. }
  34886. }
  34887. };
  34888. /**
  34889. * Gaussian blur post-processes. Horizontal and Vertical
  34890. */
  34891. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  34892. var _this = this;
  34893. var blurOffsetsW = new Array(9);
  34894. var blurOffsetsH = new Array(9);
  34895. var blurWeights = new Array(9);
  34896. var uniforms = ["blurOffsets", "blurWeights"];
  34897. // Utils for gaussian blur
  34898. var calculateBlurOffsets = function (height) {
  34899. var lastOutputDimensions = {
  34900. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  34901. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  34902. };
  34903. for (var i = 0; i < 9; i++) {
  34904. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  34905. if (height) {
  34906. blurOffsetsH[i] = value;
  34907. }
  34908. else {
  34909. blurOffsetsW[i] = value;
  34910. }
  34911. }
  34912. };
  34913. var calculateWeights = function () {
  34914. var x = 0.0;
  34915. for (var i = 0; i < 9; i++) {
  34916. x = (i - 4.0) / 4.0;
  34917. 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));
  34918. }
  34919. };
  34920. // Callback
  34921. var gaussianBlurCallback = function (height) {
  34922. return function (effect) {
  34923. if (_this._needUpdate) {
  34924. calculateWeights();
  34925. calculateBlurOffsets(height);
  34926. }
  34927. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  34928. effect.setArray("blurWeights", blurWeights);
  34929. };
  34930. };
  34931. // Create horizontal gaussian blur post-processes
  34932. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  34933. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34934. // Create vertical gaussian blur post-process
  34935. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34936. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34937. };
  34938. // Luminance generator
  34939. HDRRenderingPipeline.LUM_STEPS = 6;
  34940. return HDRRenderingPipeline;
  34941. })(BABYLON.PostProcessRenderPipeline);
  34942. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34943. })(BABYLON || (BABYLON = {}));
  34944. var BABYLON;
  34945. (function (BABYLON) {
  34946. var FaceAdjacencies = (function () {
  34947. function FaceAdjacencies() {
  34948. this.edges = new Array();
  34949. this.edgesConnectedCount = 0;
  34950. }
  34951. return FaceAdjacencies;
  34952. })();
  34953. var EdgesRenderer = (function () {
  34954. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34955. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34956. if (epsilon === void 0) { epsilon = 0.95; }
  34957. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34958. this._linesPositions = new Array();
  34959. this._linesNormals = new Array();
  34960. this._linesIndices = new Array();
  34961. this._buffers = new Array();
  34962. this._checkVerticesInsteadOfIndices = false;
  34963. this._source = source;
  34964. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34965. this._epsilon = epsilon;
  34966. this._prepareRessources();
  34967. this._generateEdgesLines();
  34968. }
  34969. EdgesRenderer.prototype._prepareRessources = function () {
  34970. if (this._lineShader) {
  34971. return;
  34972. }
  34973. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34974. attributes: ["position", "normal"],
  34975. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34976. });
  34977. this._lineShader.disableDepthWrite = true;
  34978. this._lineShader.backFaceCulling = false;
  34979. };
  34980. EdgesRenderer.prototype.dispose = function () {
  34981. this._vb0.dispose();
  34982. this._vb1.dispose();
  34983. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34984. this._lineShader.dispose();
  34985. };
  34986. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34987. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34988. return 0;
  34989. }
  34990. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34991. return 1;
  34992. }
  34993. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34994. return 2;
  34995. }
  34996. return -1;
  34997. };
  34998. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34999. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35000. return 0;
  35001. }
  35002. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35003. return 1;
  35004. }
  35005. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35006. return 2;
  35007. }
  35008. return -1;
  35009. };
  35010. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35011. var needToCreateLine;
  35012. if (edge === undefined) {
  35013. needToCreateLine = true;
  35014. }
  35015. else {
  35016. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35017. needToCreateLine = dotProduct < this._epsilon;
  35018. }
  35019. if (needToCreateLine) {
  35020. var offset = this._linesPositions.length / 3;
  35021. var normal = p0.subtract(p1);
  35022. normal.normalize();
  35023. // Positions
  35024. this._linesPositions.push(p0.x);
  35025. this._linesPositions.push(p0.y);
  35026. this._linesPositions.push(p0.z);
  35027. this._linesPositions.push(p0.x);
  35028. this._linesPositions.push(p0.y);
  35029. this._linesPositions.push(p0.z);
  35030. this._linesPositions.push(p1.x);
  35031. this._linesPositions.push(p1.y);
  35032. this._linesPositions.push(p1.z);
  35033. this._linesPositions.push(p1.x);
  35034. this._linesPositions.push(p1.y);
  35035. this._linesPositions.push(p1.z);
  35036. // Normals
  35037. this._linesNormals.push(p1.x);
  35038. this._linesNormals.push(p1.y);
  35039. this._linesNormals.push(p1.z);
  35040. this._linesNormals.push(-1);
  35041. this._linesNormals.push(p1.x);
  35042. this._linesNormals.push(p1.y);
  35043. this._linesNormals.push(p1.z);
  35044. this._linesNormals.push(1);
  35045. this._linesNormals.push(p0.x);
  35046. this._linesNormals.push(p0.y);
  35047. this._linesNormals.push(p0.z);
  35048. this._linesNormals.push(-1);
  35049. this._linesNormals.push(p0.x);
  35050. this._linesNormals.push(p0.y);
  35051. this._linesNormals.push(p0.z);
  35052. this._linesNormals.push(1);
  35053. // Indices
  35054. this._linesIndices.push(offset);
  35055. this._linesIndices.push(offset + 1);
  35056. this._linesIndices.push(offset + 2);
  35057. this._linesIndices.push(offset);
  35058. this._linesIndices.push(offset + 2);
  35059. this._linesIndices.push(offset + 3);
  35060. }
  35061. };
  35062. EdgesRenderer.prototype._generateEdgesLines = function () {
  35063. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35064. var indices = this._source.getIndices();
  35065. // First let's find adjacencies
  35066. var adjacencies = new Array();
  35067. var faceNormals = new Array();
  35068. var index;
  35069. var faceAdjacencies;
  35070. // Prepare faces
  35071. for (index = 0; index < indices.length; index += 3) {
  35072. faceAdjacencies = new FaceAdjacencies();
  35073. var p0Index = indices[index];
  35074. var p1Index = indices[index + 1];
  35075. var p2Index = indices[index + 2];
  35076. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35077. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35078. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35079. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35080. faceNormal.normalize();
  35081. faceNormals.push(faceNormal);
  35082. adjacencies.push(faceAdjacencies);
  35083. }
  35084. // Scan
  35085. for (index = 0; index < adjacencies.length; index++) {
  35086. faceAdjacencies = adjacencies[index];
  35087. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35088. var otherFaceAdjacencies = adjacencies[otherIndex];
  35089. if (faceAdjacencies.edgesConnectedCount === 3) {
  35090. break;
  35091. }
  35092. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35093. continue;
  35094. }
  35095. var otherP0 = indices[otherIndex * 3];
  35096. var otherP1 = indices[otherIndex * 3 + 1];
  35097. var otherP2 = indices[otherIndex * 3 + 2];
  35098. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35099. var otherEdgeIndex;
  35100. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35101. continue;
  35102. }
  35103. switch (edgeIndex) {
  35104. case 0:
  35105. if (this._checkVerticesInsteadOfIndices) {
  35106. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35107. }
  35108. else {
  35109. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35110. }
  35111. break;
  35112. case 1:
  35113. if (this._checkVerticesInsteadOfIndices) {
  35114. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35115. }
  35116. else {
  35117. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35118. }
  35119. break;
  35120. case 2:
  35121. if (this._checkVerticesInsteadOfIndices) {
  35122. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35123. }
  35124. else {
  35125. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35126. }
  35127. break;
  35128. }
  35129. if (otherEdgeIndex === -1) {
  35130. continue;
  35131. }
  35132. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35133. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35134. faceAdjacencies.edgesConnectedCount++;
  35135. otherFaceAdjacencies.edgesConnectedCount++;
  35136. if (faceAdjacencies.edgesConnectedCount === 3) {
  35137. break;
  35138. }
  35139. }
  35140. }
  35141. }
  35142. // Create lines
  35143. for (index = 0; index < adjacencies.length; index++) {
  35144. // 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
  35145. var current = adjacencies[index];
  35146. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35147. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35148. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35149. }
  35150. // Merge into a single mesh
  35151. var engine = this._source.getScene().getEngine();
  35152. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35153. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35154. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35155. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35156. this._ib = engine.createIndexBuffer(this._linesIndices);
  35157. this._indicesCount = this._linesIndices.length;
  35158. };
  35159. EdgesRenderer.prototype.render = function () {
  35160. if (!this._lineShader.isReady()) {
  35161. return;
  35162. }
  35163. var scene = this._source.getScene();
  35164. var engine = scene.getEngine();
  35165. this._lineShader._preBind();
  35166. // VBOs
  35167. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35168. scene.resetCachedMaterial();
  35169. this._lineShader.setColor4("color", this._source.edgesColor);
  35170. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35171. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35172. this._lineShader.bind(this._source.getWorldMatrix());
  35173. // Draw order
  35174. engine.draw(true, 0, this._indicesCount);
  35175. this._lineShader.unbind();
  35176. engine.setDepthWrite(true);
  35177. };
  35178. return EdgesRenderer;
  35179. })();
  35180. BABYLON.EdgesRenderer = EdgesRenderer;
  35181. })(BABYLON || (BABYLON = {}));
  35182. var BABYLON;
  35183. (function (BABYLON) {
  35184. (function (TonemappingOperator) {
  35185. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35186. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35187. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35188. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35189. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35190. var TonemappingOperator = BABYLON.TonemappingOperator;
  35191. ;
  35192. var TonemapPostProcess = (function (_super) {
  35193. __extends(TonemapPostProcess, _super);
  35194. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35195. var _this = this;
  35196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35197. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35198. this._operator = operator;
  35199. this._exposureAdjustment = exposureAdjustment;
  35200. var params = ["_ExposureAdjustment"];
  35201. var defines = "#define ";
  35202. if (operator === TonemappingOperator.Hable)
  35203. defines += "HABLE_TONEMAPPING";
  35204. else if (operator === TonemappingOperator.Reinhard)
  35205. defines += "REINHARD_TONEMAPPING";
  35206. else if (operator === TonemappingOperator.HejiDawson)
  35207. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35208. else if (operator === TonemappingOperator.Photographic)
  35209. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35210. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35211. this.onApply = function (effect) {
  35212. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35213. };
  35214. }
  35215. return TonemapPostProcess;
  35216. })(BABYLON.PostProcess);
  35217. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35218. })(BABYLON || (BABYLON = {}));
  35219. var BABYLON;
  35220. (function (BABYLON) {
  35221. var maxSimultaneousLights = 4;
  35222. var PBRMaterialDefines = (function (_super) {
  35223. __extends(PBRMaterialDefines, _super);
  35224. function PBRMaterialDefines() {
  35225. _super.call(this);
  35226. this.ALBEDO = false;
  35227. this.CLIPPLANE = false;
  35228. this.ALPHATEST = false;
  35229. this.FOG = false;
  35230. this.NORMAL = false;
  35231. this.UV1 = false;
  35232. this.UV2 = false;
  35233. this.VERTEXCOLOR = false;
  35234. this.VERTEXALPHA = false;
  35235. this.BONES = false;
  35236. this.BONES4 = false;
  35237. this.BonesPerMesh = 0;
  35238. this.INSTANCES = false;
  35239. this.POINTSIZE = false;
  35240. this._keys = Object.keys(this);
  35241. }
  35242. return PBRMaterialDefines;
  35243. })(BABYLON.MaterialDefines);
  35244. var PBRMaterial = (function (_super) {
  35245. __extends(PBRMaterial, _super);
  35246. function PBRMaterial(name, scene) {
  35247. _super.call(this, name, scene);
  35248. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35249. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35250. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35251. this._scaledDiffuse = new BABYLON.Color3();
  35252. this._scaledSpecular = new BABYLON.Color3();
  35253. this._defines = new PBRMaterialDefines();
  35254. this._cachedDefines = new PBRMaterialDefines();
  35255. this._cachedDefines.BonesPerMesh = -1;
  35256. }
  35257. PBRMaterial.prototype.needAlphaBlending = function () {
  35258. return this.alpha < 1.0;
  35259. };
  35260. PBRMaterial.prototype.needAlphaTesting = function () {
  35261. return false;
  35262. };
  35263. PBRMaterial.prototype.getAlphaTestTexture = function () {
  35264. return null;
  35265. };
  35266. // Methods
  35267. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  35268. if (this.checkReadyOnlyOnce) {
  35269. if (this._wasPreviouslyReady) {
  35270. return true;
  35271. }
  35272. }
  35273. var scene = this.getScene();
  35274. if (!this.checkReadyOnEveryCall) {
  35275. if (this._renderId === scene.getRenderId()) {
  35276. return true;
  35277. }
  35278. }
  35279. var engine = scene.getEngine();
  35280. var needNormals = false;
  35281. var needUVs = false;
  35282. this._defines.reset();
  35283. // Textures
  35284. if (scene.texturesEnabled) {
  35285. }
  35286. // Effect
  35287. if (scene.clipPlane) {
  35288. this._defines.CLIPPLANE = true;
  35289. }
  35290. if (engine.getAlphaTesting()) {
  35291. this._defines.ALPHATEST = true;
  35292. }
  35293. // Point size
  35294. if (this.pointsCloud || scene.forcePointsCloud) {
  35295. this._defines.POINTSIZE = true;
  35296. }
  35297. // Fog
  35298. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  35299. this._defines.FOG = true;
  35300. }
  35301. // Lights
  35302. // Attribs
  35303. if (mesh) {
  35304. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35305. this._defines.NORMAL = true;
  35306. }
  35307. if (needUVs) {
  35308. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35309. this._defines.UV1 = true;
  35310. }
  35311. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35312. this._defines.UV2 = true;
  35313. }
  35314. }
  35315. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35316. this._defines.VERTEXCOLOR = true;
  35317. if (mesh.hasVertexAlpha) {
  35318. this._defines.VERTEXALPHA = true;
  35319. }
  35320. }
  35321. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35322. this._defines.BONES = true;
  35323. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  35324. this._defines.BONES4 = true;
  35325. }
  35326. // Instances
  35327. if (useInstances) {
  35328. this._defines.INSTANCES = true;
  35329. }
  35330. }
  35331. // Get correct effect
  35332. if (!this._defines.isEqual(this._cachedDefines)) {
  35333. this._defines.cloneTo(this._cachedDefines);
  35334. scene.resetCachedMaterial();
  35335. // Fallbacks
  35336. var fallbacks = new BABYLON.EffectFallbacks();
  35337. if (this._defines.FOG) {
  35338. fallbacks.addFallback(1, "FOG");
  35339. }
  35340. if (this._defines.BONES4) {
  35341. fallbacks.addFallback(0, "BONES4");
  35342. }
  35343. //Attributes
  35344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35345. if (this._defines.NORMAL) {
  35346. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35347. }
  35348. if (this._defines.UV1) {
  35349. attribs.push(BABYLON.VertexBuffer.UVKind);
  35350. }
  35351. if (this._defines.UV2) {
  35352. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35353. }
  35354. if (this._defines.VERTEXCOLOR) {
  35355. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35356. }
  35357. if (this._defines.BONES) {
  35358. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35359. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35360. }
  35361. if (this._defines.INSTANCES) {
  35362. attribs.push("world0");
  35363. attribs.push("world1");
  35364. attribs.push("world2");
  35365. attribs.push("world3");
  35366. }
  35367. // Legacy browser patch
  35368. var join = this._defines.toString();
  35369. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  35370. "vFogInfos", "vFogColor", "pointSize",
  35371. "mBones",
  35372. "vClipPlane",
  35373. ], [], join, fallbacks, this.onCompiled, this.onError);
  35374. }
  35375. if (!this._effect.isReady()) {
  35376. return false;
  35377. }
  35378. this._renderId = scene.getRenderId();
  35379. this._wasPreviouslyReady = true;
  35380. return true;
  35381. };
  35382. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35383. this._effect.setMatrix("world", world);
  35384. };
  35385. PBRMaterial.prototype.bind = function (world, mesh) {
  35386. var scene = this.getScene();
  35387. // Matrices
  35388. this.bindOnlyWorldMatrix(world);
  35389. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35390. // Bones
  35391. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35392. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35393. }
  35394. if (scene.getCachedMaterial() !== this) {
  35395. // Clip plane
  35396. if (scene.clipPlane) {
  35397. var clipPlane = scene.clipPlane;
  35398. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35399. }
  35400. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  35401. }
  35402. // Point size
  35403. if (this.pointsCloud) {
  35404. this._effect.setFloat("pointSize", this.pointSize);
  35405. }
  35406. // Colors
  35407. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  35408. // View
  35409. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35410. this._effect.setMatrix("view", scene.getViewMatrix());
  35411. }
  35412. // Fog
  35413. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35414. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35415. this._effect.setColor3("vFogColor", scene.fogColor);
  35416. }
  35417. _super.prototype.bind.call(this, world, mesh);
  35418. };
  35419. PBRMaterial.prototype.getAnimatables = function () {
  35420. var results = [];
  35421. return results;
  35422. };
  35423. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  35424. _super.prototype.dispose.call(this, forceDisposeEffect);
  35425. };
  35426. PBRMaterial.prototype.clone = function (name) {
  35427. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  35428. // Base material
  35429. this.copyTo(newPBRMaterial);
  35430. // PBRMaterial material
  35431. newPBRMaterial.albedoColor = this.albedoColor.clone();
  35432. return newPBRMaterial;
  35433. };
  35434. return PBRMaterial;
  35435. })(BABYLON.Material);
  35436. BABYLON.PBRMaterial = PBRMaterial;
  35437. })(BABYLON || (BABYLON = {}));
  35438. var BABYLON;
  35439. (function (BABYLON) {
  35440. var ReflectionProbe = (function () {
  35441. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35442. var _this = this;
  35443. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35444. this.name = name;
  35445. this._viewMatrix = BABYLON.Matrix.Identity();
  35446. this._target = BABYLON.Vector3.Zero();
  35447. this._add = BABYLON.Vector3.Zero();
  35448. this.position = BABYLON.Vector3.Zero();
  35449. this._scene = scene;
  35450. this._scene.reflectionProbes.push(this);
  35451. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35452. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35453. switch (faceIndex) {
  35454. case 0:
  35455. _this._add.copyFromFloats(1, 0, 0);
  35456. break;
  35457. case 1:
  35458. _this._add.copyFromFloats(-1, 0, 0);
  35459. break;
  35460. case 2:
  35461. _this._add.copyFromFloats(0, -1, 0);
  35462. break;
  35463. case 3:
  35464. _this._add.copyFromFloats(0, 1, 0);
  35465. break;
  35466. case 4:
  35467. _this._add.copyFromFloats(0, 0, 1);
  35468. break;
  35469. case 5:
  35470. _this._add.copyFromFloats(0, 0, -1);
  35471. break;
  35472. }
  35473. if (_this._attachedMesh) {
  35474. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35475. }
  35476. _this.position.addToRef(_this._add, _this._target);
  35477. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35478. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35479. };
  35480. this._renderTargetTexture.onAfterUnbind = function () {
  35481. scene.updateTransformMatrix(true);
  35482. };
  35483. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35484. }
  35485. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35486. get: function () {
  35487. return this._renderTargetTexture.refreshRate;
  35488. },
  35489. set: function (value) {
  35490. this._renderTargetTexture.refreshRate = value;
  35491. },
  35492. enumerable: true,
  35493. configurable: true
  35494. });
  35495. ReflectionProbe.prototype.getScene = function () {
  35496. return this._scene;
  35497. };
  35498. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35499. get: function () {
  35500. return this._renderTargetTexture;
  35501. },
  35502. enumerable: true,
  35503. configurable: true
  35504. });
  35505. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35506. get: function () {
  35507. return this._renderTargetTexture.renderList;
  35508. },
  35509. enumerable: true,
  35510. configurable: true
  35511. });
  35512. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35513. this._attachedMesh = mesh;
  35514. };
  35515. ReflectionProbe.prototype.dispose = function () {
  35516. var index = this._scene.reflectionProbes.indexOf(this);
  35517. if (index !== -1) {
  35518. // Remove from the scene if found
  35519. this._scene.reflectionProbes.splice(index, 1);
  35520. }
  35521. };
  35522. return ReflectionProbe;
  35523. })();
  35524. BABYLON.ReflectionProbe = ReflectionProbe;
  35525. })(BABYLON || (BABYLON = {}));
  35526. var BABYLON;
  35527. (function (BABYLON) {
  35528. var SolidParticle = (function () {
  35529. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35530. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35531. this.position = BABYLON.Vector3.Zero(); // position
  35532. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35533. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35534. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35535. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35536. this.alive = true; // alive
  35537. this.idx = particleIndex;
  35538. this._pos = positionIndex;
  35539. this._model = model;
  35540. this.shapeId = shapeId;
  35541. this.idxInShape = idxInShape;
  35542. }
  35543. return SolidParticle;
  35544. })();
  35545. BABYLON.SolidParticle = SolidParticle;
  35546. var ModelShape = (function () {
  35547. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35548. this.shapeID = id;
  35549. this._shape = shape;
  35550. this._shapeUV = shapeUV;
  35551. this._positionFunction = posFunction;
  35552. this._vertexFunction = vtxFunction;
  35553. }
  35554. return ModelShape;
  35555. })();
  35556. BABYLON.ModelShape = ModelShape;
  35557. })(BABYLON || (BABYLON = {}));
  35558. var BABYLON;
  35559. (function (BABYLON) {
  35560. var SolidParticleSystem = (function () {
  35561. function SolidParticleSystem(name, scene, options) {
  35562. // public members
  35563. this.particles = new Array();
  35564. this.nbParticles = 0;
  35565. this.billboard = false;
  35566. this.counter = 0;
  35567. this._positions = new Array();
  35568. this._indices = new Array();
  35569. this._normals = new Array();
  35570. this._colors = new Array();
  35571. this._uvs = new Array();
  35572. this._index = 0; // indices index
  35573. this._updatable = true;
  35574. this._shapeCounter = 0;
  35575. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35576. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35577. this._computeParticleColor = true;
  35578. this._computeParticleTexture = true;
  35579. this._computeParticleRotation = true;
  35580. this._computeParticleVertex = false;
  35581. this._cam_axisZ = BABYLON.Vector3.Zero();
  35582. this._cam_axisY = BABYLON.Vector3.Zero();
  35583. this._cam_axisX = BABYLON.Vector3.Zero();
  35584. this._axisX = BABYLON.Axis.X;
  35585. this._axisY = BABYLON.Axis.Y;
  35586. this._axisZ = BABYLON.Axis.Z;
  35587. this._fakeCamPos = BABYLON.Vector3.Zero();
  35588. this._rotMatrix = new BABYLON.Matrix();
  35589. this._invertedMatrix = new BABYLON.Matrix();
  35590. this._rotated = BABYLON.Vector3.Zero();
  35591. this._quaternion = new BABYLON.Quaternion();
  35592. this._vertex = BABYLON.Vector3.Zero();
  35593. this._yaw = 0.0;
  35594. this._pitch = 0.0;
  35595. this._roll = 0.0;
  35596. this._halfroll = 0.0;
  35597. this._halfpitch = 0.0;
  35598. this._halfyaw = 0.0;
  35599. this._sinRoll = 0.0;
  35600. this._cosRoll = 0.0;
  35601. this._sinPitch = 0.0;
  35602. this._cosPitch = 0.0;
  35603. this._sinYaw = 0.0;
  35604. this._cosYaw = 0.0;
  35605. this.name = name;
  35606. this._scene = scene;
  35607. this._camera = scene.activeCamera;
  35608. if (options && options.updatable) {
  35609. this._updatable = options.updatable;
  35610. }
  35611. else {
  35612. this._updatable = true;
  35613. }
  35614. }
  35615. // build the SPS mesh : returns the mesh
  35616. SolidParticleSystem.prototype.buildMesh = function () {
  35617. if (this.nbParticles === 0) {
  35618. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35619. this.addShape(triangle, 1);
  35620. triangle.dispose();
  35621. }
  35622. this._positions32 = new Float32Array(this._positions);
  35623. this._uvs32 = new Float32Array(this._uvs);
  35624. this._colors32 = new Float32Array(this._colors);
  35625. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35626. this._normals32 = new Float32Array(this._normals);
  35627. var vertexData = new BABYLON.VertexData();
  35628. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35629. vertexData.indices = this._indices;
  35630. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35631. if (this._uvs32) {
  35632. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35633. ;
  35634. }
  35635. if (this._colors32) {
  35636. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35637. }
  35638. var mesh = new BABYLON.Mesh(name, this._scene);
  35639. vertexData.applyToMesh(mesh, this._updatable);
  35640. this.mesh = mesh;
  35641. // free memory
  35642. this._positions = null;
  35643. this._normals = null;
  35644. this._uvs = null;
  35645. this._colors = null;
  35646. if (!this._updatable) {
  35647. this.particles.length = 0;
  35648. }
  35649. return mesh;
  35650. };
  35651. //reset copy
  35652. SolidParticleSystem.prototype._resetCopy = function () {
  35653. this._copy.position.x = 0;
  35654. this._copy.position.y = 0;
  35655. this._copy.position.z = 0;
  35656. this._copy.rotation.x = 0;
  35657. this._copy.rotation.y = 0;
  35658. this._copy.rotation.z = 0;
  35659. this._copy.quaternion = null;
  35660. this._copy.scale.x = 1;
  35661. this._copy.scale.y = 1;
  35662. this._copy.scale.z = 1;
  35663. this._copy.uvs.x = 0;
  35664. this._copy.uvs.y = 0;
  35665. this._copy.uvs.z = 1;
  35666. this._copy.uvs.w = 1;
  35667. this._copy.color = null;
  35668. };
  35669. // _meshBuilder : inserts the shape model in the global SPS mesh
  35670. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35671. var i;
  35672. var u = 0;
  35673. var c = 0;
  35674. this._resetCopy();
  35675. if (options && options.positionFunction) {
  35676. options.positionFunction(this._copy, idx, idxInShape);
  35677. }
  35678. if (this._copy.quaternion) {
  35679. this._quaternion.x = this._copy.quaternion.x;
  35680. this._quaternion.y = this._copy.quaternion.y;
  35681. this._quaternion.z = this._copy.quaternion.z;
  35682. this._quaternion.w = this._copy.quaternion.w;
  35683. }
  35684. else {
  35685. this._yaw = this._copy.rotation.y;
  35686. this._pitch = this._copy.rotation.x;
  35687. this._roll = this._copy.rotation.z;
  35688. this._quaternionRotationYPR();
  35689. }
  35690. this._quaternionToRotationMatrix();
  35691. for (i = 0; i < shape.length; i++) {
  35692. this._vertex.x = shape[i].x;
  35693. this._vertex.y = shape[i].y;
  35694. this._vertex.z = shape[i].z;
  35695. if (options && options.vertexFunction) {
  35696. options.vertexFunction(this._copy, this._vertex, i);
  35697. }
  35698. this._vertex.x *= this._copy.scale.x;
  35699. this._vertex.y *= this._copy.scale.y;
  35700. this._vertex.z *= this._copy.scale.z;
  35701. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35702. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35703. if (meshUV) {
  35704. 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);
  35705. u += 2;
  35706. }
  35707. if (this._copy.color) {
  35708. this._color = this._copy.color;
  35709. }
  35710. else if (meshCol && meshCol[c]) {
  35711. this._color.r = meshCol[c];
  35712. this._color.g = meshCol[c + 1];
  35713. this._color.b = meshCol[c + 2];
  35714. this._color.a = meshCol[c + 3];
  35715. }
  35716. else {
  35717. this._color.r = 1;
  35718. this._color.g = 1;
  35719. this._color.b = 1;
  35720. this._color.a = 1;
  35721. }
  35722. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35723. c += 4;
  35724. }
  35725. for (i = 0; i < meshInd.length; i++) {
  35726. indices.push(p + meshInd[i]);
  35727. }
  35728. };
  35729. // returns a shape array from positions array
  35730. SolidParticleSystem.prototype._posToShape = function (positions) {
  35731. var shape = [];
  35732. for (var i = 0; i < positions.length; i += 3) {
  35733. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  35734. }
  35735. return shape;
  35736. };
  35737. // returns a shapeUV array from a Vector4 uvs
  35738. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  35739. var shapeUV = [];
  35740. if (uvs) {
  35741. for (var i = 0; i < uvs.length; i++)
  35742. shapeUV.push(uvs[i]);
  35743. }
  35744. return shapeUV;
  35745. };
  35746. // adds a new particle object in the particles array
  35747. SolidParticleSystem.prototype._addParticle = function (p, idxpos, model, shapeId, idxInShape) {
  35748. this.particles.push(new BABYLON.SolidParticle(p, idxpos, model, shapeId, idxInShape));
  35749. };
  35750. // add solid particles from a shape model in the particles array
  35751. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  35752. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35753. var meshInd = mesh.getIndices();
  35754. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35755. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35756. var shape = this._posToShape(meshPos);
  35757. var shapeUV = this._uvsToShapeUV(meshUV);
  35758. var posfunc = options ? options.positionFunction : null;
  35759. var vtxfunc = options ? options.vertexFunction : null;
  35760. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  35761. // particles
  35762. for (var i = 0; i < nb; i++) {
  35763. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, this.nbParticles + i, i, options);
  35764. if (this._updatable) {
  35765. this._addParticle(this.nbParticles + i, this._positions.length, modelShape, this._shapeCounter, i);
  35766. }
  35767. this._index += shape.length;
  35768. }
  35769. this.nbParticles += nb;
  35770. this._shapeCounter++;
  35771. return this._shapeCounter;
  35772. };
  35773. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  35774. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  35775. this._resetCopy();
  35776. if (particle._model._positionFunction) {
  35777. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  35778. }
  35779. if (this._copy.quaternion) {
  35780. this._quaternion.x = this._copy.quaternion.x;
  35781. this._quaternion.y = this._copy.quaternion.y;
  35782. this._quaternion.z = this._copy.quaternion.z;
  35783. this._quaternion.w = this._copy.quaternion.w;
  35784. }
  35785. else {
  35786. this._yaw = this._copy.rotation.y;
  35787. this._pitch = this._copy.rotation.x;
  35788. this._roll = this._copy.rotation.z;
  35789. this._quaternionRotationYPR();
  35790. }
  35791. this._quaternionToRotationMatrix();
  35792. this._shape = particle._model._shape;
  35793. for (var pt = 0; pt < this._shape.length; pt++) {
  35794. this._vertex.x = this._shape[pt].x;
  35795. this._vertex.y = this._shape[pt].y;
  35796. this._vertex.z = this._shape[pt].z;
  35797. if (particle._model._vertexFunction) {
  35798. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  35799. }
  35800. this._vertex.x *= this._copy.scale.x;
  35801. this._vertex.y *= this._copy.scale.y;
  35802. this._vertex.z *= this._copy.scale.z;
  35803. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35804. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  35805. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  35806. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  35807. }
  35808. particle.position.x = 0;
  35809. particle.position.y = 0;
  35810. particle.position.z = 0;
  35811. particle.rotation.x = 0;
  35812. particle.rotation.y = 0;
  35813. particle.rotation.z = 0;
  35814. particle.quaternion = null;
  35815. particle.scale.x = 1;
  35816. particle.scale.y = 1;
  35817. particle.scale.z = 1;
  35818. };
  35819. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  35820. SolidParticleSystem.prototype.rebuildMesh = function () {
  35821. for (var p = 0; p < this.particles.length; p++) {
  35822. this._rebuildParticle(this.particles[p]);
  35823. }
  35824. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  35825. };
  35826. // sets all the particles : updates the VBO
  35827. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  35828. if (start === void 0) { start = 0; }
  35829. if (end === void 0) { end = this.nbParticles - 1; }
  35830. if (update === void 0) { update = true; }
  35831. // custom beforeUpdate
  35832. this.beforeUpdateParticles(start, end, update);
  35833. this._cam_axisX.x = 1;
  35834. this._cam_axisX.y = 0;
  35835. this._cam_axisX.z = 0;
  35836. this._cam_axisY.x = 0;
  35837. this._cam_axisY.y = 1;
  35838. this._cam_axisY.z = 0;
  35839. this._cam_axisZ.x = 0;
  35840. this._cam_axisZ.y = 0;
  35841. this._cam_axisZ.z = 1;
  35842. // if the particles will always face the camera
  35843. if (this.billboard) {
  35844. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  35845. this._yaw = this.mesh.rotation.y;
  35846. this._pitch = this.mesh.rotation.x;
  35847. this._roll = this.mesh.rotation.z;
  35848. this._quaternionRotationYPR();
  35849. this._quaternionToRotationMatrix();
  35850. this._rotMatrix.invertToRef(this._invertedMatrix);
  35851. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertedMatrix, this._fakeCamPos);
  35852. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  35853. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  35854. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  35855. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  35856. this._cam_axisY.normalize();
  35857. this._cam_axisX.normalize();
  35858. this._cam_axisZ.normalize();
  35859. }
  35860. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  35861. var idx = 0;
  35862. var index = 0;
  35863. var colidx = 0;
  35864. var colorIndex = 0;
  35865. var uvidx = 0;
  35866. var uvIndex = 0;
  35867. // particle loop
  35868. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  35869. for (var p = start; p <= end; p++) {
  35870. this._particle = this.particles[p];
  35871. this._shape = this._particle._model._shape;
  35872. this._shapeUV = this._particle._model._shapeUV;
  35873. // call to custom user function to update the particle properties
  35874. this.updateParticle(this._particle);
  35875. // particle rotation matrix
  35876. if (this.billboard) {
  35877. this._particle.rotation.x = 0.0;
  35878. this._particle.rotation.y = 0.0;
  35879. }
  35880. if (this._computeParticleRotation) {
  35881. if (this._particle.quaternion) {
  35882. this._quaternion.x = this._particle.quaternion.x;
  35883. this._quaternion.y = this._particle.quaternion.y;
  35884. this._quaternion.z = this._particle.quaternion.z;
  35885. this._quaternion.w = this._particle.quaternion.w;
  35886. }
  35887. else {
  35888. this._yaw = this._particle.rotation.y;
  35889. this._pitch = this._particle.rotation.x;
  35890. this._roll = this._particle.rotation.z;
  35891. this._quaternionRotationYPR();
  35892. }
  35893. this._quaternionToRotationMatrix();
  35894. }
  35895. for (var pt = 0; pt < this._shape.length; pt++) {
  35896. idx = index + pt * 3;
  35897. colidx = colorIndex + pt * 4;
  35898. uvidx = uvIndex + pt * 2;
  35899. this._vertex.x = this._shape[pt].x;
  35900. this._vertex.y = this._shape[pt].y;
  35901. this._vertex.z = this._shape[pt].z;
  35902. if (this._computeParticleVertex) {
  35903. this.updateParticleVertex(this._particle, this._vertex, pt);
  35904. }
  35905. this._vertex.x *= this._particle.scale.x;
  35906. this._vertex.y *= this._particle.scale.y;
  35907. this._vertex.z *= this._particle.scale.z;
  35908. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35909. 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;
  35910. 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;
  35911. 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;
  35912. if (this._computeParticleColor) {
  35913. this._colors32[colidx] = this._particle.color.r;
  35914. this._colors32[colidx + 1] = this._particle.color.g;
  35915. this._colors32[colidx + 2] = this._particle.color.b;
  35916. this._colors32[colidx + 3] = this._particle.color.a;
  35917. }
  35918. if (this._computeParticleTexture) {
  35919. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  35920. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  35921. }
  35922. }
  35923. index = idx + 3;
  35924. colorIndex = colidx + 4;
  35925. uvIndex = uvidx + 2;
  35926. }
  35927. if (update) {
  35928. if (this._computeParticleColor) {
  35929. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  35930. }
  35931. if (this._computeParticleTexture) {
  35932. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  35933. }
  35934. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  35935. if (!this.mesh.areNormalsFrozen) {
  35936. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  35937. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  35938. }
  35939. }
  35940. this.afterUpdateParticles(start, end, update);
  35941. };
  35942. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  35943. this._halfroll = this._roll * 0.5;
  35944. this._halfpitch = this._pitch * 0.5;
  35945. this._halfyaw = this._yaw * 0.5;
  35946. this._sinRoll = Math.sin(this._halfroll);
  35947. this._cosRoll = Math.cos(this._halfroll);
  35948. this._sinPitch = Math.sin(this._halfpitch);
  35949. this._cosPitch = Math.cos(this._halfpitch);
  35950. this._sinYaw = Math.sin(this._halfyaw);
  35951. this._cosYaw = Math.cos(this._halfyaw);
  35952. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  35953. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  35954. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  35955. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  35956. };
  35957. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  35958. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  35959. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  35960. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  35961. this._rotMatrix.m[3] = 0;
  35962. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  35963. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  35964. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  35965. this._rotMatrix.m[7] = 0;
  35966. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  35967. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  35968. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  35969. this._rotMatrix.m[11] = 0;
  35970. this._rotMatrix.m[12] = 0;
  35971. this._rotMatrix.m[13] = 0;
  35972. this._rotMatrix.m[14] = 0;
  35973. this._rotMatrix.m[15] = 1.0;
  35974. };
  35975. // dispose the SPS
  35976. SolidParticleSystem.prototype.dispose = function () {
  35977. this.mesh.dispose();
  35978. // drop references to internal big arrays for the GC
  35979. this._positions = null;
  35980. this._indices = null;
  35981. this._normals = null;
  35982. this._uvs = null;
  35983. this._colors = null;
  35984. this._positions32 = null;
  35985. this._normals32 = null;
  35986. this._uvs32 = null;
  35987. this._colors32 = null;
  35988. };
  35989. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  35990. // getters
  35991. get: function () {
  35992. return this._computeParticleRotation;
  35993. },
  35994. // Optimizer setters
  35995. set: function (val) {
  35996. this._computeParticleRotation = val;
  35997. },
  35998. enumerable: true,
  35999. configurable: true
  36000. });
  36001. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36002. get: function () {
  36003. return this._computeParticleColor;
  36004. },
  36005. set: function (val) {
  36006. this._computeParticleColor = val;
  36007. },
  36008. enumerable: true,
  36009. configurable: true
  36010. });
  36011. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36012. get: function () {
  36013. return this._computeParticleTexture;
  36014. },
  36015. set: function (val) {
  36016. this._computeParticleTexture = val;
  36017. },
  36018. enumerable: true,
  36019. configurable: true
  36020. });
  36021. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36022. get: function () {
  36023. return this._computeParticleVertex;
  36024. },
  36025. set: function (val) {
  36026. this._computeParticleVertex = val;
  36027. },
  36028. enumerable: true,
  36029. configurable: true
  36030. });
  36031. // =======================================================================
  36032. // Particle behavior logic
  36033. // these following methods may be overwritten by the user to fit his needs
  36034. // init : sets all particles first values and calls updateParticle to set them in space
  36035. // can be overwritten by the user
  36036. SolidParticleSystem.prototype.initParticles = function () {
  36037. };
  36038. // recycles a particle : can by overwritten by the user
  36039. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36040. return particle;
  36041. };
  36042. // updates a particle : can be overwritten by the user
  36043. // will be called on each particle by setParticles() :
  36044. // ex : just set a particle position or velocity and recycle conditions
  36045. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36046. return particle;
  36047. };
  36048. // updates a vertex of a particle : can be overwritten by the user
  36049. // will be called on each vertex particle by setParticles() :
  36050. // particle : the current particle
  36051. // vertex : the current index of the current particle
  36052. // pt : the index of the current vertex in the particle shape
  36053. // ex : just set a vertex particle position
  36054. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36055. return vertex;
  36056. };
  36057. // will be called before any other treatment by setParticles()
  36058. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36059. };
  36060. // will be called after all setParticles() treatments
  36061. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36062. };
  36063. return SolidParticleSystem;
  36064. })();
  36065. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36066. })(BABYLON || (BABYLON = {}));
  36067. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"precision highp float;\r\n\r\n// Constants\r\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\n\tvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvarying vec3 vDirectionW;\r\n#endif\r\n\r\n\t#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\n\t\tuniform mat4 reflectionMatrix;\r\n\t#endif\r\n\t#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\n\t\tuniform mat4 view;\r\n\t#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 bias, float darkness)\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 visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-0.094201624, 0.04, -0.039906216);\r\n\tpoissonDisk[1] = vec3(0.094558609, -0.04, -0.076890725);\r\n\tpoissonDisk[2] = vec3(-0.094184101, 0.01, -0.092938870);\r\n\tpoissonDisk[3] = vec3(0.034495938, -0.01, 0.029387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0])) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1])) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2])) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3])) < 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\t#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#endif\r\n#else\r\n\t#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#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.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\t#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#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.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\t#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#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\t\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.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\t#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#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\t#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\t#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\t#ifdef USELIGHTMAPASSHADOWMAP\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t#else\r\n\t\tcolor.rgb += lightmapColor;\r\n\t#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#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform 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\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#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#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"precision highp float;\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\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#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#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;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#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}","marblePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = 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}","woodPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  36068. 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={}));";
  36069. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36070. module.exports = BABYLON;
  36071. };