babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. 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);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. 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);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Vector3.Zero();
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1;
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1 = new Vector3(x, y, z);
  902. u1.normalize();
  903. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  904. cross.normalize();
  905. if (Vector3.Dot(w, cross) < 0) {
  906. sign = 1.0;
  907. }
  908. dot = Vector3.Dot(u, u1);
  909. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  910. roll = Math.acos(dot) * sign;
  911. if (Vector3.Dot(u1, X) < 0) {
  912. roll = Math.PI + roll;
  913. u1 = u1.scaleInPlace(-1);
  914. nbRevert++;
  915. }
  916. // step 2 : rotate around u1
  917. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  918. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  919. var w2;
  920. var v2;
  921. x = 0.0;
  922. y = 0.0;
  923. z = 0.0;
  924. sign = -1.0;
  925. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  926. x = 1.0;
  927. }
  928. else {
  929. t = u1.z / u1.x;
  930. x = -t * Math.sqrt(1 / (1 + t * t));
  931. z = Math.sqrt(1 / (1 + t * t));
  932. }
  933. w2 = new Vector3(x, y, z);
  934. w2.normalize();
  935. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  936. v2.normalize();
  937. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  938. cross.normalize();
  939. if (Vector3.Dot(u1, cross) < 0) {
  940. sign = 1.0;
  941. }
  942. dot = Vector3.Dot(w, w2);
  943. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  944. pitch = Math.acos(dot) * sign;
  945. if (Vector3.Dot(v2, Y) < 0) {
  946. pitch = Math.PI + pitch;
  947. nbRevert++;
  948. }
  949. // step 3 : rotate around v2
  950. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  951. sign = -1.0;
  952. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  953. cross.normalize();
  954. if (Vector3.Dot(cross, Y) < 0) {
  955. sign = 1.0;
  956. }
  957. dot = Vector3.Dot(u1, X);
  958. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  959. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  960. if (dot < 0 && nbRevert < 2) {
  961. yaw = Math.PI + yaw;
  962. }
  963. ref.x = pitch;
  964. ref.y = yaw;
  965. ref.z = roll;
  966. };
  967. return Vector3;
  968. })();
  969. BABYLON.Vector3 = Vector3;
  970. //Vector4 class created for EulerAngle class conversion to Quaternion
  971. var Vector4 = (function () {
  972. function Vector4(x, y, z, w) {
  973. this.x = x;
  974. this.y = y;
  975. this.z = z;
  976. this.w = w;
  977. }
  978. Vector4.prototype.toString = function () {
  979. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  980. };
  981. // Operators
  982. Vector4.prototype.asArray = function () {
  983. var result = [];
  984. this.toArray(result, 0);
  985. return result;
  986. };
  987. Vector4.prototype.toArray = function (array, index) {
  988. if (index === undefined) {
  989. index = 0;
  990. }
  991. array[index] = this.x;
  992. array[index + 1] = this.y;
  993. array[index + 2] = this.z;
  994. array[index + 3] = this.w;
  995. return this;
  996. };
  997. Vector4.prototype.addInPlace = function (otherVector) {
  998. this.x += otherVector.x;
  999. this.y += otherVector.y;
  1000. this.z += otherVector.z;
  1001. this.w += otherVector.w;
  1002. return this;
  1003. };
  1004. Vector4.prototype.add = function (otherVector) {
  1005. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1006. };
  1007. Vector4.prototype.addToRef = function (otherVector, result) {
  1008. result.x = this.x + otherVector.x;
  1009. result.y = this.y + otherVector.y;
  1010. result.z = this.z + otherVector.z;
  1011. result.w = this.w + otherVector.w;
  1012. return this;
  1013. };
  1014. Vector4.prototype.subtractInPlace = function (otherVector) {
  1015. this.x -= otherVector.x;
  1016. this.y -= otherVector.y;
  1017. this.z -= otherVector.z;
  1018. this.w -= otherVector.w;
  1019. return this;
  1020. };
  1021. Vector4.prototype.subtract = function (otherVector) {
  1022. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1023. };
  1024. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1025. result.x = this.x - otherVector.x;
  1026. result.y = this.y - otherVector.y;
  1027. result.z = this.z - otherVector.z;
  1028. result.w = this.w - otherVector.w;
  1029. return this;
  1030. };
  1031. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1032. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1033. };
  1034. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1035. result.x = this.x - x;
  1036. result.y = this.y - y;
  1037. result.z = this.z - z;
  1038. result.w = this.w - w;
  1039. return this;
  1040. };
  1041. Vector4.prototype.negate = function () {
  1042. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1043. };
  1044. Vector4.prototype.scaleInPlace = function (scale) {
  1045. this.x *= scale;
  1046. this.y *= scale;
  1047. this.z *= scale;
  1048. this.w *= scale;
  1049. return this;
  1050. };
  1051. Vector4.prototype.scale = function (scale) {
  1052. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1053. };
  1054. Vector4.prototype.scaleToRef = function (scale, result) {
  1055. result.x = this.x * scale;
  1056. result.y = this.y * scale;
  1057. result.z = this.z * scale;
  1058. result.w = this.w * scale;
  1059. };
  1060. Vector4.prototype.equals = function (otherVector) {
  1061. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1062. };
  1063. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1064. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1065. return otherVector
  1066. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1067. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1068. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1069. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1070. };
  1071. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1072. return this.x === x && this.y === y && this.z === z && this.w === w;
  1073. };
  1074. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1075. this.x *= otherVector.x;
  1076. this.y *= otherVector.y;
  1077. this.z *= otherVector.z;
  1078. this.w *= otherVector.w;
  1079. return this;
  1080. };
  1081. Vector4.prototype.multiply = function (otherVector) {
  1082. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1083. };
  1084. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1085. result.x = this.x * otherVector.x;
  1086. result.y = this.y * otherVector.y;
  1087. result.z = this.z * otherVector.z;
  1088. result.w = this.w * otherVector.w;
  1089. return this;
  1090. };
  1091. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1092. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1093. };
  1094. Vector4.prototype.divide = function (otherVector) {
  1095. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1096. };
  1097. Vector4.prototype.divideToRef = function (otherVector, result) {
  1098. result.x = this.x / otherVector.x;
  1099. result.y = this.y / otherVector.y;
  1100. result.z = this.z / otherVector.z;
  1101. result.w = this.w / otherVector.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MinimizeInPlace = function (other) {
  1105. if (other.x < this.x)
  1106. this.x = other.x;
  1107. if (other.y < this.y)
  1108. this.y = other.y;
  1109. if (other.z < this.z)
  1110. this.z = other.z;
  1111. if (other.w < this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. Vector4.prototype.MaximizeInPlace = function (other) {
  1116. if (other.x > this.x)
  1117. this.x = other.x;
  1118. if (other.y > this.y)
  1119. this.y = other.y;
  1120. if (other.z > this.z)
  1121. this.z = other.z;
  1122. if (other.w > this.w)
  1123. this.w = other.w;
  1124. return this;
  1125. };
  1126. // Properties
  1127. Vector4.prototype.length = function () {
  1128. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1129. };
  1130. Vector4.prototype.lengthSquared = function () {
  1131. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1132. };
  1133. // Methods
  1134. Vector4.prototype.normalize = function () {
  1135. var len = this.length();
  1136. if (len === 0)
  1137. return this;
  1138. var num = 1.0 / len;
  1139. this.x *= num;
  1140. this.y *= num;
  1141. this.z *= num;
  1142. this.w *= num;
  1143. return this;
  1144. };
  1145. Vector4.prototype.clone = function () {
  1146. return new Vector4(this.x, this.y, this.z, this.w);
  1147. };
  1148. Vector4.prototype.copyFrom = function (source) {
  1149. this.x = source.x;
  1150. this.y = source.y;
  1151. this.z = source.z;
  1152. this.w = source.w;
  1153. return this;
  1154. };
  1155. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1156. this.x = x;
  1157. this.y = y;
  1158. this.z = z;
  1159. this.w = w;
  1160. return this;
  1161. };
  1162. // Statics
  1163. Vector4.FromArray = function (array, offset) {
  1164. if (!offset) {
  1165. offset = 0;
  1166. }
  1167. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1168. };
  1169. Vector4.FromArrayToRef = function (array, offset, result) {
  1170. result.x = array[offset];
  1171. result.y = array[offset + 1];
  1172. result.z = array[offset + 2];
  1173. result.w = array[offset + 3];
  1174. };
  1175. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1176. result.x = array[offset];
  1177. result.y = array[offset + 1];
  1178. result.z = array[offset + 2];
  1179. result.w = array[offset + 3];
  1180. };
  1181. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1182. result.x = x;
  1183. result.y = y;
  1184. result.z = z;
  1185. result.w = w;
  1186. };
  1187. Vector4.Zero = function () {
  1188. return new Vector4(0, 0, 0, 0);
  1189. };
  1190. Vector4.Normalize = function (vector) {
  1191. var result = Vector4.Zero();
  1192. Vector4.NormalizeToRef(vector, result);
  1193. return result;
  1194. };
  1195. Vector4.NormalizeToRef = function (vector, result) {
  1196. result.copyFrom(vector);
  1197. result.normalize();
  1198. };
  1199. Vector4.Minimize = function (left, right) {
  1200. var min = left.clone();
  1201. min.MinimizeInPlace(right);
  1202. return min;
  1203. };
  1204. Vector4.Maximize = function (left, right) {
  1205. var max = left.clone();
  1206. max.MaximizeInPlace(right);
  1207. return max;
  1208. };
  1209. Vector4.Distance = function (value1, value2) {
  1210. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1211. };
  1212. Vector4.DistanceSquared = function (value1, value2) {
  1213. var x = value1.x - value2.x;
  1214. var y = value1.y - value2.y;
  1215. var z = value1.z - value2.z;
  1216. var w = value1.w - value2.w;
  1217. return (x * x) + (y * y) + (z * z) + (w * w);
  1218. };
  1219. Vector4.Center = function (value1, value2) {
  1220. var center = value1.add(value2);
  1221. center.scaleInPlace(0.5);
  1222. return center;
  1223. };
  1224. return Vector4;
  1225. })();
  1226. BABYLON.Vector4 = Vector4;
  1227. var Quaternion = (function () {
  1228. function Quaternion(x, y, z, w) {
  1229. if (x === void 0) { x = 0; }
  1230. if (y === void 0) { y = 0; }
  1231. if (z === void 0) { z = 0; }
  1232. if (w === void 0) { w = 1; }
  1233. this.x = x;
  1234. this.y = y;
  1235. this.z = z;
  1236. this.w = w;
  1237. }
  1238. Quaternion.prototype.toString = function () {
  1239. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1240. };
  1241. Quaternion.prototype.asArray = function () {
  1242. return [this.x, this.y, this.z, this.w];
  1243. };
  1244. Quaternion.prototype.equals = function (otherQuaternion) {
  1245. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1246. };
  1247. Quaternion.prototype.clone = function () {
  1248. return new Quaternion(this.x, this.y, this.z, this.w);
  1249. };
  1250. Quaternion.prototype.copyFrom = function (other) {
  1251. this.x = other.x;
  1252. this.y = other.y;
  1253. this.z = other.z;
  1254. this.w = other.w;
  1255. return this;
  1256. };
  1257. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1258. this.x = x;
  1259. this.y = y;
  1260. this.z = z;
  1261. this.w = w;
  1262. return this;
  1263. };
  1264. Quaternion.prototype.add = function (other) {
  1265. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1266. };
  1267. Quaternion.prototype.subtract = function (other) {
  1268. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1269. };
  1270. Quaternion.prototype.scale = function (value) {
  1271. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1272. };
  1273. Quaternion.prototype.multiply = function (q1) {
  1274. var result = new Quaternion(0, 0, 0, 1.0);
  1275. this.multiplyToRef(q1, result);
  1276. return result;
  1277. };
  1278. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1279. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1280. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1281. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1282. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1283. result.copyFromFloats(x, y, z, w);
  1284. return this;
  1285. };
  1286. Quaternion.prototype.multiplyInPlace = function (q1) {
  1287. this.multiplyToRef(q1, this);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.length = function () {
  1291. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1292. };
  1293. Quaternion.prototype.normalize = function () {
  1294. var length = 1.0 / this.length();
  1295. this.x *= length;
  1296. this.y *= length;
  1297. this.z *= length;
  1298. this.w *= length;
  1299. return this;
  1300. };
  1301. Quaternion.prototype.toEulerAngles = function () {
  1302. var result = Vector3.Zero();
  1303. this.toEulerAnglesToRef(result);
  1304. return result;
  1305. };
  1306. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1307. //result is an EulerAngles in the in the z-x-z convention
  1308. var qx = this.x;
  1309. var qy = this.y;
  1310. var qz = this.z;
  1311. var qw = this.w;
  1312. var qxy = qx * qy;
  1313. var qxz = qx * qz;
  1314. var qwy = qw * qy;
  1315. var qwz = qw * qz;
  1316. var qwx = qw * qx;
  1317. var qyz = qy * qz;
  1318. var sqx = qx * qx;
  1319. var sqy = qy * qy;
  1320. var determinant = sqx + sqy;
  1321. if (determinant !== 0.000 && determinant !== 1.000) {
  1322. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1323. result.y = Math.acos(1 - 2 * determinant);
  1324. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1325. }
  1326. else {
  1327. if (determinant === 0.0) {
  1328. result.x = 0.0;
  1329. result.y = 0.0;
  1330. 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)
  1331. }
  1332. else {
  1333. 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)
  1334. result.y = Math.PI;
  1335. result.z = 0.0;
  1336. }
  1337. }
  1338. return this;
  1339. };
  1340. Quaternion.prototype.toRotationMatrix = function (result) {
  1341. var xx = this.x * this.x;
  1342. var yy = this.y * this.y;
  1343. var zz = this.z * this.z;
  1344. var xy = this.x * this.y;
  1345. var zw = this.z * this.w;
  1346. var zx = this.z * this.x;
  1347. var yw = this.y * this.w;
  1348. var yz = this.y * this.z;
  1349. var xw = this.x * this.w;
  1350. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1351. result.m[1] = 2.0 * (xy + zw);
  1352. result.m[2] = 2.0 * (zx - yw);
  1353. result.m[3] = 0;
  1354. result.m[4] = 2.0 * (xy - zw);
  1355. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1356. result.m[6] = 2.0 * (yz + xw);
  1357. result.m[7] = 0;
  1358. result.m[8] = 2.0 * (zx + yw);
  1359. result.m[9] = 2.0 * (yz - xw);
  1360. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1361. result.m[11] = 0;
  1362. result.m[12] = 0;
  1363. result.m[13] = 0;
  1364. result.m[14] = 0;
  1365. result.m[15] = 1.0;
  1366. return this;
  1367. };
  1368. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1369. Quaternion.FromRotationMatrixToRef(matrix, this);
  1370. return this;
  1371. };
  1372. // Statics
  1373. Quaternion.FromRotationMatrix = function (matrix) {
  1374. var result = new Quaternion();
  1375. Quaternion.FromRotationMatrixToRef(matrix, result);
  1376. return result;
  1377. };
  1378. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1379. var data = matrix.m;
  1380. var m11 = data[0], m12 = data[4], m13 = data[8];
  1381. var m21 = data[1], m22 = data[5], m23 = data[9];
  1382. var m31 = data[2], m32 = data[6], m33 = data[10];
  1383. var trace = m11 + m22 + m33;
  1384. var s;
  1385. if (trace > 0) {
  1386. s = 0.5 / Math.sqrt(trace + 1.0);
  1387. result.w = 0.25 / s;
  1388. result.x = (m32 - m23) * s;
  1389. result.y = (m13 - m31) * s;
  1390. result.z = (m21 - m12) * s;
  1391. }
  1392. else if (m11 > m22 && m11 > m33) {
  1393. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1394. result.w = (m32 - m23) / s;
  1395. result.x = 0.25 * s;
  1396. result.y = (m12 + m21) / s;
  1397. result.z = (m13 + m31) / s;
  1398. }
  1399. else if (m22 > m33) {
  1400. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1401. result.w = (m13 - m31) / s;
  1402. result.x = (m12 + m21) / s;
  1403. result.y = 0.25 * s;
  1404. result.z = (m23 + m32) / s;
  1405. }
  1406. else {
  1407. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1408. result.w = (m21 - m12) / s;
  1409. result.x = (m13 + m31) / s;
  1410. result.y = (m23 + m32) / s;
  1411. result.z = 0.25 * s;
  1412. }
  1413. };
  1414. Quaternion.Inverse = function (q) {
  1415. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1416. };
  1417. Quaternion.Identity = function () {
  1418. return new Quaternion(0, 0, 0, 1);
  1419. };
  1420. Quaternion.RotationAxis = function (axis, angle) {
  1421. var result = new Quaternion();
  1422. var sin = Math.sin(angle / 2);
  1423. axis.normalize();
  1424. result.w = Math.cos(angle / 2);
  1425. result.x = axis.x * sin;
  1426. result.y = axis.y * sin;
  1427. result.z = axis.z * sin;
  1428. return result;
  1429. };
  1430. Quaternion.FromArray = function (array, offset) {
  1431. if (!offset) {
  1432. offset = 0;
  1433. }
  1434. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1435. };
  1436. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1437. var result = new Quaternion();
  1438. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1439. return result;
  1440. };
  1441. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1442. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1443. var halfRoll = roll * 0.5;
  1444. var halfPitch = pitch * 0.5;
  1445. var halfYaw = yaw * 0.5;
  1446. var sinRoll = Math.sin(halfRoll);
  1447. var cosRoll = Math.cos(halfRoll);
  1448. var sinPitch = Math.sin(halfPitch);
  1449. var cosPitch = Math.cos(halfPitch);
  1450. var sinYaw = Math.sin(halfYaw);
  1451. var cosYaw = Math.cos(halfYaw);
  1452. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1453. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1454. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1455. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1456. };
  1457. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1458. var result = new Quaternion();
  1459. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1460. return result;
  1461. };
  1462. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1463. // Produces a quaternion from Euler angles in the z-x-z orientation
  1464. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1465. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1466. var halfBeta = beta * 0.5;
  1467. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1468. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1469. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1470. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1471. };
  1472. Quaternion.Slerp = function (left, right, amount) {
  1473. var num2;
  1474. var num3;
  1475. var num = amount;
  1476. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1477. var flag = false;
  1478. if (num4 < 0) {
  1479. flag = true;
  1480. num4 = -num4;
  1481. }
  1482. if (num4 > 0.999999) {
  1483. num3 = 1 - num;
  1484. num2 = flag ? -num : num;
  1485. }
  1486. else {
  1487. var num5 = Math.acos(num4);
  1488. var num6 = (1.0 / Math.sin(num5));
  1489. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1490. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1491. }
  1492. 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));
  1493. };
  1494. return Quaternion;
  1495. })();
  1496. BABYLON.Quaternion = Quaternion;
  1497. var Matrix = (function () {
  1498. function Matrix() {
  1499. this.m = new Float32Array(16);
  1500. }
  1501. // Properties
  1502. Matrix.prototype.isIdentity = function () {
  1503. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1504. return false;
  1505. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1506. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1507. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1508. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1509. return false;
  1510. return true;
  1511. };
  1512. Matrix.prototype.determinant = function () {
  1513. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1514. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1515. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1516. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1517. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1518. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1519. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1520. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1521. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1522. };
  1523. // Methods
  1524. Matrix.prototype.toArray = function () {
  1525. return this.m;
  1526. };
  1527. Matrix.prototype.asArray = function () {
  1528. return this.toArray();
  1529. };
  1530. Matrix.prototype.invert = function () {
  1531. this.invertToRef(this);
  1532. return this;
  1533. };
  1534. Matrix.prototype.reset = function () {
  1535. for (var index = 0; index < 16; index++) {
  1536. this.m[index] = 0;
  1537. }
  1538. return this;
  1539. };
  1540. Matrix.prototype.add = function (other) {
  1541. var result = new Matrix();
  1542. this.addToRef(other, result);
  1543. return result;
  1544. };
  1545. Matrix.prototype.addToRef = function (other, result) {
  1546. for (var index = 0; index < 16; index++) {
  1547. result.m[index] = this.m[index] + other.m[index];
  1548. }
  1549. return this;
  1550. };
  1551. Matrix.prototype.addToSelf = function (other) {
  1552. for (var index = 0; index < 16; index++) {
  1553. this.m[index] += other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.invertToRef = function (other) {
  1558. var l1 = this.m[0];
  1559. var l2 = this.m[1];
  1560. var l3 = this.m[2];
  1561. var l4 = this.m[3];
  1562. var l5 = this.m[4];
  1563. var l6 = this.m[5];
  1564. var l7 = this.m[6];
  1565. var l8 = this.m[7];
  1566. var l9 = this.m[8];
  1567. var l10 = this.m[9];
  1568. var l11 = this.m[10];
  1569. var l12 = this.m[11];
  1570. var l13 = this.m[12];
  1571. var l14 = this.m[13];
  1572. var l15 = this.m[14];
  1573. var l16 = this.m[15];
  1574. var l17 = (l11 * l16) - (l12 * l15);
  1575. var l18 = (l10 * l16) - (l12 * l14);
  1576. var l19 = (l10 * l15) - (l11 * l14);
  1577. var l20 = (l9 * l16) - (l12 * l13);
  1578. var l21 = (l9 * l15) - (l11 * l13);
  1579. var l22 = (l9 * l14) - (l10 * l13);
  1580. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1581. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1582. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1583. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1584. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1585. var l28 = (l7 * l16) - (l8 * l15);
  1586. var l29 = (l6 * l16) - (l8 * l14);
  1587. var l30 = (l6 * l15) - (l7 * l14);
  1588. var l31 = (l5 * l16) - (l8 * l13);
  1589. var l32 = (l5 * l15) - (l7 * l13);
  1590. var l33 = (l5 * l14) - (l6 * l13);
  1591. var l34 = (l7 * l12) - (l8 * l11);
  1592. var l35 = (l6 * l12) - (l8 * l10);
  1593. var l36 = (l6 * l11) - (l7 * l10);
  1594. var l37 = (l5 * l12) - (l8 * l9);
  1595. var l38 = (l5 * l11) - (l7 * l9);
  1596. var l39 = (l5 * l10) - (l6 * l9);
  1597. other.m[0] = l23 * l27;
  1598. other.m[4] = l24 * l27;
  1599. other.m[8] = l25 * l27;
  1600. other.m[12] = l26 * l27;
  1601. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1602. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1603. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1604. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1605. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1606. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1607. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1608. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1609. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1610. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1611. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1612. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1613. return this;
  1614. };
  1615. Matrix.prototype.setTranslation = function (vector3) {
  1616. this.m[12] = vector3.x;
  1617. this.m[13] = vector3.y;
  1618. this.m[14] = vector3.z;
  1619. return this;
  1620. };
  1621. Matrix.prototype.multiply = function (other) {
  1622. var result = new Matrix();
  1623. this.multiplyToRef(other, result);
  1624. return result;
  1625. };
  1626. Matrix.prototype.copyFrom = function (other) {
  1627. for (var index = 0; index < 16; index++) {
  1628. this.m[index] = other.m[index];
  1629. }
  1630. return this;
  1631. };
  1632. Matrix.prototype.copyToArray = function (array, offset) {
  1633. if (offset === void 0) { offset = 0; }
  1634. for (var index = 0; index < 16; index++) {
  1635. array[offset + index] = this.m[index];
  1636. }
  1637. return this;
  1638. };
  1639. Matrix.prototype.multiplyToRef = function (other, result) {
  1640. this.multiplyToArray(other, result.m, 0);
  1641. return this;
  1642. };
  1643. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1644. var tm0 = this.m[0];
  1645. var tm1 = this.m[1];
  1646. var tm2 = this.m[2];
  1647. var tm3 = this.m[3];
  1648. var tm4 = this.m[4];
  1649. var tm5 = this.m[5];
  1650. var tm6 = this.m[6];
  1651. var tm7 = this.m[7];
  1652. var tm8 = this.m[8];
  1653. var tm9 = this.m[9];
  1654. var tm10 = this.m[10];
  1655. var tm11 = this.m[11];
  1656. var tm12 = this.m[12];
  1657. var tm13 = this.m[13];
  1658. var tm14 = this.m[14];
  1659. var tm15 = this.m[15];
  1660. var om0 = other.m[0];
  1661. var om1 = other.m[1];
  1662. var om2 = other.m[2];
  1663. var om3 = other.m[3];
  1664. var om4 = other.m[4];
  1665. var om5 = other.m[5];
  1666. var om6 = other.m[6];
  1667. var om7 = other.m[7];
  1668. var om8 = other.m[8];
  1669. var om9 = other.m[9];
  1670. var om10 = other.m[10];
  1671. var om11 = other.m[11];
  1672. var om12 = other.m[12];
  1673. var om13 = other.m[13];
  1674. var om14 = other.m[14];
  1675. var om15 = other.m[15];
  1676. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1677. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1678. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1679. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1680. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1681. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1682. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1683. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1684. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1685. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1686. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1687. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1688. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1689. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1690. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1691. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1692. return this;
  1693. };
  1694. Matrix.prototype.equals = function (value) {
  1695. return value &&
  1696. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1697. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1698. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1699. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1700. };
  1701. Matrix.prototype.clone = function () {
  1702. 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]);
  1703. };
  1704. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1705. translation.x = this.m[12];
  1706. translation.y = this.m[13];
  1707. translation.z = this.m[14];
  1708. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1709. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1710. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1711. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1712. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1713. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1714. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1715. rotation.x = 0;
  1716. rotation.y = 0;
  1717. rotation.z = 0;
  1718. rotation.w = 1;
  1719. return false;
  1720. }
  1721. 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);
  1722. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1723. return true;
  1724. };
  1725. // Statics
  1726. Matrix.FromArray = function (array, offset) {
  1727. var result = new Matrix();
  1728. if (!offset) {
  1729. offset = 0;
  1730. }
  1731. Matrix.FromArrayToRef(array, offset, result);
  1732. return result;
  1733. };
  1734. Matrix.FromArrayToRef = function (array, offset, result) {
  1735. for (var index = 0; index < 16; index++) {
  1736. result.m[index] = array[index + offset];
  1737. }
  1738. };
  1739. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1740. for (var index = 0; index < 16; index++) {
  1741. result.m[index] = array[index + offset] * scale;
  1742. }
  1743. };
  1744. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1745. result.m[0] = initialM11;
  1746. result.m[1] = initialM12;
  1747. result.m[2] = initialM13;
  1748. result.m[3] = initialM14;
  1749. result.m[4] = initialM21;
  1750. result.m[5] = initialM22;
  1751. result.m[6] = initialM23;
  1752. result.m[7] = initialM24;
  1753. result.m[8] = initialM31;
  1754. result.m[9] = initialM32;
  1755. result.m[10] = initialM33;
  1756. result.m[11] = initialM34;
  1757. result.m[12] = initialM41;
  1758. result.m[13] = initialM42;
  1759. result.m[14] = initialM43;
  1760. result.m[15] = initialM44;
  1761. };
  1762. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1763. var result = new Matrix();
  1764. result.m[0] = initialM11;
  1765. result.m[1] = initialM12;
  1766. result.m[2] = initialM13;
  1767. result.m[3] = initialM14;
  1768. result.m[4] = initialM21;
  1769. result.m[5] = initialM22;
  1770. result.m[6] = initialM23;
  1771. result.m[7] = initialM24;
  1772. result.m[8] = initialM31;
  1773. result.m[9] = initialM32;
  1774. result.m[10] = initialM33;
  1775. result.m[11] = initialM34;
  1776. result.m[12] = initialM41;
  1777. result.m[13] = initialM42;
  1778. result.m[14] = initialM43;
  1779. result.m[15] = initialM44;
  1780. return result;
  1781. };
  1782. Matrix.Compose = function (scale, rotation, translation) {
  1783. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1784. var rotationMatrix = Matrix.Identity();
  1785. rotation.toRotationMatrix(rotationMatrix);
  1786. result = result.multiply(rotationMatrix);
  1787. result.setTranslation(translation);
  1788. return result;
  1789. };
  1790. Matrix.Identity = function () {
  1791. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1792. };
  1793. Matrix.IdentityToRef = function (result) {
  1794. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1795. };
  1796. Matrix.Zero = function () {
  1797. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1798. };
  1799. Matrix.RotationX = function (angle) {
  1800. var result = new Matrix();
  1801. Matrix.RotationXToRef(angle, result);
  1802. return result;
  1803. };
  1804. Matrix.Invert = function (source) {
  1805. var result = new Matrix();
  1806. source.invertToRef(result);
  1807. return result;
  1808. };
  1809. Matrix.RotationXToRef = function (angle, result) {
  1810. var s = Math.sin(angle);
  1811. var c = Math.cos(angle);
  1812. result.m[0] = 1.0;
  1813. result.m[15] = 1.0;
  1814. result.m[5] = c;
  1815. result.m[10] = c;
  1816. result.m[9] = -s;
  1817. result.m[6] = s;
  1818. result.m[1] = 0;
  1819. result.m[2] = 0;
  1820. result.m[3] = 0;
  1821. result.m[4] = 0;
  1822. result.m[7] = 0;
  1823. result.m[8] = 0;
  1824. result.m[11] = 0;
  1825. result.m[12] = 0;
  1826. result.m[13] = 0;
  1827. result.m[14] = 0;
  1828. };
  1829. Matrix.RotationY = function (angle) {
  1830. var result = new Matrix();
  1831. Matrix.RotationYToRef(angle, result);
  1832. return result;
  1833. };
  1834. Matrix.RotationYToRef = function (angle, result) {
  1835. var s = Math.sin(angle);
  1836. var c = Math.cos(angle);
  1837. result.m[5] = 1.0;
  1838. result.m[15] = 1.0;
  1839. result.m[0] = c;
  1840. result.m[2] = -s;
  1841. result.m[8] = s;
  1842. result.m[10] = c;
  1843. result.m[1] = 0;
  1844. result.m[3] = 0;
  1845. result.m[4] = 0;
  1846. result.m[6] = 0;
  1847. result.m[7] = 0;
  1848. result.m[9] = 0;
  1849. result.m[11] = 0;
  1850. result.m[12] = 0;
  1851. result.m[13] = 0;
  1852. result.m[14] = 0;
  1853. };
  1854. Matrix.RotationZ = function (angle) {
  1855. var result = new Matrix();
  1856. Matrix.RotationZToRef(angle, result);
  1857. return result;
  1858. };
  1859. Matrix.RotationZToRef = function (angle, result) {
  1860. var s = Math.sin(angle);
  1861. var c = Math.cos(angle);
  1862. result.m[10] = 1.0;
  1863. result.m[15] = 1.0;
  1864. result.m[0] = c;
  1865. result.m[1] = s;
  1866. result.m[4] = -s;
  1867. result.m[5] = c;
  1868. result.m[2] = 0;
  1869. result.m[3] = 0;
  1870. result.m[6] = 0;
  1871. result.m[7] = 0;
  1872. result.m[8] = 0;
  1873. result.m[9] = 0;
  1874. result.m[11] = 0;
  1875. result.m[12] = 0;
  1876. result.m[13] = 0;
  1877. result.m[14] = 0;
  1878. };
  1879. Matrix.RotationAxis = function (axis, angle) {
  1880. var result = Matrix.Zero();
  1881. Matrix.RotationAxisToRef(axis, angle, result);
  1882. return result;
  1883. };
  1884. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1885. var s = Math.sin(-angle);
  1886. var c = Math.cos(-angle);
  1887. var c1 = 1 - c;
  1888. axis.normalize();
  1889. result.m[0] = (axis.x * axis.x) * c1 + c;
  1890. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1891. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1892. result.m[3] = 0.0;
  1893. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1894. result.m[5] = (axis.y * axis.y) * c1 + c;
  1895. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1896. result.m[7] = 0.0;
  1897. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1898. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1899. result.m[10] = (axis.z * axis.z) * c1 + c;
  1900. result.m[11] = 0.0;
  1901. result.m[15] = 1.0;
  1902. };
  1903. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1904. var result = new Matrix();
  1905. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1906. return result;
  1907. };
  1908. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1909. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1910. this._tempQuaternion.toRotationMatrix(result);
  1911. };
  1912. Matrix.Scaling = function (x, y, z) {
  1913. var result = Matrix.Zero();
  1914. Matrix.ScalingToRef(x, y, z, result);
  1915. return result;
  1916. };
  1917. Matrix.ScalingToRef = function (x, y, z, result) {
  1918. result.m[0] = x;
  1919. result.m[1] = 0;
  1920. result.m[2] = 0;
  1921. result.m[3] = 0;
  1922. result.m[4] = 0;
  1923. result.m[5] = y;
  1924. result.m[6] = 0;
  1925. result.m[7] = 0;
  1926. result.m[8] = 0;
  1927. result.m[9] = 0;
  1928. result.m[10] = z;
  1929. result.m[11] = 0;
  1930. result.m[12] = 0;
  1931. result.m[13] = 0;
  1932. result.m[14] = 0;
  1933. result.m[15] = 1.0;
  1934. };
  1935. Matrix.Translation = function (x, y, z) {
  1936. var result = Matrix.Identity();
  1937. Matrix.TranslationToRef(x, y, z, result);
  1938. return result;
  1939. };
  1940. Matrix.TranslationToRef = function (x, y, z, result) {
  1941. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1942. };
  1943. Matrix.Lerp = function (startValue, endValue, gradient) {
  1944. var startScale = new Vector3(0, 0, 0);
  1945. var startRotation = new Quaternion();
  1946. var startTranslation = new Vector3(0, 0, 0);
  1947. startValue.decompose(startScale, startRotation, startTranslation);
  1948. var endScale = new Vector3(0, 0, 0);
  1949. var endRotation = new Quaternion();
  1950. var endTranslation = new Vector3(0, 0, 0);
  1951. endValue.decompose(endScale, endRotation, endTranslation);
  1952. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1953. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1954. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1955. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1956. };
  1957. Matrix.LookAtLH = function (eye, target, up) {
  1958. var result = Matrix.Zero();
  1959. Matrix.LookAtLHToRef(eye, target, up, result);
  1960. return result;
  1961. };
  1962. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1963. // Z axis
  1964. target.subtractToRef(eye, this._zAxis);
  1965. this._zAxis.normalize();
  1966. // X axis
  1967. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1968. if (this._xAxis.lengthSquared() === 0) {
  1969. this._xAxis.x = 1.0;
  1970. }
  1971. else {
  1972. this._xAxis.normalize();
  1973. }
  1974. // Y axis
  1975. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1976. this._yAxis.normalize();
  1977. // Eye angles
  1978. var ex = -Vector3.Dot(this._xAxis, eye);
  1979. var ey = -Vector3.Dot(this._yAxis, eye);
  1980. var ez = -Vector3.Dot(this._zAxis, eye);
  1981. 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);
  1982. };
  1983. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1984. var matrix = Matrix.Zero();
  1985. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1986. return matrix;
  1987. };
  1988. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1989. var hw = 2.0 / width;
  1990. var hh = 2.0 / height;
  1991. var id = 1.0 / (zfar - znear);
  1992. var nid = znear / (znear - zfar);
  1993. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1994. };
  1995. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1996. var matrix = Matrix.Zero();
  1997. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1998. return matrix;
  1999. };
  2000. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2001. result.m[0] = 2.0 / (right - left);
  2002. result.m[1] = result.m[2] = result.m[3] = 0;
  2003. result.m[5] = 2.0 / (top - bottom);
  2004. result.m[4] = result.m[6] = result.m[7] = 0;
  2005. result.m[10] = -1.0 / (znear - zfar);
  2006. result.m[8] = result.m[9] = result.m[11] = 0;
  2007. result.m[12] = (left + right) / (left - right);
  2008. result.m[13] = (top + bottom) / (bottom - top);
  2009. result.m[14] = znear / (znear - zfar);
  2010. result.m[15] = 1.0;
  2011. };
  2012. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2013. var matrix = Matrix.Zero();
  2014. matrix.m[0] = (2.0 * znear) / width;
  2015. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2016. matrix.m[5] = (2.0 * znear) / height;
  2017. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2018. matrix.m[10] = -zfar / (znear - zfar);
  2019. matrix.m[8] = matrix.m[9] = 0.0;
  2020. matrix.m[11] = 1.0;
  2021. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2022. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2023. return matrix;
  2024. };
  2025. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2026. var matrix = Matrix.Zero();
  2027. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2028. return matrix;
  2029. };
  2030. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2031. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2032. var tan = 1.0 / (Math.tan(fov * 0.5));
  2033. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2034. if (v_fixed) {
  2035. result.m[0] = tan / aspect;
  2036. }
  2037. else {
  2038. result.m[0] = tan;
  2039. }
  2040. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2041. if (v_fixed) {
  2042. result.m[5] = tan;
  2043. }
  2044. else {
  2045. result.m[5] = tan * aspect;
  2046. }
  2047. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2048. result.m[8] = result.m[9] = 0.0;
  2049. result.m[10] = -zfar / (znear - zfar);
  2050. result.m[11] = 1.0;
  2051. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2052. result.m[14] = (znear * zfar) / (znear - zfar);
  2053. };
  2054. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2055. var cw = viewport.width;
  2056. var ch = viewport.height;
  2057. var cx = viewport.x;
  2058. var cy = viewport.y;
  2059. 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);
  2060. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2061. };
  2062. Matrix.GetAsMatrix2x2 = function (matrix) {
  2063. return new Float32Array([
  2064. matrix.m[0], matrix.m[1],
  2065. matrix.m[4], matrix.m[5]
  2066. ]);
  2067. };
  2068. Matrix.GetAsMatrix3x3 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1], matrix.m[2],
  2071. matrix.m[4], matrix.m[5], matrix.m[6],
  2072. matrix.m[8], matrix.m[9], matrix.m[10]
  2073. ]);
  2074. };
  2075. Matrix.Transpose = function (matrix) {
  2076. var result = new Matrix();
  2077. result.m[0] = matrix.m[0];
  2078. result.m[1] = matrix.m[4];
  2079. result.m[2] = matrix.m[8];
  2080. result.m[3] = matrix.m[12];
  2081. result.m[4] = matrix.m[1];
  2082. result.m[5] = matrix.m[5];
  2083. result.m[6] = matrix.m[9];
  2084. result.m[7] = matrix.m[13];
  2085. result.m[8] = matrix.m[2];
  2086. result.m[9] = matrix.m[6];
  2087. result.m[10] = matrix.m[10];
  2088. result.m[11] = matrix.m[14];
  2089. result.m[12] = matrix.m[3];
  2090. result.m[13] = matrix.m[7];
  2091. result.m[14] = matrix.m[11];
  2092. result.m[15] = matrix.m[15];
  2093. return result;
  2094. };
  2095. Matrix.Reflection = function (plane) {
  2096. var matrix = new Matrix();
  2097. Matrix.ReflectionToRef(plane, matrix);
  2098. return matrix;
  2099. };
  2100. Matrix.ReflectionToRef = function (plane, result) {
  2101. plane.normalize();
  2102. var x = plane.normal.x;
  2103. var y = plane.normal.y;
  2104. var z = plane.normal.z;
  2105. var temp = -2 * x;
  2106. var temp2 = -2 * y;
  2107. var temp3 = -2 * z;
  2108. result.m[0] = (temp * x) + 1;
  2109. result.m[1] = temp2 * x;
  2110. result.m[2] = temp3 * x;
  2111. result.m[3] = 0.0;
  2112. result.m[4] = temp * y;
  2113. result.m[5] = (temp2 * y) + 1;
  2114. result.m[6] = temp3 * y;
  2115. result.m[7] = 0.0;
  2116. result.m[8] = temp * z;
  2117. result.m[9] = temp2 * z;
  2118. result.m[10] = (temp3 * z) + 1;
  2119. result.m[11] = 0.0;
  2120. result.m[12] = temp * plane.d;
  2121. result.m[13] = temp2 * plane.d;
  2122. result.m[14] = temp3 * plane.d;
  2123. result.m[15] = 1.0;
  2124. };
  2125. Matrix._tempQuaternion = new Quaternion();
  2126. Matrix._xAxis = Vector3.Zero();
  2127. Matrix._yAxis = Vector3.Zero();
  2128. Matrix._zAxis = Vector3.Zero();
  2129. return Matrix;
  2130. })();
  2131. BABYLON.Matrix = Matrix;
  2132. var Plane = (function () {
  2133. function Plane(a, b, c, d) {
  2134. this.normal = new Vector3(a, b, c);
  2135. this.d = d;
  2136. }
  2137. Plane.prototype.asArray = function () {
  2138. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2139. };
  2140. // Methods
  2141. Plane.prototype.clone = function () {
  2142. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2143. };
  2144. Plane.prototype.normalize = function () {
  2145. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2146. var magnitude = 0;
  2147. if (norm !== 0) {
  2148. magnitude = 1.0 / norm;
  2149. }
  2150. this.normal.x *= magnitude;
  2151. this.normal.y *= magnitude;
  2152. this.normal.z *= magnitude;
  2153. this.d *= magnitude;
  2154. return this;
  2155. };
  2156. Plane.prototype.transform = function (transformation) {
  2157. var transposedMatrix = Matrix.Transpose(transformation);
  2158. var x = this.normal.x;
  2159. var y = this.normal.y;
  2160. var z = this.normal.z;
  2161. var d = this.d;
  2162. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2163. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2164. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2165. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2166. return new Plane(normalX, normalY, normalZ, finalD);
  2167. };
  2168. Plane.prototype.dotCoordinate = function (point) {
  2169. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2170. };
  2171. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2172. var x1 = point2.x - point1.x;
  2173. var y1 = point2.y - point1.y;
  2174. var z1 = point2.z - point1.z;
  2175. var x2 = point3.x - point1.x;
  2176. var y2 = point3.y - point1.y;
  2177. var z2 = point3.z - point1.z;
  2178. var yz = (y1 * z2) - (z1 * y2);
  2179. var xz = (z1 * x2) - (x1 * z2);
  2180. var xy = (x1 * y2) - (y1 * x2);
  2181. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2182. var invPyth;
  2183. if (pyth !== 0) {
  2184. invPyth = 1.0 / pyth;
  2185. }
  2186. else {
  2187. invPyth = 0;
  2188. }
  2189. this.normal.x = yz * invPyth;
  2190. this.normal.y = xz * invPyth;
  2191. this.normal.z = xy * invPyth;
  2192. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2193. return this;
  2194. };
  2195. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2196. var dot = Vector3.Dot(this.normal, direction);
  2197. return (dot <= epsilon);
  2198. };
  2199. Plane.prototype.signedDistanceTo = function (point) {
  2200. return Vector3.Dot(point, this.normal) + this.d;
  2201. };
  2202. // Statics
  2203. Plane.FromArray = function (array) {
  2204. return new Plane(array[0], array[1], array[2], array[3]);
  2205. };
  2206. Plane.FromPoints = function (point1, point2, point3) {
  2207. var result = new Plane(0, 0, 0, 0);
  2208. result.copyFromPoints(point1, point2, point3);
  2209. return result;
  2210. };
  2211. Plane.FromPositionAndNormal = function (origin, normal) {
  2212. var result = new Plane(0, 0, 0, 0);
  2213. normal.normalize();
  2214. result.normal = normal;
  2215. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2216. return result;
  2217. };
  2218. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2219. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2220. return Vector3.Dot(point, normal) + d;
  2221. };
  2222. return Plane;
  2223. })();
  2224. BABYLON.Plane = Plane;
  2225. var Viewport = (function () {
  2226. function Viewport(x, y, width, height) {
  2227. this.x = x;
  2228. this.y = y;
  2229. this.width = width;
  2230. this.height = height;
  2231. }
  2232. Viewport.prototype.toGlobal = function (engine) {
  2233. var width = engine.getRenderWidth();
  2234. var height = engine.getRenderHeight();
  2235. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2236. };
  2237. Viewport.prototype.toScreenGlobal = function (engine) {
  2238. var width = engine.getRenderWidth(true);
  2239. var height = engine.getRenderHeight(true);
  2240. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2241. };
  2242. return Viewport;
  2243. })();
  2244. BABYLON.Viewport = Viewport;
  2245. var Frustum = (function () {
  2246. function Frustum() {
  2247. }
  2248. Frustum.GetPlanes = function (transform) {
  2249. var frustumPlanes = [];
  2250. for (var index = 0; index < 6; index++) {
  2251. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2252. }
  2253. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2254. return frustumPlanes;
  2255. };
  2256. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2257. // Near
  2258. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2259. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2260. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2261. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2262. frustumPlanes[0].normalize();
  2263. // Far
  2264. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2265. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2266. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2267. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2268. frustumPlanes[1].normalize();
  2269. // Left
  2270. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2271. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2272. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2273. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2274. frustumPlanes[2].normalize();
  2275. // Right
  2276. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2277. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2278. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2279. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2280. frustumPlanes[3].normalize();
  2281. // Top
  2282. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2283. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2284. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2285. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2286. frustumPlanes[4].normalize();
  2287. // Bottom
  2288. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2289. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2290. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2291. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2292. frustumPlanes[5].normalize();
  2293. };
  2294. return Frustum;
  2295. })();
  2296. BABYLON.Frustum = Frustum;
  2297. var Ray = (function () {
  2298. function Ray(origin, direction, length) {
  2299. if (length === void 0) { length = Number.MAX_VALUE; }
  2300. this.origin = origin;
  2301. this.direction = direction;
  2302. this.length = length;
  2303. }
  2304. // Methods
  2305. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2306. var d = 0.0;
  2307. var maxValue = Number.MAX_VALUE;
  2308. var inv;
  2309. var min;
  2310. var max;
  2311. var temp;
  2312. if (Math.abs(this.direction.x) < 0.0000001) {
  2313. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2314. return false;
  2315. }
  2316. }
  2317. else {
  2318. inv = 1.0 / this.direction.x;
  2319. min = (minimum.x - this.origin.x) * inv;
  2320. max = (maximum.x - this.origin.x) * inv;
  2321. if (max === -Infinity) {
  2322. max = Infinity;
  2323. }
  2324. if (min > max) {
  2325. temp = min;
  2326. min = max;
  2327. max = temp;
  2328. }
  2329. d = Math.max(min, d);
  2330. maxValue = Math.min(max, maxValue);
  2331. if (d > maxValue) {
  2332. return false;
  2333. }
  2334. }
  2335. if (Math.abs(this.direction.y) < 0.0000001) {
  2336. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2337. return false;
  2338. }
  2339. }
  2340. else {
  2341. inv = 1.0 / this.direction.y;
  2342. min = (minimum.y - this.origin.y) * inv;
  2343. max = (maximum.y - this.origin.y) * inv;
  2344. if (max === -Infinity) {
  2345. max = Infinity;
  2346. }
  2347. if (min > max) {
  2348. temp = min;
  2349. min = max;
  2350. max = temp;
  2351. }
  2352. d = Math.max(min, d);
  2353. maxValue = Math.min(max, maxValue);
  2354. if (d > maxValue) {
  2355. return false;
  2356. }
  2357. }
  2358. if (Math.abs(this.direction.z) < 0.0000001) {
  2359. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2360. return false;
  2361. }
  2362. }
  2363. else {
  2364. inv = 1.0 / this.direction.z;
  2365. min = (minimum.z - this.origin.z) * inv;
  2366. max = (maximum.z - this.origin.z) * inv;
  2367. if (max === -Infinity) {
  2368. max = Infinity;
  2369. }
  2370. if (min > max) {
  2371. temp = min;
  2372. min = max;
  2373. max = temp;
  2374. }
  2375. d = Math.max(min, d);
  2376. maxValue = Math.min(max, maxValue);
  2377. if (d > maxValue) {
  2378. return false;
  2379. }
  2380. }
  2381. return true;
  2382. };
  2383. Ray.prototype.intersectsBox = function (box) {
  2384. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2385. };
  2386. Ray.prototype.intersectsSphere = function (sphere) {
  2387. var x = sphere.center.x - this.origin.x;
  2388. var y = sphere.center.y - this.origin.y;
  2389. var z = sphere.center.z - this.origin.z;
  2390. var pyth = (x * x) + (y * y) + (z * z);
  2391. var rr = sphere.radius * sphere.radius;
  2392. if (pyth <= rr) {
  2393. return true;
  2394. }
  2395. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2396. if (dot < 0.0) {
  2397. return false;
  2398. }
  2399. var temp = pyth - (dot * dot);
  2400. return temp <= rr;
  2401. };
  2402. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2403. if (!this._edge1) {
  2404. this._edge1 = Vector3.Zero();
  2405. this._edge2 = Vector3.Zero();
  2406. this._pvec = Vector3.Zero();
  2407. this._tvec = Vector3.Zero();
  2408. this._qvec = Vector3.Zero();
  2409. }
  2410. vertex1.subtractToRef(vertex0, this._edge1);
  2411. vertex2.subtractToRef(vertex0, this._edge2);
  2412. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2413. var det = Vector3.Dot(this._edge1, this._pvec);
  2414. if (det === 0) {
  2415. return null;
  2416. }
  2417. var invdet = 1 / det;
  2418. this.origin.subtractToRef(vertex0, this._tvec);
  2419. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2420. if (bu < 0 || bu > 1.0) {
  2421. return null;
  2422. }
  2423. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2424. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2425. if (bv < 0 || bu + bv > 1.0) {
  2426. return null;
  2427. }
  2428. //check if the distance is longer than the predefined length.
  2429. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2430. if (distance > this.length) {
  2431. return null;
  2432. }
  2433. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2434. };
  2435. // Statics
  2436. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2437. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2438. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2439. var direction = end.subtract(start);
  2440. direction.normalize();
  2441. return new Ray(start, direction);
  2442. };
  2443. /**
  2444. * 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
  2445. * transformed to the given world matrix.
  2446. * @param origin The origin point
  2447. * @param end The end point
  2448. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2449. */
  2450. Ray.CreateNewFromTo = function (origin, end, world) {
  2451. if (world === void 0) { world = Matrix.Identity(); }
  2452. var direction = end.subtract(origin);
  2453. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2454. direction.normalize();
  2455. return Ray.Transform(new Ray(origin, direction, length), world);
  2456. };
  2457. Ray.Transform = function (ray, matrix) {
  2458. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2459. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2460. return new Ray(newOrigin, newDirection, ray.length);
  2461. };
  2462. return Ray;
  2463. })();
  2464. BABYLON.Ray = Ray;
  2465. (function (Space) {
  2466. Space[Space["LOCAL"] = 0] = "LOCAL";
  2467. Space[Space["WORLD"] = 1] = "WORLD";
  2468. })(BABYLON.Space || (BABYLON.Space = {}));
  2469. var Space = BABYLON.Space;
  2470. var Axis = (function () {
  2471. function Axis() {
  2472. }
  2473. Axis.X = new Vector3(1, 0, 0);
  2474. Axis.Y = new Vector3(0, 1, 0);
  2475. Axis.Z = new Vector3(0, 0, 1);
  2476. return Axis;
  2477. })();
  2478. BABYLON.Axis = Axis;
  2479. ;
  2480. var BezierCurve = (function () {
  2481. function BezierCurve() {
  2482. }
  2483. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2484. // Extract X (which is equal to time here)
  2485. var f0 = 1 - 3 * x2 + 3 * x1;
  2486. var f1 = 3 * x2 - 6 * x1;
  2487. var f2 = 3 * x1;
  2488. var refinedT = t;
  2489. for (var i = 0; i < 5; i++) {
  2490. var refinedT2 = refinedT * refinedT;
  2491. var refinedT3 = refinedT2 * refinedT;
  2492. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2493. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2494. refinedT -= (x - t) * slope;
  2495. refinedT = Math.min(1, Math.max(0, refinedT));
  2496. }
  2497. // Resolve cubic bezier for the given x
  2498. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2499. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2500. Math.pow(refinedT, 3);
  2501. };
  2502. return BezierCurve;
  2503. })();
  2504. BABYLON.BezierCurve = BezierCurve;
  2505. (function (Orientation) {
  2506. Orientation[Orientation["CW"] = 0] = "CW";
  2507. Orientation[Orientation["CCW"] = 1] = "CCW";
  2508. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2509. var Orientation = BABYLON.Orientation;
  2510. var Angle = (function () {
  2511. function Angle(radians) {
  2512. var _this = this;
  2513. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2514. this.radians = function () { return _this._radians; };
  2515. this._radians = radians;
  2516. if (this._radians < 0)
  2517. this._radians += (2 * Math.PI);
  2518. }
  2519. Angle.BetweenTwoPoints = function (a, b) {
  2520. var delta = b.subtract(a);
  2521. var theta = Math.atan2(delta.y, delta.x);
  2522. return new Angle(theta);
  2523. };
  2524. Angle.FromRadians = function (radians) {
  2525. return new Angle(radians);
  2526. };
  2527. Angle.FromDegrees = function (degrees) {
  2528. return new Angle(degrees * Math.PI / 180);
  2529. };
  2530. return Angle;
  2531. })();
  2532. BABYLON.Angle = Angle;
  2533. var Arc2 = (function () {
  2534. function Arc2(startPoint, midPoint, endPoint) {
  2535. this.startPoint = startPoint;
  2536. this.midPoint = midPoint;
  2537. this.endPoint = endPoint;
  2538. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2539. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2540. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2541. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2542. 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);
  2543. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2544. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2545. var a1 = this.startAngle.degrees();
  2546. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2547. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2548. // angles correction
  2549. if (a2 - a1 > +180.0)
  2550. a2 -= 360.0;
  2551. if (a2 - a1 < -180.0)
  2552. a2 += 360.0;
  2553. if (a3 - a2 > +180.0)
  2554. a3 -= 360.0;
  2555. if (a3 - a2 < -180.0)
  2556. a3 += 360.0;
  2557. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2558. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2559. }
  2560. return Arc2;
  2561. })();
  2562. BABYLON.Arc2 = Arc2;
  2563. var PathCursor = (function () {
  2564. function PathCursor(path) {
  2565. this.path = path;
  2566. this._onchange = new Array();
  2567. this.value = 0;
  2568. this.animations = new Array();
  2569. }
  2570. PathCursor.prototype.getPoint = function () {
  2571. var point = this.path.getPointAtLengthPosition(this.value);
  2572. return new Vector3(point.x, 0, point.y);
  2573. };
  2574. PathCursor.prototype.moveAhead = function (step) {
  2575. if (step === void 0) { step = 0.002; }
  2576. this.move(step);
  2577. return this;
  2578. };
  2579. PathCursor.prototype.moveBack = function (step) {
  2580. if (step === void 0) { step = 0.002; }
  2581. this.move(-step);
  2582. return this;
  2583. };
  2584. PathCursor.prototype.move = function (step) {
  2585. if (Math.abs(step) > 1) {
  2586. throw "step size should be less than 1.";
  2587. }
  2588. this.value += step;
  2589. this.ensureLimits();
  2590. this.raiseOnChange();
  2591. return this;
  2592. };
  2593. PathCursor.prototype.ensureLimits = function () {
  2594. while (this.value > 1) {
  2595. this.value -= 1;
  2596. }
  2597. while (this.value < 0) {
  2598. this.value += 1;
  2599. }
  2600. return this;
  2601. };
  2602. // used by animation engine
  2603. PathCursor.prototype.markAsDirty = function (propertyName) {
  2604. this.ensureLimits();
  2605. this.raiseOnChange();
  2606. return this;
  2607. };
  2608. PathCursor.prototype.raiseOnChange = function () {
  2609. var _this = this;
  2610. this._onchange.forEach(function (f) { return f(_this); });
  2611. return this;
  2612. };
  2613. PathCursor.prototype.onchange = function (f) {
  2614. this._onchange.push(f);
  2615. return this;
  2616. };
  2617. return PathCursor;
  2618. })();
  2619. BABYLON.PathCursor = PathCursor;
  2620. var Path2 = (function () {
  2621. function Path2(x, y) {
  2622. this._points = new Array();
  2623. this._length = 0;
  2624. this.closed = false;
  2625. this._points.push(new Vector2(x, y));
  2626. }
  2627. Path2.prototype.addLineTo = function (x, y) {
  2628. if (closed) {
  2629. BABYLON.Tools.Error("cannot add lines to closed paths");
  2630. return this;
  2631. }
  2632. var newPoint = new Vector2(x, y);
  2633. var previousPoint = this._points[this._points.length - 1];
  2634. this._points.push(newPoint);
  2635. this._length += newPoint.subtract(previousPoint).length();
  2636. return this;
  2637. };
  2638. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2639. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2640. if (closed) {
  2641. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2642. return this;
  2643. }
  2644. var startPoint = this._points[this._points.length - 1];
  2645. var midPoint = new Vector2(midX, midY);
  2646. var endPoint = new Vector2(endX, endY);
  2647. var arc = new Arc2(startPoint, midPoint, endPoint);
  2648. var increment = arc.angle.radians() / numberOfSegments;
  2649. if (arc.orientation === Orientation.CW)
  2650. increment *= -1;
  2651. var currentAngle = arc.startAngle.radians() + increment;
  2652. for (var i = 0; i < numberOfSegments; i++) {
  2653. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2654. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2655. this.addLineTo(x, y);
  2656. currentAngle += increment;
  2657. }
  2658. return this;
  2659. };
  2660. Path2.prototype.close = function () {
  2661. this.closed = true;
  2662. return this;
  2663. };
  2664. Path2.prototype.length = function () {
  2665. var result = this._length;
  2666. if (!this.closed) {
  2667. var lastPoint = this._points[this._points.length - 1];
  2668. var firstPoint = this._points[0];
  2669. result += (firstPoint.subtract(lastPoint).length());
  2670. }
  2671. return result;
  2672. };
  2673. Path2.prototype.getPoints = function () {
  2674. return this._points;
  2675. };
  2676. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2677. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2678. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2679. return Vector2.Zero();
  2680. }
  2681. var lengthPosition = normalizedLengthPosition * this.length();
  2682. var previousOffset = 0;
  2683. for (var i = 0; i < this._points.length; i++) {
  2684. var j = (i + 1) % this._points.length;
  2685. var a = this._points[i];
  2686. var b = this._points[j];
  2687. var bToA = b.subtract(a);
  2688. var nextOffset = (bToA.length() + previousOffset);
  2689. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2690. var dir = bToA.normalize();
  2691. var localOffset = lengthPosition - previousOffset;
  2692. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2693. }
  2694. previousOffset = nextOffset;
  2695. }
  2696. BABYLON.Tools.Error("internal error");
  2697. return Vector2.Zero();
  2698. };
  2699. Path2.StartingAt = function (x, y) {
  2700. return new Path2(x, y);
  2701. };
  2702. return Path2;
  2703. })();
  2704. BABYLON.Path2 = Path2;
  2705. var Path3D = (function () {
  2706. /**
  2707. * new Path3D(path, normal, raw)
  2708. * path : an array of Vector3, the curve axis of the Path3D
  2709. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2710. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2711. */
  2712. function Path3D(path, firstNormal, raw) {
  2713. this.path = path;
  2714. this._curve = new Array();
  2715. this._distances = new Array();
  2716. this._tangents = new Array();
  2717. this._normals = new Array();
  2718. this._binormals = new Array();
  2719. for (var p = 0; p < path.length; p++) {
  2720. this._curve[p] = path[p].clone(); // hard copy
  2721. }
  2722. this._raw = raw || false;
  2723. this._compute(firstNormal);
  2724. }
  2725. Path3D.prototype.getCurve = function () {
  2726. return this._curve;
  2727. };
  2728. Path3D.prototype.getTangents = function () {
  2729. return this._tangents;
  2730. };
  2731. Path3D.prototype.getNormals = function () {
  2732. return this._normals;
  2733. };
  2734. Path3D.prototype.getBinormals = function () {
  2735. return this._binormals;
  2736. };
  2737. Path3D.prototype.getDistances = function () {
  2738. return this._distances;
  2739. };
  2740. Path3D.prototype.update = function (path, firstNormal) {
  2741. for (var p = 0; p < path.length; p++) {
  2742. this._curve[p].x = path[p].x;
  2743. this._curve[p].y = path[p].y;
  2744. this._curve[p].z = path[p].z;
  2745. }
  2746. this._compute(firstNormal);
  2747. return this;
  2748. };
  2749. // private function compute() : computes tangents, normals and binormals
  2750. Path3D.prototype._compute = function (firstNormal) {
  2751. var l = this._curve.length;
  2752. // first and last tangents
  2753. this._tangents[0] = this._getFirstNonNullVector(0);
  2754. if (!this._raw) {
  2755. this._tangents[0].normalize();
  2756. }
  2757. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2758. if (!this._raw) {
  2759. this._tangents[l - 1].normalize();
  2760. }
  2761. // normals and binormals at first point : arbitrary vector with _normalVector()
  2762. var tg0 = this._tangents[0];
  2763. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2764. this._normals[0] = pp0;
  2765. if (!this._raw) {
  2766. this._normals[0].normalize();
  2767. }
  2768. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2769. if (!this._raw) {
  2770. this._binormals[0].normalize();
  2771. }
  2772. this._distances[0] = 0;
  2773. // normals and binormals : next points
  2774. var prev; // previous vector (segment)
  2775. var cur; // current vector (segment)
  2776. var curTang; // current tangent
  2777. // previous normal
  2778. var prevBinor; // previous binormal
  2779. for (var i = 1; i < l; i++) {
  2780. // tangents
  2781. prev = this._getLastNonNullVector(i);
  2782. if (i < l - 1) {
  2783. cur = this._getFirstNonNullVector(i);
  2784. this._tangents[i] = prev.add(cur);
  2785. this._tangents[i].normalize();
  2786. }
  2787. this._distances[i] = this._distances[i - 1] + prev.length();
  2788. // normals and binormals
  2789. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2790. curTang = this._tangents[i];
  2791. prevBinor = this._binormals[i - 1];
  2792. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2793. if (!this._raw) {
  2794. this._normals[i].normalize();
  2795. }
  2796. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2797. if (!this._raw) {
  2798. this._binormals[i].normalize();
  2799. }
  2800. }
  2801. };
  2802. // private function getFirstNonNullVector(index)
  2803. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2804. Path3D.prototype._getFirstNonNullVector = function (index) {
  2805. var i = 1;
  2806. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2807. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2808. i++;
  2809. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2810. }
  2811. return nNVector;
  2812. };
  2813. // private function getLastNonNullVector(index)
  2814. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2815. Path3D.prototype._getLastNonNullVector = function (index) {
  2816. var i = 1;
  2817. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2818. while (nLVector.length() === 0 && index > i + 1) {
  2819. i++;
  2820. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2821. }
  2822. return nLVector;
  2823. };
  2824. // private function normalVector(v0, vt, va) :
  2825. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2826. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2827. Path3D.prototype._normalVector = function (v0, vt, va) {
  2828. var normal0;
  2829. if (va === undefined || va === null) {
  2830. var point;
  2831. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2832. point = new Vector3(0, -1, 0);
  2833. }
  2834. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2835. point = new Vector3(1, 0, 0);
  2836. }
  2837. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, 0, 1);
  2839. }
  2840. normal0 = Vector3.Cross(vt, point);
  2841. }
  2842. else {
  2843. normal0 = Vector3.Cross(vt, va);
  2844. Vector3.CrossToRef(normal0, vt, normal0);
  2845. }
  2846. normal0.normalize();
  2847. return normal0;
  2848. };
  2849. return Path3D;
  2850. })();
  2851. BABYLON.Path3D = Path3D;
  2852. var Curve3 = (function () {
  2853. function Curve3(points) {
  2854. this._length = 0;
  2855. this._points = points;
  2856. this._length = this._computeLength(points);
  2857. }
  2858. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2859. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2860. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2861. var bez = new Array();
  2862. var equation = function (t, val0, val1, val2) {
  2863. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2864. return res;
  2865. };
  2866. for (var i = 0; i <= nbPoints; i++) {
  2867. 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)));
  2868. }
  2869. return new Curve3(bez);
  2870. };
  2871. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2872. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2873. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2874. var bez = new Array();
  2875. var equation = function (t, val0, val1, val2, val3) {
  2876. 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;
  2877. return res;
  2878. };
  2879. for (var i = 0; i <= nbPoints; i++) {
  2880. 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)));
  2881. }
  2882. return new Curve3(bez);
  2883. };
  2884. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2885. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2886. var hermite = new Array();
  2887. var step = 1 / nbPoints;
  2888. for (var i = 0; i <= nbPoints; i++) {
  2889. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2890. }
  2891. return new Curve3(hermite);
  2892. };
  2893. Curve3.prototype.getPoints = function () {
  2894. return this._points;
  2895. };
  2896. Curve3.prototype.length = function () {
  2897. return this._length;
  2898. };
  2899. Curve3.prototype.continue = function (curve) {
  2900. var lastPoint = this._points[this._points.length - 1];
  2901. var continuedPoints = this._points.slice();
  2902. var curvePoints = curve.getPoints();
  2903. for (var i = 1; i < curvePoints.length; i++) {
  2904. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2905. }
  2906. var continuedCurve = new Curve3(continuedPoints);
  2907. return continuedCurve;
  2908. };
  2909. Curve3.prototype._computeLength = function (path) {
  2910. var l = 0;
  2911. for (var i = 1; i < path.length; i++) {
  2912. l += (path[i].subtract(path[i - 1])).length();
  2913. }
  2914. return l;
  2915. };
  2916. return Curve3;
  2917. })();
  2918. BABYLON.Curve3 = Curve3;
  2919. // Vertex formats
  2920. var PositionNormalVertex = (function () {
  2921. function PositionNormalVertex(position, normal) {
  2922. if (position === void 0) { position = Vector3.Zero(); }
  2923. if (normal === void 0) { normal = Vector3.Up(); }
  2924. this.position = position;
  2925. this.normal = normal;
  2926. }
  2927. PositionNormalVertex.prototype.clone = function () {
  2928. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2929. };
  2930. return PositionNormalVertex;
  2931. })();
  2932. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2933. var PositionNormalTextureVertex = (function () {
  2934. function PositionNormalTextureVertex(position, normal, uv) {
  2935. if (position === void 0) { position = Vector3.Zero(); }
  2936. if (normal === void 0) { normal = Vector3.Up(); }
  2937. if (uv === void 0) { uv = Vector2.Zero(); }
  2938. this.position = position;
  2939. this.normal = normal;
  2940. this.uv = uv;
  2941. }
  2942. PositionNormalTextureVertex.prototype.clone = function () {
  2943. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2944. };
  2945. return PositionNormalTextureVertex;
  2946. })();
  2947. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2948. // Temporary pre-allocated objects for engine internal use
  2949. // usage in any internal function :
  2950. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2951. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2952. var Tmp = (function () {
  2953. function Tmp() {
  2954. }
  2955. Tmp.Int = [0, 0, 0, 0, 0, 0]; // 6 temp integers at once should be enough
  2956. Tmp.Float = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; // 6 temp floats at once should be enough
  2957. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2958. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 3 temp Vector3 at once should be enough
  2959. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2960. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2961. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2962. Matrix.Zero(), Matrix.Zero(),
  2963. Matrix.Zero(), Matrix.Zero(),
  2964. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2965. return Tmp;
  2966. })();
  2967. BABYLON.Tmp = Tmp;
  2968. })(BABYLON || (BABYLON = {}));
  2969. var BABYLON;
  2970. (function (BABYLON) {
  2971. var Database = (function () {
  2972. function Database(urlToScene, callbackManifestChecked) {
  2973. // Handling various flavors of prefixed version of IndexedDB
  2974. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2975. this.callbackManifestChecked = callbackManifestChecked;
  2976. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2977. this.db = null;
  2978. this.enableSceneOffline = false;
  2979. this.enableTexturesOffline = false;
  2980. this.manifestVersionFound = 0;
  2981. this.mustUpdateRessources = false;
  2982. this.hasReachedQuota = false;
  2983. if (!Database.IDBStorageEnabled) {
  2984. this.callbackManifestChecked(true);
  2985. }
  2986. else {
  2987. this.checkManifestFile();
  2988. }
  2989. }
  2990. Database.prototype.checkManifestFile = function () {
  2991. var _this = this;
  2992. function noManifestFile() {
  2993. that.enableSceneOffline = false;
  2994. that.enableTexturesOffline = false;
  2995. that.callbackManifestChecked(false);
  2996. }
  2997. var that = this;
  2998. var manifestURL = this.currentSceneUrl + ".manifest";
  2999. var xhr = new XMLHttpRequest();
  3000. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3001. xhr.open("GET", manifestURLTimeStamped, true);
  3002. xhr.addEventListener("load", function () {
  3003. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3004. try {
  3005. var manifestFile = JSON.parse(xhr.response);
  3006. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3007. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3008. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3009. _this.manifestVersionFound = manifestFile.version;
  3010. }
  3011. if (_this.callbackManifestChecked) {
  3012. _this.callbackManifestChecked(true);
  3013. }
  3014. }
  3015. catch (ex) {
  3016. noManifestFile();
  3017. }
  3018. }
  3019. else {
  3020. noManifestFile();
  3021. }
  3022. }, false);
  3023. xhr.addEventListener("error", function (event) {
  3024. noManifestFile();
  3025. }, false);
  3026. try {
  3027. xhr.send();
  3028. }
  3029. catch (ex) {
  3030. BABYLON.Tools.Error("Error on XHR send request.");
  3031. that.callbackManifestChecked(false);
  3032. }
  3033. };
  3034. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3035. var _this = this;
  3036. function handleError() {
  3037. that.isSupported = false;
  3038. if (errorCallback)
  3039. errorCallback();
  3040. }
  3041. var that = this;
  3042. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3043. // Your browser doesn't support IndexedDB
  3044. this.isSupported = false;
  3045. if (errorCallback)
  3046. errorCallback();
  3047. }
  3048. else {
  3049. // If the DB hasn't been opened or created yet
  3050. if (!this.db) {
  3051. this.hasReachedQuota = false;
  3052. this.isSupported = true;
  3053. var request = this.idbFactory.open("babylonjs", 1);
  3054. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3055. request.onerror = function (event) {
  3056. handleError();
  3057. };
  3058. // executes when a version change transaction cannot complete due to other active transactions
  3059. request.onblocked = function (event) {
  3060. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3061. handleError();
  3062. };
  3063. // DB has been opened successfully
  3064. request.onsuccess = function (event) {
  3065. _this.db = request.result;
  3066. successCallback();
  3067. };
  3068. // Initialization of the DB. Creating Scenes & Textures stores
  3069. request.onupgradeneeded = function (event) {
  3070. _this.db = (event.target).result;
  3071. try {
  3072. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3073. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3074. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3075. }
  3076. catch (ex) {
  3077. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3078. handleError();
  3079. }
  3080. };
  3081. }
  3082. else {
  3083. if (successCallback)
  3084. successCallback();
  3085. }
  3086. }
  3087. };
  3088. Database.prototype.loadImageFromDB = function (url, image) {
  3089. var _this = this;
  3090. var completeURL = Database.ReturnFullUrlLocation(url);
  3091. var saveAndLoadImage = function () {
  3092. if (!_this.hasReachedQuota && _this.db !== null) {
  3093. // the texture is not yet in the DB, let's try to save it
  3094. _this._saveImageIntoDBAsync(completeURL, image);
  3095. }
  3096. else {
  3097. image.src = url;
  3098. }
  3099. };
  3100. if (!this.mustUpdateRessources) {
  3101. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3102. }
  3103. else {
  3104. saveAndLoadImage();
  3105. }
  3106. };
  3107. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3108. if (this.isSupported && this.db !== null) {
  3109. var texture;
  3110. var transaction = this.db.transaction(["textures"]);
  3111. transaction.onabort = function (event) {
  3112. image.src = url;
  3113. };
  3114. transaction.oncomplete = function (event) {
  3115. var blobTextureURL;
  3116. if (texture) {
  3117. var URL = window.URL || window.webkitURL;
  3118. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3119. image.onerror = function () {
  3120. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3121. image.src = url;
  3122. };
  3123. image.src = blobTextureURL;
  3124. }
  3125. else {
  3126. notInDBCallback();
  3127. }
  3128. };
  3129. var getRequest = transaction.objectStore("textures").get(url);
  3130. getRequest.onsuccess = function (event) {
  3131. texture = (event.target).result;
  3132. };
  3133. getRequest.onerror = function (event) {
  3134. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3135. image.src = url;
  3136. };
  3137. }
  3138. else {
  3139. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3140. image.src = url;
  3141. }
  3142. };
  3143. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3144. var _this = this;
  3145. if (this.isSupported) {
  3146. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3147. var generateBlobUrl = function () {
  3148. var blobTextureURL;
  3149. if (blob) {
  3150. var URL = window.URL || window.webkitURL;
  3151. try {
  3152. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3153. }
  3154. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3155. catch (ex) {
  3156. blobTextureURL = URL.createObjectURL(blob);
  3157. }
  3158. }
  3159. image.src = blobTextureURL;
  3160. };
  3161. if (Database.IsUASupportingBlobStorage) {
  3162. var xhr = new XMLHttpRequest(), blob;
  3163. xhr.open("GET", url, true);
  3164. xhr.responseType = "blob";
  3165. xhr.addEventListener("load", function () {
  3166. if (xhr.status === 200) {
  3167. // Blob as response (XHR2)
  3168. blob = xhr.response;
  3169. var transaction = _this.db.transaction(["textures"], "readwrite");
  3170. // the transaction could abort because of a QuotaExceededError error
  3171. transaction.onabort = function (event) {
  3172. try {
  3173. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3174. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3175. this.hasReachedQuota = true;
  3176. }
  3177. }
  3178. catch (ex) { }
  3179. generateBlobUrl();
  3180. };
  3181. transaction.oncomplete = function (event) {
  3182. generateBlobUrl();
  3183. };
  3184. var newTexture = { textureUrl: url, data: blob };
  3185. try {
  3186. // Put the blob into the dabase
  3187. var addRequest = transaction.objectStore("textures").put(newTexture);
  3188. addRequest.onsuccess = function (event) {
  3189. };
  3190. addRequest.onerror = function (event) {
  3191. generateBlobUrl();
  3192. };
  3193. }
  3194. catch (ex) {
  3195. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3196. if (ex.code === 25) {
  3197. Database.IsUASupportingBlobStorage = false;
  3198. }
  3199. image.src = url;
  3200. }
  3201. }
  3202. else {
  3203. image.src = url;
  3204. }
  3205. }, false);
  3206. xhr.addEventListener("error", function (event) {
  3207. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3208. image.src = url;
  3209. }, false);
  3210. xhr.send();
  3211. }
  3212. else {
  3213. image.src = url;
  3214. }
  3215. }
  3216. else {
  3217. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3218. image.src = url;
  3219. }
  3220. };
  3221. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3222. var _this = this;
  3223. var updateVersion = function (event) {
  3224. // the version is not yet in the DB or we need to update it
  3225. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3226. };
  3227. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3228. };
  3229. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3230. var _this = this;
  3231. if (this.isSupported) {
  3232. var version;
  3233. try {
  3234. var transaction = this.db.transaction(["versions"]);
  3235. transaction.oncomplete = function (event) {
  3236. if (version) {
  3237. // If the version in the JSON file is > than the version in DB
  3238. if (_this.manifestVersionFound > version.data) {
  3239. _this.mustUpdateRessources = true;
  3240. updateInDBCallback();
  3241. }
  3242. else {
  3243. callback(version.data);
  3244. }
  3245. }
  3246. else {
  3247. _this.mustUpdateRessources = true;
  3248. updateInDBCallback();
  3249. }
  3250. };
  3251. transaction.onabort = function (event) {
  3252. callback(-1);
  3253. };
  3254. var getRequest = transaction.objectStore("versions").get(url);
  3255. getRequest.onsuccess = function (event) {
  3256. version = (event.target).result;
  3257. };
  3258. getRequest.onerror = function (event) {
  3259. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3260. callback(-1);
  3261. };
  3262. }
  3263. catch (ex) {
  3264. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3265. callback(-1);
  3266. }
  3267. }
  3268. else {
  3269. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3270. callback(-1);
  3271. }
  3272. };
  3273. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3274. var _this = this;
  3275. if (this.isSupported && !this.hasReachedQuota) {
  3276. try {
  3277. // Open a transaction to the database
  3278. var transaction = this.db.transaction(["versions"], "readwrite");
  3279. // the transaction could abort because of a QuotaExceededError error
  3280. transaction.onabort = function (event) {
  3281. try {
  3282. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3283. _this.hasReachedQuota = true;
  3284. }
  3285. }
  3286. catch (ex) { }
  3287. callback(-1);
  3288. };
  3289. transaction.oncomplete = function (event) {
  3290. callback(_this.manifestVersionFound);
  3291. };
  3292. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3293. // Put the scene into the database
  3294. var addRequest = transaction.objectStore("versions").put(newVersion);
  3295. addRequest.onsuccess = function (event) {
  3296. };
  3297. addRequest.onerror = function (event) {
  3298. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3299. };
  3300. }
  3301. catch (ex) {
  3302. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3303. callback(-1);
  3304. }
  3305. }
  3306. else {
  3307. callback(-1);
  3308. }
  3309. };
  3310. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3311. var _this = this;
  3312. var completeUrl = Database.ReturnFullUrlLocation(url);
  3313. var saveAndLoadFile = function (event) {
  3314. // the scene is not yet in the DB, let's try to save it
  3315. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3316. };
  3317. this._checkVersionFromDB(completeUrl, function (version) {
  3318. if (version !== -1) {
  3319. if (!_this.mustUpdateRessources) {
  3320. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3321. }
  3322. else {
  3323. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3324. }
  3325. }
  3326. else {
  3327. errorCallback();
  3328. }
  3329. });
  3330. };
  3331. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3332. if (this.isSupported) {
  3333. var targetStore;
  3334. if (url.indexOf(".babylon") !== -1) {
  3335. targetStore = "scenes";
  3336. }
  3337. else {
  3338. targetStore = "textures";
  3339. }
  3340. var file;
  3341. var transaction = this.db.transaction([targetStore]);
  3342. transaction.oncomplete = function (event) {
  3343. if (file) {
  3344. callback(file.data);
  3345. }
  3346. else {
  3347. notInDBCallback();
  3348. }
  3349. };
  3350. transaction.onabort = function (event) {
  3351. notInDBCallback();
  3352. };
  3353. var getRequest = transaction.objectStore(targetStore).get(url);
  3354. getRequest.onsuccess = function (event) {
  3355. file = (event.target).result;
  3356. };
  3357. getRequest.onerror = function (event) {
  3358. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3359. notInDBCallback();
  3360. };
  3361. }
  3362. else {
  3363. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3364. callback();
  3365. }
  3366. };
  3367. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3368. var _this = this;
  3369. if (this.isSupported) {
  3370. var targetStore;
  3371. if (url.indexOf(".babylon") !== -1) {
  3372. targetStore = "scenes";
  3373. }
  3374. else {
  3375. targetStore = "textures";
  3376. }
  3377. // Create XHR
  3378. var xhr = new XMLHttpRequest(), fileData;
  3379. xhr.open("GET", url, true);
  3380. if (useArrayBuffer) {
  3381. xhr.responseType = "arraybuffer";
  3382. }
  3383. xhr.onprogress = progressCallback;
  3384. xhr.addEventListener("load", function () {
  3385. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3386. // Blob as response (XHR2)
  3387. //fileData = xhr.responseText;
  3388. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3389. if (!_this.hasReachedQuota) {
  3390. // Open a transaction to the database
  3391. var transaction = _this.db.transaction([targetStore], "readwrite");
  3392. // the transaction could abort because of a QuotaExceededError error
  3393. transaction.onabort = function (event) {
  3394. try {
  3395. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3396. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3397. this.hasReachedQuota = true;
  3398. }
  3399. }
  3400. catch (ex) { }
  3401. callback(fileData);
  3402. };
  3403. transaction.oncomplete = function (event) {
  3404. callback(fileData);
  3405. };
  3406. var newFile;
  3407. if (targetStore === "scenes") {
  3408. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3409. }
  3410. else {
  3411. newFile = { textureUrl: url, data: fileData };
  3412. }
  3413. try {
  3414. // Put the scene into the database
  3415. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3416. addRequest.onsuccess = function (event) {
  3417. };
  3418. addRequest.onerror = function (event) {
  3419. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3420. };
  3421. }
  3422. catch (ex) {
  3423. callback(fileData);
  3424. }
  3425. }
  3426. else {
  3427. callback(fileData);
  3428. }
  3429. }
  3430. else {
  3431. callback();
  3432. }
  3433. }, false);
  3434. xhr.addEventListener("error", function (event) {
  3435. BABYLON.Tools.Error("error on XHR request.");
  3436. callback();
  3437. }, false);
  3438. xhr.send();
  3439. }
  3440. else {
  3441. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3442. callback();
  3443. }
  3444. };
  3445. Database.IsUASupportingBlobStorage = true;
  3446. Database.IDBStorageEnabled = true;
  3447. Database.parseURL = function (url) {
  3448. var a = document.createElement('a');
  3449. a.href = url;
  3450. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3451. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3452. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3453. return absLocation;
  3454. };
  3455. Database.ReturnFullUrlLocation = function (url) {
  3456. if (url.indexOf("http:/") === -1) {
  3457. return (Database.parseURL(window.location.href) + url);
  3458. }
  3459. else {
  3460. return url;
  3461. }
  3462. };
  3463. return Database;
  3464. })();
  3465. BABYLON.Database = Database;
  3466. })(BABYLON || (BABYLON = {}));
  3467. var BABYLON;
  3468. (function (BABYLON) {
  3469. var Internals;
  3470. (function (Internals) {
  3471. /*
  3472. * Based on jsTGALoader - Javascript loader for TGA file
  3473. * By Vincent Thibault
  3474. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3475. */
  3476. var TGATools = (function () {
  3477. function TGATools() {
  3478. }
  3479. TGATools.GetTGAHeader = function (data) {
  3480. var offset = 0;
  3481. var header = {
  3482. id_length: data[offset++],
  3483. colormap_type: data[offset++],
  3484. image_type: data[offset++],
  3485. colormap_index: data[offset++] | data[offset++] << 8,
  3486. colormap_length: data[offset++] | data[offset++] << 8,
  3487. colormap_size: data[offset++],
  3488. origin: [
  3489. data[offset++] | data[offset++] << 8,
  3490. data[offset++] | data[offset++] << 8
  3491. ],
  3492. width: data[offset++] | data[offset++] << 8,
  3493. height: data[offset++] | data[offset++] << 8,
  3494. pixel_size: data[offset++],
  3495. flags: data[offset++]
  3496. };
  3497. return header;
  3498. };
  3499. TGATools.UploadContent = function (gl, data) {
  3500. // Not enough data to contain header ?
  3501. if (data.length < 19) {
  3502. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3503. return;
  3504. }
  3505. // Read Header
  3506. var offset = 18;
  3507. var header = TGATools.GetTGAHeader(data);
  3508. // Assume it's a valid Targa file.
  3509. if (header.id_length + offset > data.length) {
  3510. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3511. return;
  3512. }
  3513. // Skip not needed data
  3514. offset += header.id_length;
  3515. var use_rle = false;
  3516. var use_pal = false;
  3517. var use_rgb = false;
  3518. var use_grey = false;
  3519. // Get some informations.
  3520. switch (header.image_type) {
  3521. case TGATools._TYPE_RLE_INDEXED:
  3522. use_rle = true;
  3523. case TGATools._TYPE_INDEXED:
  3524. use_pal = true;
  3525. break;
  3526. case TGATools._TYPE_RLE_RGB:
  3527. use_rle = true;
  3528. case TGATools._TYPE_RGB:
  3529. use_rgb = true;
  3530. break;
  3531. case TGATools._TYPE_RLE_GREY:
  3532. use_rle = true;
  3533. case TGATools._TYPE_GREY:
  3534. use_grey = true;
  3535. break;
  3536. }
  3537. var pixel_data;
  3538. var numAlphaBits = header.flags & 0xf;
  3539. var pixel_size = header.pixel_size >> 3;
  3540. var pixel_total = header.width * header.height * pixel_size;
  3541. // Read palettes
  3542. var palettes;
  3543. if (use_pal) {
  3544. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3545. }
  3546. // Read LRE
  3547. if (use_rle) {
  3548. pixel_data = new Uint8Array(pixel_total);
  3549. var c, count, i;
  3550. var localOffset = 0;
  3551. var pixels = new Uint8Array(pixel_size);
  3552. while (offset < pixel_total && localOffset < pixel_total) {
  3553. c = data[offset++];
  3554. count = (c & 0x7f) + 1;
  3555. // RLE pixels
  3556. if (c & 0x80) {
  3557. // Bind pixel tmp array
  3558. for (i = 0; i < pixel_size; ++i) {
  3559. pixels[i] = data[offset++];
  3560. }
  3561. // Copy pixel array
  3562. for (i = 0; i < count; ++i) {
  3563. pixel_data.set(pixels, localOffset + i * pixel_size);
  3564. }
  3565. localOffset += pixel_size * count;
  3566. }
  3567. else {
  3568. count *= pixel_size;
  3569. for (i = 0; i < count; ++i) {
  3570. pixel_data[localOffset + i] = data[offset++];
  3571. }
  3572. localOffset += count;
  3573. }
  3574. }
  3575. }
  3576. else {
  3577. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3578. }
  3579. // Load to texture
  3580. var x_start, y_start, x_step, y_step, y_end, x_end;
  3581. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3582. default:
  3583. case TGATools._ORIGIN_UL:
  3584. x_start = 0;
  3585. x_step = 1;
  3586. x_end = header.width;
  3587. y_start = 0;
  3588. y_step = 1;
  3589. y_end = header.height;
  3590. break;
  3591. case TGATools._ORIGIN_BL:
  3592. x_start = 0;
  3593. x_step = 1;
  3594. x_end = header.width;
  3595. y_start = header.height - 1;
  3596. y_step = -1;
  3597. y_end = -1;
  3598. break;
  3599. case TGATools._ORIGIN_UR:
  3600. x_start = header.width - 1;
  3601. x_step = -1;
  3602. x_end = -1;
  3603. y_start = 0;
  3604. y_step = 1;
  3605. y_end = header.height;
  3606. break;
  3607. case TGATools._ORIGIN_BR:
  3608. x_start = header.width - 1;
  3609. x_step = -1;
  3610. x_end = -1;
  3611. y_start = header.height - 1;
  3612. y_step = -1;
  3613. y_end = -1;
  3614. break;
  3615. }
  3616. // Load the specify method
  3617. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3618. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3619. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3620. };
  3621. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3622. var image = pixel_data, colormap = palettes;
  3623. var width = header.width, height = header.height;
  3624. var color, i = 0, x, y;
  3625. var imageData = new Uint8Array(width * height * 4);
  3626. for (y = y_start; y !== y_end; y += y_step) {
  3627. for (x = x_start; x !== x_end; x += x_step, i++) {
  3628. color = image[i];
  3629. imageData[(x + width * y) * 4 + 3] = 255;
  3630. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3631. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3632. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3633. }
  3634. }
  3635. return imageData;
  3636. };
  3637. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3638. var image = pixel_data;
  3639. var width = header.width, height = header.height;
  3640. var color, i = 0, x, y;
  3641. var imageData = new Uint8Array(width * height * 4);
  3642. for (y = y_start; y !== y_end; y += y_step) {
  3643. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3644. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3645. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3646. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3647. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3648. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3649. }
  3650. }
  3651. return imageData;
  3652. };
  3653. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3654. var image = pixel_data;
  3655. var width = header.width, height = header.height;
  3656. var i = 0, x, y;
  3657. var imageData = new Uint8Array(width * height * 4);
  3658. for (y = y_start; y !== y_end; y += y_step) {
  3659. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3660. imageData[(x + width * y) * 4 + 3] = 255;
  3661. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3662. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3663. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3664. }
  3665. }
  3666. return imageData;
  3667. };
  3668. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3669. var image = pixel_data;
  3670. var width = header.width, height = header.height;
  3671. var i = 0, x, y;
  3672. var imageData = new Uint8Array(width * height * 4);
  3673. for (y = y_start; y !== y_end; y += y_step) {
  3674. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3675. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3676. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3677. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3678. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3679. }
  3680. }
  3681. return imageData;
  3682. };
  3683. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3684. var image = pixel_data;
  3685. var width = header.width, height = header.height;
  3686. var color, i = 0, x, y;
  3687. var imageData = new Uint8Array(width * height * 4);
  3688. for (y = y_start; y !== y_end; y += y_step) {
  3689. for (x = x_start; x !== x_end; x += x_step, i++) {
  3690. color = image[i];
  3691. imageData[(x + width * y) * 4 + 0] = color;
  3692. imageData[(x + width * y) * 4 + 1] = color;
  3693. imageData[(x + width * y) * 4 + 2] = color;
  3694. imageData[(x + width * y) * 4 + 3] = 255;
  3695. }
  3696. }
  3697. return imageData;
  3698. };
  3699. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3700. var image = pixel_data;
  3701. var width = header.width, height = header.height;
  3702. var i = 0, x, y;
  3703. var imageData = new Uint8Array(width * height * 4);
  3704. for (y = y_start; y !== y_end; y += y_step) {
  3705. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3706. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3707. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3708. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3709. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3710. }
  3711. }
  3712. return imageData;
  3713. };
  3714. TGATools._TYPE_NO_DATA = 0;
  3715. TGATools._TYPE_INDEXED = 1;
  3716. TGATools._TYPE_RGB = 2;
  3717. TGATools._TYPE_GREY = 3;
  3718. TGATools._TYPE_RLE_INDEXED = 9;
  3719. TGATools._TYPE_RLE_RGB = 10;
  3720. TGATools._TYPE_RLE_GREY = 11;
  3721. TGATools._ORIGIN_MASK = 0x30;
  3722. TGATools._ORIGIN_SHIFT = 0x04;
  3723. TGATools._ORIGIN_BL = 0x00;
  3724. TGATools._ORIGIN_BR = 0x01;
  3725. TGATools._ORIGIN_UL = 0x02;
  3726. TGATools._ORIGIN_UR = 0x03;
  3727. return TGATools;
  3728. })();
  3729. Internals.TGATools = TGATools;
  3730. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3731. })(BABYLON || (BABYLON = {}));
  3732. var BABYLON;
  3733. (function (BABYLON) {
  3734. var SmartArray = (function () {
  3735. function SmartArray(capacity) {
  3736. this.length = 0;
  3737. this._duplicateId = 0;
  3738. this.data = new Array(capacity);
  3739. this._id = SmartArray._GlobalId++;
  3740. }
  3741. SmartArray.prototype.push = function (value) {
  3742. this.data[this.length++] = value;
  3743. if (this.length > this.data.length) {
  3744. this.data.length *= 2;
  3745. }
  3746. if (!value.__smartArrayFlags) {
  3747. value.__smartArrayFlags = {};
  3748. }
  3749. value.__smartArrayFlags[this._id] = this._duplicateId;
  3750. };
  3751. SmartArray.prototype.pushNoDuplicate = function (value) {
  3752. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3753. return;
  3754. }
  3755. this.push(value);
  3756. };
  3757. SmartArray.prototype.sort = function (compareFn) {
  3758. this.data.sort(compareFn);
  3759. };
  3760. SmartArray.prototype.reset = function () {
  3761. this.length = 0;
  3762. this._duplicateId++;
  3763. };
  3764. SmartArray.prototype.concat = function (array) {
  3765. if (array.length === 0) {
  3766. return;
  3767. }
  3768. if (this.length + array.length > this.data.length) {
  3769. this.data.length = (this.length + array.length) * 2;
  3770. }
  3771. for (var index = 0; index < array.length; index++) {
  3772. this.data[this.length++] = (array.data || array)[index];
  3773. }
  3774. };
  3775. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3776. if (array.length === 0) {
  3777. return;
  3778. }
  3779. if (this.length + array.length > this.data.length) {
  3780. this.data.length = (this.length + array.length) * 2;
  3781. }
  3782. for (var index = 0; index < array.length; index++) {
  3783. var item = (array.data || array)[index];
  3784. this.pushNoDuplicate(item);
  3785. }
  3786. };
  3787. SmartArray.prototype.indexOf = function (value) {
  3788. var position = this.data.indexOf(value);
  3789. if (position >= this.length) {
  3790. return -1;
  3791. }
  3792. return position;
  3793. };
  3794. // Statics
  3795. SmartArray._GlobalId = 0;
  3796. return SmartArray;
  3797. })();
  3798. BABYLON.SmartArray = SmartArray;
  3799. })(BABYLON || (BABYLON = {}));
  3800. var BABYLON;
  3801. (function (BABYLON) {
  3802. var SmartCollection = (function () {
  3803. function SmartCollection(capacity) {
  3804. if (capacity === void 0) { capacity = 10; }
  3805. this.count = 0;
  3806. this._initialCapacity = capacity;
  3807. this.items = {};
  3808. this._keys = new Array(this._initialCapacity);
  3809. }
  3810. SmartCollection.prototype.add = function (key, item) {
  3811. if (this.items[key] != undefined) {
  3812. return -1;
  3813. }
  3814. this.items[key] = item;
  3815. //literal keys are always strings, but we keep source type of key in _keys array
  3816. this._keys[this.count++] = key;
  3817. if (this.count > this._keys.length) {
  3818. this._keys.length *= 2;
  3819. }
  3820. return this.count;
  3821. };
  3822. SmartCollection.prototype.remove = function (key) {
  3823. if (this.items[key] == undefined) {
  3824. return -1;
  3825. }
  3826. return this.removeItemOfIndex(this.indexOf(key));
  3827. };
  3828. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3829. if (index < this.count && index > -1) {
  3830. delete this.items[this._keys[index]];
  3831. //here, shifting by hand is better optimised than .splice
  3832. while (index < this.count) {
  3833. this._keys[index] = this._keys[index + 1];
  3834. index++;
  3835. }
  3836. }
  3837. else {
  3838. return -1;
  3839. }
  3840. return --this.count;
  3841. };
  3842. SmartCollection.prototype.indexOf = function (key) {
  3843. for (var i = 0; i !== this.count; i++) {
  3844. if (this._keys[i] === key) {
  3845. return i;
  3846. }
  3847. }
  3848. return -1;
  3849. };
  3850. SmartCollection.prototype.item = function (key) {
  3851. return this.items[key];
  3852. };
  3853. SmartCollection.prototype.getAllKeys = function () {
  3854. if (this.count > 0) {
  3855. var keys = new Array(this.count);
  3856. for (var i = 0; i < this.count; i++) {
  3857. keys[i] = this._keys[i];
  3858. }
  3859. return keys;
  3860. }
  3861. else {
  3862. return undefined;
  3863. }
  3864. };
  3865. SmartCollection.prototype.getKeyByIndex = function (index) {
  3866. if (index < this.count && index > -1) {
  3867. return this._keys[index];
  3868. }
  3869. else {
  3870. return undefined;
  3871. }
  3872. };
  3873. SmartCollection.prototype.getItemByIndex = function (index) {
  3874. if (index < this.count && index > -1) {
  3875. return this.items[this._keys[index]];
  3876. }
  3877. else {
  3878. return undefined;
  3879. }
  3880. };
  3881. SmartCollection.prototype.empty = function () {
  3882. if (this.count > 0) {
  3883. this.count = 0;
  3884. this.items = {};
  3885. this._keys = new Array(this._initialCapacity);
  3886. }
  3887. };
  3888. SmartCollection.prototype.forEach = function (block) {
  3889. var key;
  3890. for (key in this.items) {
  3891. if (this.items.hasOwnProperty(key)) {
  3892. block(this.items[key]);
  3893. }
  3894. }
  3895. };
  3896. return SmartCollection;
  3897. })();
  3898. BABYLON.SmartCollection = SmartCollection;
  3899. })(BABYLON || (BABYLON = {}));
  3900. var BABYLON;
  3901. (function (BABYLON) {
  3902. // Screenshots
  3903. var screenshotCanvas;
  3904. var cloneValue = function (source, destinationObject) {
  3905. if (!source)
  3906. return null;
  3907. if (source instanceof BABYLON.Mesh) {
  3908. return null;
  3909. }
  3910. if (source instanceof BABYLON.SubMesh) {
  3911. return source.clone(destinationObject);
  3912. }
  3913. else if (source.clone) {
  3914. return source.clone();
  3915. }
  3916. return null;
  3917. };
  3918. var Tools = (function () {
  3919. function Tools() {
  3920. }
  3921. Tools.Instantiate = function (className) {
  3922. var arr = className.split(".");
  3923. var fn = (window || this);
  3924. for (var i = 0, len = arr.length; i < len; i++) {
  3925. fn = fn[arr[i]];
  3926. }
  3927. if (typeof fn !== "function") {
  3928. return null;
  3929. }
  3930. return fn;
  3931. };
  3932. Tools.GetConstructorName = function (obj) {
  3933. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3934. var cname = str.match(/function\s(\w*)/)[1];
  3935. var aliases = ["", "anonymous", "Anonymous"];
  3936. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3937. };
  3938. Tools.ToHex = function (i) {
  3939. var str = i.toString(16);
  3940. if (i <= 15) {
  3941. return ("0" + str).toUpperCase();
  3942. }
  3943. return str.toUpperCase();
  3944. };
  3945. Tools.SetImmediate = function (action) {
  3946. if (window.setImmediate) {
  3947. window.setImmediate(action);
  3948. }
  3949. else {
  3950. setTimeout(action, 1);
  3951. }
  3952. };
  3953. Tools.IsExponentOfTwo = function (value) {
  3954. var count = 1;
  3955. do {
  3956. count *= 2;
  3957. } while (count < value);
  3958. return count === value;
  3959. };
  3960. Tools.GetExponentOfTwo = function (value, max) {
  3961. var count = 1;
  3962. do {
  3963. count *= 2;
  3964. } while (count < value);
  3965. if (count > max)
  3966. count = max;
  3967. return count;
  3968. };
  3969. Tools.GetFilename = function (path) {
  3970. var index = path.lastIndexOf("/");
  3971. if (index < 0)
  3972. return path;
  3973. return path.substring(index + 1);
  3974. };
  3975. Tools.GetDOMTextContent = function (element) {
  3976. var result = "";
  3977. var child = element.firstChild;
  3978. while (child) {
  3979. if (child.nodeType === 3) {
  3980. result += child.textContent;
  3981. }
  3982. child = child.nextSibling;
  3983. }
  3984. return result;
  3985. };
  3986. Tools.ToDegrees = function (angle) {
  3987. return angle * 180 / Math.PI;
  3988. };
  3989. Tools.ToRadians = function (angle) {
  3990. return angle * Math.PI / 180;
  3991. };
  3992. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3993. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3994. var output = "";
  3995. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3996. var i = 0;
  3997. var bytes = new Uint8Array(buffer);
  3998. while (i < bytes.length) {
  3999. chr1 = bytes[i++];
  4000. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4001. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4002. enc1 = chr1 >> 2;
  4003. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4004. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4005. enc4 = chr3 & 63;
  4006. if (isNaN(chr2)) {
  4007. enc3 = enc4 = 64;
  4008. }
  4009. else if (isNaN(chr3)) {
  4010. enc4 = 64;
  4011. }
  4012. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4013. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4014. }
  4015. return "data:image/png;base64," + output;
  4016. };
  4017. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4018. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4019. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4020. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4021. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4022. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4023. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4024. }
  4025. return {
  4026. minimum: minimum,
  4027. maximum: maximum
  4028. };
  4029. };
  4030. Tools.ExtractMinAndMax = function (positions, start, count) {
  4031. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4032. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4033. for (var index = start; index < start + count; index++) {
  4034. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4035. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4036. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4037. }
  4038. return {
  4039. minimum: minimum,
  4040. maximum: maximum
  4041. };
  4042. };
  4043. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4044. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4045. return undefined;
  4046. return Array.isArray(obj) ? obj : [obj];
  4047. };
  4048. // Misc.
  4049. Tools.GetPointerPrefix = function () {
  4050. var eventPrefix = "pointer";
  4051. // Check if pointer events are supported
  4052. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4053. eventPrefix = "mouse";
  4054. }
  4055. return eventPrefix;
  4056. };
  4057. Tools.QueueNewFrame = function (func) {
  4058. if (window.requestAnimationFrame)
  4059. window.requestAnimationFrame(func);
  4060. else if (window.msRequestAnimationFrame)
  4061. window.msRequestAnimationFrame(func);
  4062. else if (window.webkitRequestAnimationFrame)
  4063. window.webkitRequestAnimationFrame(func);
  4064. else if (window.mozRequestAnimationFrame)
  4065. window.mozRequestAnimationFrame(func);
  4066. else if (window.oRequestAnimationFrame)
  4067. window.oRequestAnimationFrame(func);
  4068. else {
  4069. window.setTimeout(func, 16);
  4070. }
  4071. };
  4072. Tools.RequestFullscreen = function (element) {
  4073. if (element.requestFullscreen)
  4074. element.requestFullscreen();
  4075. else if (element.msRequestFullscreen)
  4076. element.msRequestFullscreen();
  4077. else if (element.webkitRequestFullscreen)
  4078. element.webkitRequestFullscreen();
  4079. else if (element.mozRequestFullScreen)
  4080. element.mozRequestFullScreen();
  4081. };
  4082. Tools.ExitFullscreen = function () {
  4083. if (document.exitFullscreen) {
  4084. document.exitFullscreen();
  4085. }
  4086. else if (document.mozCancelFullScreen) {
  4087. document.mozCancelFullScreen();
  4088. }
  4089. else if (document.webkitCancelFullScreen) {
  4090. document.webkitCancelFullScreen();
  4091. }
  4092. else if (document.msCancelFullScreen) {
  4093. document.msCancelFullScreen();
  4094. }
  4095. };
  4096. // External files
  4097. Tools.CleanUrl = function (url) {
  4098. url = url.replace(/#/mg, "%23");
  4099. return url;
  4100. };
  4101. Tools.LoadImage = function (url, onload, onerror, database) {
  4102. if (url instanceof ArrayBuffer) {
  4103. url = Tools.EncodeArrayBufferTobase64(url);
  4104. }
  4105. url = Tools.CleanUrl(url);
  4106. var img = new Image();
  4107. if (url.substr(0, 5) !== "data:") {
  4108. if (Tools.CorsBehavior) {
  4109. switch (typeof (Tools.CorsBehavior)) {
  4110. case "function":
  4111. var result = Tools.CorsBehavior(url);
  4112. if (result) {
  4113. img.crossOrigin = result;
  4114. }
  4115. break;
  4116. case "string":
  4117. default:
  4118. img.crossOrigin = Tools.CorsBehavior;
  4119. break;
  4120. }
  4121. }
  4122. }
  4123. img.onload = function () {
  4124. onload(img);
  4125. };
  4126. img.onerror = function (err) {
  4127. Tools.Error("Error while trying to load texture: " + url);
  4128. 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";
  4129. onload(img);
  4130. };
  4131. var noIndexedDB = function () {
  4132. img.src = url;
  4133. };
  4134. var loadFromIndexedDB = function () {
  4135. database.loadImageFromDB(url, img);
  4136. };
  4137. //ANY database to do!
  4138. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4139. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4140. }
  4141. else {
  4142. if (url.indexOf("file:") === -1) {
  4143. noIndexedDB();
  4144. }
  4145. else {
  4146. try {
  4147. var textureName = url.substring(5);
  4148. var blobURL;
  4149. try {
  4150. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4151. }
  4152. catch (ex) {
  4153. // Chrome doesn't support oneTimeOnly parameter
  4154. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4155. }
  4156. img.src = blobURL;
  4157. }
  4158. catch (e) {
  4159. img.src = null;
  4160. }
  4161. }
  4162. }
  4163. return img;
  4164. };
  4165. //ANY
  4166. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4167. url = Tools.CleanUrl(url);
  4168. var noIndexedDB = function () {
  4169. var request = new XMLHttpRequest();
  4170. var loadUrl = Tools.BaseUrl + url;
  4171. request.open('GET', loadUrl, true);
  4172. if (useArrayBuffer) {
  4173. request.responseType = "arraybuffer";
  4174. }
  4175. request.onprogress = progressCallBack;
  4176. request.onreadystatechange = function () {
  4177. if (request.readyState === 4) {
  4178. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4179. callback(!useArrayBuffer ? request.responseText : request.response);
  4180. }
  4181. else {
  4182. if (onError) {
  4183. onError();
  4184. }
  4185. else {
  4186. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4187. }
  4188. }
  4189. }
  4190. };
  4191. request.send(null);
  4192. };
  4193. var loadFromIndexedDB = function () {
  4194. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4195. };
  4196. if (url.indexOf("file:") !== -1) {
  4197. var fileName = url.substring(5);
  4198. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4199. }
  4200. else {
  4201. // Caching all files
  4202. if (database && database.enableSceneOffline) {
  4203. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4204. }
  4205. else {
  4206. noIndexedDB();
  4207. }
  4208. }
  4209. };
  4210. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4211. var reader = new FileReader();
  4212. reader.onload = function (e) {
  4213. //target doesn't have result from ts 1.3
  4214. callback(e.target['result']);
  4215. };
  4216. reader.onprogress = progressCallback;
  4217. reader.readAsDataURL(fileToLoad);
  4218. };
  4219. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4220. var reader = new FileReader();
  4221. reader.onerror = function (e) {
  4222. Tools.Log("Error while reading file: " + fileToLoad.name);
  4223. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4224. };
  4225. reader.onload = function (e) {
  4226. //target doesn't have result from ts 1.3
  4227. callback(e.target['result']);
  4228. };
  4229. reader.onprogress = progressCallBack;
  4230. if (!useArrayBuffer) {
  4231. // Asynchronous read
  4232. reader.readAsText(fileToLoad);
  4233. }
  4234. else {
  4235. reader.readAsArrayBuffer(fileToLoad);
  4236. }
  4237. };
  4238. //returns a downloadable url to a file content.
  4239. Tools.FileAsURL = function (content) {
  4240. var fileBlob = new Blob([content]);
  4241. var url = window.URL || window.webkitURL;
  4242. var link = url.createObjectURL(fileBlob);
  4243. return link;
  4244. };
  4245. // Misc.
  4246. Tools.Clamp = function (value, min, max) {
  4247. if (min === void 0) { min = 0; }
  4248. if (max === void 0) { max = 1; }
  4249. return Math.min(max, Math.max(min, value));
  4250. };
  4251. // Returns -1 when value is a negative number and
  4252. // +1 when value is a positive number.
  4253. Tools.Sign = function (value) {
  4254. value = +value; // convert to a number
  4255. if (value === 0 || isNaN(value))
  4256. return value;
  4257. return value > 0 ? 1 : -1;
  4258. };
  4259. Tools.Format = function (value, decimals) {
  4260. if (decimals === void 0) { decimals = 2; }
  4261. return value.toFixed(decimals);
  4262. };
  4263. Tools.CheckExtends = function (v, min, max) {
  4264. if (v.x < min.x)
  4265. min.x = v.x;
  4266. if (v.y < min.y)
  4267. min.y = v.y;
  4268. if (v.z < min.z)
  4269. min.z = v.z;
  4270. if (v.x > max.x)
  4271. max.x = v.x;
  4272. if (v.y > max.y)
  4273. max.y = v.y;
  4274. if (v.z > max.z)
  4275. max.z = v.z;
  4276. };
  4277. Tools.WithinEpsilon = function (a, b, epsilon) {
  4278. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4279. var num = a - b;
  4280. return -epsilon <= num && num <= epsilon;
  4281. };
  4282. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4283. for (var prop in source) {
  4284. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4285. continue;
  4286. }
  4287. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4288. continue;
  4289. }
  4290. var sourceValue = source[prop];
  4291. var typeOfSourceValue = typeof sourceValue;
  4292. if (typeOfSourceValue === "function") {
  4293. continue;
  4294. }
  4295. if (typeOfSourceValue === "object") {
  4296. if (sourceValue instanceof Array) {
  4297. destination[prop] = [];
  4298. if (sourceValue.length > 0) {
  4299. if (typeof sourceValue[0] == "object") {
  4300. for (var index = 0; index < sourceValue.length; index++) {
  4301. var clonedValue = cloneValue(sourceValue[index], destination);
  4302. if (destination[prop].indexOf(clonedValue) === -1) {
  4303. destination[prop].push(clonedValue);
  4304. }
  4305. }
  4306. }
  4307. else {
  4308. destination[prop] = sourceValue.slice(0);
  4309. }
  4310. }
  4311. }
  4312. else {
  4313. destination[prop] = cloneValue(sourceValue, destination);
  4314. }
  4315. }
  4316. else {
  4317. destination[prop] = sourceValue;
  4318. }
  4319. }
  4320. };
  4321. Tools.IsEmpty = function (obj) {
  4322. for (var i in obj) {
  4323. return false;
  4324. }
  4325. return true;
  4326. };
  4327. Tools.RegisterTopRootEvents = function (events) {
  4328. for (var index = 0; index < events.length; index++) {
  4329. var event = events[index];
  4330. window.addEventListener(event.name, event.handler, false);
  4331. try {
  4332. if (window.parent) {
  4333. window.parent.addEventListener(event.name, event.handler, false);
  4334. }
  4335. }
  4336. catch (e) {
  4337. }
  4338. }
  4339. };
  4340. Tools.UnregisterTopRootEvents = function (events) {
  4341. for (var index = 0; index < events.length; index++) {
  4342. var event = events[index];
  4343. window.removeEventListener(event.name, event.handler);
  4344. try {
  4345. if (window.parent) {
  4346. window.parent.removeEventListener(event.name, event.handler);
  4347. }
  4348. }
  4349. catch (e) {
  4350. }
  4351. }
  4352. };
  4353. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4354. // Read the contents of the framebuffer
  4355. var numberOfChannelsByLine = width * 4;
  4356. var halfHeight = height / 2;
  4357. //Reading datas from WebGL
  4358. var data = engine.readPixels(0, 0, width, height);
  4359. //To flip image on Y axis.
  4360. for (var i = 0; i < halfHeight; i++) {
  4361. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4362. var currentCell = j + i * numberOfChannelsByLine;
  4363. var targetLine = height - i - 1;
  4364. var targetCell = j + targetLine * numberOfChannelsByLine;
  4365. var temp = data[currentCell];
  4366. data[currentCell] = data[targetCell];
  4367. data[targetCell] = temp;
  4368. }
  4369. }
  4370. // Create a 2D canvas to store the result
  4371. if (!screenshotCanvas) {
  4372. screenshotCanvas = document.createElement('canvas');
  4373. }
  4374. screenshotCanvas.width = width;
  4375. screenshotCanvas.height = height;
  4376. var context = screenshotCanvas.getContext('2d');
  4377. // Copy the pixels to a 2D canvas
  4378. var imageData = context.createImageData(width, height);
  4379. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4380. var castData = imageData.data;
  4381. castData.set(data);
  4382. context.putImageData(imageData, 0, 0);
  4383. var base64Image = screenshotCanvas.toDataURL();
  4384. if (successCallback) {
  4385. successCallback(base64Image);
  4386. }
  4387. else {
  4388. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4389. if (("download" in document.createElement("a"))) {
  4390. var a = window.document.createElement("a");
  4391. a.href = base64Image;
  4392. var date = new Date();
  4393. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4394. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4395. window.document.body.appendChild(a);
  4396. a.addEventListener("click", function () {
  4397. a.parentElement.removeChild(a);
  4398. });
  4399. a.click();
  4400. }
  4401. else {
  4402. var newWindow = window.open("");
  4403. var img = newWindow.document.createElement("img");
  4404. img.src = base64Image;
  4405. newWindow.document.body.appendChild(img);
  4406. }
  4407. }
  4408. };
  4409. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4410. var width;
  4411. var height;
  4412. //If a precision value is specified
  4413. if (size.precision) {
  4414. width = Math.round(engine.getRenderWidth() * size.precision);
  4415. height = Math.round(width / engine.getAspectRatio(camera));
  4416. size = { width: width, height: height };
  4417. }
  4418. else if (size.width && size.height) {
  4419. width = size.width;
  4420. height = size.height;
  4421. }
  4422. else if (size.width && !size.height) {
  4423. width = size.width;
  4424. height = Math.round(width / engine.getAspectRatio(camera));
  4425. size = { width: width, height: height };
  4426. }
  4427. else if (size.height && !size.width) {
  4428. height = size.height;
  4429. width = Math.round(height * engine.getAspectRatio(camera));
  4430. size = { width: width, height: height };
  4431. }
  4432. else if (!isNaN(size)) {
  4433. height = size;
  4434. width = size;
  4435. }
  4436. else {
  4437. Tools.Error("Invalid 'size' parameter !");
  4438. return;
  4439. }
  4440. var scene = camera.getScene();
  4441. var previousCamera = null;
  4442. if (scene.activeCamera !== camera) {
  4443. previousCamera = scene.activeCamera;
  4444. scene.activeCamera = camera;
  4445. }
  4446. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4447. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4448. texture.renderList = scene.meshes;
  4449. texture.onAfterRender = function () {
  4450. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4451. };
  4452. scene.incrementRenderId();
  4453. texture.render(true);
  4454. texture.dispose();
  4455. if (previousCamera) {
  4456. scene.activeCamera = previousCamera;
  4457. }
  4458. camera.getProjectionMatrix(true); // Force cache refresh;
  4459. };
  4460. // XHR response validator for local file scenario
  4461. Tools.ValidateXHRData = function (xhr, dataType) {
  4462. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4463. if (dataType === void 0) { dataType = 7; }
  4464. try {
  4465. if (dataType & 1) {
  4466. if (xhr.responseText && xhr.responseText.length > 0) {
  4467. return true;
  4468. }
  4469. else if (dataType === 1) {
  4470. return false;
  4471. }
  4472. }
  4473. if (dataType & 2) {
  4474. // Check header width and height since there is no "TGA" magic number
  4475. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4476. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4477. return true;
  4478. }
  4479. else if (dataType === 2) {
  4480. return false;
  4481. }
  4482. }
  4483. if (dataType & 4) {
  4484. // Check for the "DDS" magic number
  4485. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4486. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4487. return true;
  4488. }
  4489. else {
  4490. return false;
  4491. }
  4492. }
  4493. }
  4494. catch (e) {
  4495. }
  4496. return false;
  4497. };
  4498. Object.defineProperty(Tools, "NoneLogLevel", {
  4499. get: function () {
  4500. return Tools._NoneLogLevel;
  4501. },
  4502. enumerable: true,
  4503. configurable: true
  4504. });
  4505. Object.defineProperty(Tools, "MessageLogLevel", {
  4506. get: function () {
  4507. return Tools._MessageLogLevel;
  4508. },
  4509. enumerable: true,
  4510. configurable: true
  4511. });
  4512. Object.defineProperty(Tools, "WarningLogLevel", {
  4513. get: function () {
  4514. return Tools._WarningLogLevel;
  4515. },
  4516. enumerable: true,
  4517. configurable: true
  4518. });
  4519. Object.defineProperty(Tools, "ErrorLogLevel", {
  4520. get: function () {
  4521. return Tools._ErrorLogLevel;
  4522. },
  4523. enumerable: true,
  4524. configurable: true
  4525. });
  4526. Object.defineProperty(Tools, "AllLogLevel", {
  4527. get: function () {
  4528. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4529. },
  4530. enumerable: true,
  4531. configurable: true
  4532. });
  4533. Tools._AddLogEntry = function (entry) {
  4534. Tools._LogCache = entry + Tools._LogCache;
  4535. if (Tools.OnNewCacheEntry) {
  4536. Tools.OnNewCacheEntry(entry);
  4537. }
  4538. };
  4539. Tools._FormatMessage = function (message) {
  4540. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4541. var date = new Date();
  4542. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4543. };
  4544. Tools._LogDisabled = function (message) {
  4545. // nothing to do
  4546. };
  4547. Tools._LogEnabled = function (message) {
  4548. var formattedMessage = Tools._FormatMessage(message);
  4549. console.log("BJS - " + formattedMessage);
  4550. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4551. Tools._AddLogEntry(entry);
  4552. };
  4553. Tools._WarnDisabled = function (message) {
  4554. // nothing to do
  4555. };
  4556. Tools._WarnEnabled = function (message) {
  4557. var formattedMessage = Tools._FormatMessage(message);
  4558. console.warn("BJS - " + formattedMessage);
  4559. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4560. Tools._AddLogEntry(entry);
  4561. };
  4562. Tools._ErrorDisabled = function (message) {
  4563. // nothing to do
  4564. };
  4565. Tools._ErrorEnabled = function (message) {
  4566. Tools.errorsCount++;
  4567. var formattedMessage = Tools._FormatMessage(message);
  4568. console.error("BJS - " + formattedMessage);
  4569. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4570. Tools._AddLogEntry(entry);
  4571. };
  4572. Object.defineProperty(Tools, "LogCache", {
  4573. get: function () {
  4574. return Tools._LogCache;
  4575. },
  4576. enumerable: true,
  4577. configurable: true
  4578. });
  4579. Tools.ClearLogCache = function () {
  4580. Tools._LogCache = "";
  4581. Tools.errorsCount = 0;
  4582. };
  4583. Object.defineProperty(Tools, "LogLevels", {
  4584. set: function (level) {
  4585. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4586. Tools.Log = Tools._LogEnabled;
  4587. }
  4588. else {
  4589. Tools.Log = Tools._LogDisabled;
  4590. }
  4591. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4592. Tools.Warn = Tools._WarnEnabled;
  4593. }
  4594. else {
  4595. Tools.Warn = Tools._WarnDisabled;
  4596. }
  4597. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4598. Tools.Error = Tools._ErrorEnabled;
  4599. }
  4600. else {
  4601. Tools.Error = Tools._ErrorDisabled;
  4602. }
  4603. },
  4604. enumerable: true,
  4605. configurable: true
  4606. });
  4607. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4608. get: function () {
  4609. return Tools._PerformanceNoneLogLevel;
  4610. },
  4611. enumerable: true,
  4612. configurable: true
  4613. });
  4614. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4615. get: function () {
  4616. return Tools._PerformanceUserMarkLogLevel;
  4617. },
  4618. enumerable: true,
  4619. configurable: true
  4620. });
  4621. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4622. get: function () {
  4623. return Tools._PerformanceConsoleLogLevel;
  4624. },
  4625. enumerable: true,
  4626. configurable: true
  4627. });
  4628. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4629. set: function (level) {
  4630. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4631. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4632. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4633. return;
  4634. }
  4635. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4636. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4637. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4638. return;
  4639. }
  4640. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4641. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4642. },
  4643. enumerable: true,
  4644. configurable: true
  4645. });
  4646. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4647. };
  4648. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4649. };
  4650. Tools._StartUserMark = function (counterName, condition) {
  4651. if (condition === void 0) { condition = true; }
  4652. if (!condition || !Tools._performance.mark) {
  4653. return;
  4654. }
  4655. Tools._performance.mark(counterName + "-Begin");
  4656. };
  4657. Tools._EndUserMark = function (counterName, condition) {
  4658. if (condition === void 0) { condition = true; }
  4659. if (!condition || !Tools._performance.mark) {
  4660. return;
  4661. }
  4662. Tools._performance.mark(counterName + "-End");
  4663. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4664. };
  4665. Tools._StartPerformanceConsole = function (counterName, condition) {
  4666. if (condition === void 0) { condition = true; }
  4667. if (!condition) {
  4668. return;
  4669. }
  4670. Tools._StartUserMark(counterName, condition);
  4671. if (console.time) {
  4672. console.time(counterName);
  4673. }
  4674. };
  4675. Tools._EndPerformanceConsole = function (counterName, condition) {
  4676. if (condition === void 0) { condition = true; }
  4677. if (!condition) {
  4678. return;
  4679. }
  4680. Tools._EndUserMark(counterName, condition);
  4681. if (console.time) {
  4682. console.timeEnd(counterName);
  4683. }
  4684. };
  4685. Object.defineProperty(Tools, "Now", {
  4686. get: function () {
  4687. if (window.performance && window.performance.now) {
  4688. return window.performance.now();
  4689. }
  4690. return new Date().getTime();
  4691. },
  4692. enumerable: true,
  4693. configurable: true
  4694. });
  4695. Tools.BaseUrl = "";
  4696. Tools.CorsBehavior = "anonymous";
  4697. // Logs
  4698. Tools._NoneLogLevel = 0;
  4699. Tools._MessageLogLevel = 1;
  4700. Tools._WarningLogLevel = 2;
  4701. Tools._ErrorLogLevel = 4;
  4702. Tools._LogCache = "";
  4703. Tools.errorsCount = 0;
  4704. Tools.Log = Tools._LogEnabled;
  4705. Tools.Warn = Tools._WarnEnabled;
  4706. Tools.Error = Tools._ErrorEnabled;
  4707. // Performances
  4708. Tools._PerformanceNoneLogLevel = 0;
  4709. Tools._PerformanceUserMarkLogLevel = 1;
  4710. Tools._PerformanceConsoleLogLevel = 2;
  4711. Tools._performance = window.performance;
  4712. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4713. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4714. return Tools;
  4715. })();
  4716. BABYLON.Tools = Tools;
  4717. /**
  4718. * An implementation of a loop for asynchronous functions.
  4719. */
  4720. var AsyncLoop = (function () {
  4721. /**
  4722. * Constroctor.
  4723. * @param iterations the number of iterations.
  4724. * @param _fn the function to run each iteration
  4725. * @param _successCallback the callback that will be called upon succesful execution
  4726. * @param offset starting offset.
  4727. */
  4728. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4729. if (offset === void 0) { offset = 0; }
  4730. this.iterations = iterations;
  4731. this._fn = _fn;
  4732. this._successCallback = _successCallback;
  4733. this.index = offset - 1;
  4734. this._done = false;
  4735. }
  4736. /**
  4737. * Execute the next iteration. Must be called after the last iteration was finished.
  4738. */
  4739. AsyncLoop.prototype.executeNext = function () {
  4740. if (!this._done) {
  4741. if (this.index + 1 < this.iterations) {
  4742. ++this.index;
  4743. this._fn(this);
  4744. }
  4745. else {
  4746. this.breakLoop();
  4747. }
  4748. }
  4749. };
  4750. /**
  4751. * Break the loop and run the success callback.
  4752. */
  4753. AsyncLoop.prototype.breakLoop = function () {
  4754. this._done = true;
  4755. this._successCallback();
  4756. };
  4757. /**
  4758. * Helper function
  4759. */
  4760. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4761. if (offset === void 0) { offset = 0; }
  4762. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4763. loop.executeNext();
  4764. return loop;
  4765. };
  4766. /**
  4767. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4768. * @param iterations total number of iterations
  4769. * @param syncedIterations number of synchronous iterations in each async iteration.
  4770. * @param fn the function to call each iteration.
  4771. * @param callback a success call back that will be called when iterating stops.
  4772. * @param breakFunction a break condition (optional)
  4773. * @param timeout timeout settings for the setTimeout function. default - 0.
  4774. * @constructor
  4775. */
  4776. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4777. if (timeout === void 0) { timeout = 0; }
  4778. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4779. if (breakFunction && breakFunction())
  4780. loop.breakLoop();
  4781. else {
  4782. setTimeout(function () {
  4783. for (var i = 0; i < syncedIterations; ++i) {
  4784. var iteration = (loop.index * syncedIterations) + i;
  4785. if (iteration >= iterations)
  4786. break;
  4787. fn(iteration);
  4788. if (breakFunction && breakFunction()) {
  4789. loop.breakLoop();
  4790. break;
  4791. }
  4792. }
  4793. loop.executeNext();
  4794. }, timeout);
  4795. }
  4796. }, callback);
  4797. };
  4798. return AsyncLoop;
  4799. })();
  4800. BABYLON.AsyncLoop = AsyncLoop;
  4801. })(BABYLON || (BABYLON = {}));
  4802. var BABYLON;
  4803. (function (BABYLON) {
  4804. var _DepthCullingState = (function () {
  4805. function _DepthCullingState() {
  4806. this._isDepthTestDirty = false;
  4807. this._isDepthMaskDirty = false;
  4808. this._isDepthFuncDirty = false;
  4809. this._isCullFaceDirty = false;
  4810. this._isCullDirty = false;
  4811. this._isZOffsetDirty = false;
  4812. }
  4813. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4814. get: function () {
  4815. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4816. },
  4817. enumerable: true,
  4818. configurable: true
  4819. });
  4820. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4821. get: function () {
  4822. return this._zOffset;
  4823. },
  4824. set: function (value) {
  4825. if (this._zOffset === value) {
  4826. return;
  4827. }
  4828. this._zOffset = value;
  4829. this._isZOffsetDirty = true;
  4830. },
  4831. enumerable: true,
  4832. configurable: true
  4833. });
  4834. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4835. get: function () {
  4836. return this._cullFace;
  4837. },
  4838. set: function (value) {
  4839. if (this._cullFace === value) {
  4840. return;
  4841. }
  4842. this._cullFace = value;
  4843. this._isCullFaceDirty = true;
  4844. },
  4845. enumerable: true,
  4846. configurable: true
  4847. });
  4848. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4849. get: function () {
  4850. return this._cull;
  4851. },
  4852. set: function (value) {
  4853. if (this._cull === value) {
  4854. return;
  4855. }
  4856. this._cull = value;
  4857. this._isCullDirty = true;
  4858. },
  4859. enumerable: true,
  4860. configurable: true
  4861. });
  4862. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4863. get: function () {
  4864. return this._depthFunc;
  4865. },
  4866. set: function (value) {
  4867. if (this._depthFunc === value) {
  4868. return;
  4869. }
  4870. this._depthFunc = value;
  4871. this._isDepthFuncDirty = true;
  4872. },
  4873. enumerable: true,
  4874. configurable: true
  4875. });
  4876. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4877. get: function () {
  4878. return this._depthMask;
  4879. },
  4880. set: function (value) {
  4881. if (this._depthMask === value) {
  4882. return;
  4883. }
  4884. this._depthMask = value;
  4885. this._isDepthMaskDirty = true;
  4886. },
  4887. enumerable: true,
  4888. configurable: true
  4889. });
  4890. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4891. get: function () {
  4892. return this._depthTest;
  4893. },
  4894. set: function (value) {
  4895. if (this._depthTest === value) {
  4896. return;
  4897. }
  4898. this._depthTest = value;
  4899. this._isDepthTestDirty = true;
  4900. },
  4901. enumerable: true,
  4902. configurable: true
  4903. });
  4904. _DepthCullingState.prototype.reset = function () {
  4905. this._depthMask = true;
  4906. this._depthTest = true;
  4907. this._depthFunc = null;
  4908. this._cull = null;
  4909. this._cullFace = null;
  4910. this._zOffset = 0;
  4911. this._isDepthTestDirty = true;
  4912. this._isDepthMaskDirty = true;
  4913. this._isDepthFuncDirty = false;
  4914. this._isCullFaceDirty = false;
  4915. this._isCullDirty = false;
  4916. this._isZOffsetDirty = false;
  4917. };
  4918. _DepthCullingState.prototype.apply = function (gl) {
  4919. if (!this.isDirty) {
  4920. return;
  4921. }
  4922. // Cull
  4923. if (this._isCullDirty) {
  4924. if (this.cull) {
  4925. gl.enable(gl.CULL_FACE);
  4926. }
  4927. else {
  4928. gl.disable(gl.CULL_FACE);
  4929. }
  4930. this._isCullDirty = false;
  4931. }
  4932. // Cull face
  4933. if (this._isCullFaceDirty) {
  4934. gl.cullFace(this.cullFace);
  4935. this._isCullFaceDirty = false;
  4936. }
  4937. // Depth mask
  4938. if (this._isDepthMaskDirty) {
  4939. gl.depthMask(this.depthMask);
  4940. this._isDepthMaskDirty = false;
  4941. }
  4942. // Depth test
  4943. if (this._isDepthTestDirty) {
  4944. if (this.depthTest) {
  4945. gl.enable(gl.DEPTH_TEST);
  4946. }
  4947. else {
  4948. gl.disable(gl.DEPTH_TEST);
  4949. }
  4950. this._isDepthTestDirty = false;
  4951. }
  4952. // Depth func
  4953. if (this._isDepthFuncDirty) {
  4954. gl.depthFunc(this.depthFunc);
  4955. this._isDepthFuncDirty = false;
  4956. }
  4957. // zOffset
  4958. if (this._isZOffsetDirty) {
  4959. if (this.zOffset) {
  4960. gl.enable(gl.POLYGON_OFFSET_FILL);
  4961. gl.polygonOffset(this.zOffset, 0);
  4962. }
  4963. else {
  4964. gl.disable(gl.POLYGON_OFFSET_FILL);
  4965. }
  4966. this._isZOffsetDirty = false;
  4967. }
  4968. };
  4969. return _DepthCullingState;
  4970. })();
  4971. BABYLON._DepthCullingState = _DepthCullingState;
  4972. var _AlphaState = (function () {
  4973. function _AlphaState() {
  4974. this._isAlphaBlendDirty = false;
  4975. this._isBlendFunctionParametersDirty = false;
  4976. this._alphaBlend = false;
  4977. this._blendFunctionParameters = new Array(4);
  4978. }
  4979. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4980. get: function () {
  4981. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4982. },
  4983. enumerable: true,
  4984. configurable: true
  4985. });
  4986. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4987. get: function () {
  4988. return this._alphaBlend;
  4989. },
  4990. set: function (value) {
  4991. if (this._alphaBlend === value) {
  4992. return;
  4993. }
  4994. this._alphaBlend = value;
  4995. this._isAlphaBlendDirty = true;
  4996. },
  4997. enumerable: true,
  4998. configurable: true
  4999. });
  5000. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5001. if (this._blendFunctionParameters[0] === value0 &&
  5002. this._blendFunctionParameters[1] === value1 &&
  5003. this._blendFunctionParameters[2] === value2 &&
  5004. this._blendFunctionParameters[3] === value3) {
  5005. return;
  5006. }
  5007. this._blendFunctionParameters[0] = value0;
  5008. this._blendFunctionParameters[1] = value1;
  5009. this._blendFunctionParameters[2] = value2;
  5010. this._blendFunctionParameters[3] = value3;
  5011. this._isBlendFunctionParametersDirty = true;
  5012. };
  5013. _AlphaState.prototype.reset = function () {
  5014. this._alphaBlend = false;
  5015. this._blendFunctionParameters[0] = null;
  5016. this._blendFunctionParameters[1] = null;
  5017. this._blendFunctionParameters[2] = null;
  5018. this._blendFunctionParameters[3] = null;
  5019. this._isAlphaBlendDirty = true;
  5020. this._isBlendFunctionParametersDirty = false;
  5021. };
  5022. _AlphaState.prototype.apply = function (gl) {
  5023. if (!this.isDirty) {
  5024. return;
  5025. }
  5026. // Alpha blend
  5027. if (this._isAlphaBlendDirty) {
  5028. if (this._alphaBlend) {
  5029. gl.enable(gl.BLEND);
  5030. }
  5031. else {
  5032. gl.disable(gl.BLEND);
  5033. }
  5034. this._isAlphaBlendDirty = false;
  5035. }
  5036. // Alpha function
  5037. if (this._isBlendFunctionParametersDirty) {
  5038. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5039. this._isBlendFunctionParametersDirty = false;
  5040. }
  5041. };
  5042. return _AlphaState;
  5043. })();
  5044. BABYLON._AlphaState = _AlphaState;
  5045. var compileShader = function (gl, source, type, defines) {
  5046. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5047. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5048. gl.compileShader(shader);
  5049. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5050. throw new Error(gl.getShaderInfoLog(shader));
  5051. }
  5052. return shader;
  5053. };
  5054. var getWebGLTextureType = function (gl, type) {
  5055. var textureType = gl.UNSIGNED_BYTE;
  5056. if (type === Engine.TEXTURETYPE_FLOAT)
  5057. textureType = gl.FLOAT;
  5058. return textureType;
  5059. };
  5060. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5061. var magFilter = gl.NEAREST;
  5062. var minFilter = gl.NEAREST;
  5063. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5064. magFilter = gl.LINEAR;
  5065. if (generateMipMaps) {
  5066. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5067. }
  5068. else {
  5069. minFilter = gl.LINEAR;
  5070. }
  5071. }
  5072. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5073. magFilter = gl.LINEAR;
  5074. if (generateMipMaps) {
  5075. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5076. }
  5077. else {
  5078. minFilter = gl.LINEAR;
  5079. }
  5080. }
  5081. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5082. magFilter = gl.NEAREST;
  5083. if (generateMipMaps) {
  5084. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5085. }
  5086. else {
  5087. minFilter = gl.NEAREST;
  5088. }
  5089. }
  5090. return {
  5091. min: minFilter,
  5092. mag: magFilter
  5093. };
  5094. };
  5095. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5097. var engine = scene.getEngine();
  5098. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5099. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5100. gl.bindTexture(gl.TEXTURE_2D, texture);
  5101. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5102. texture._baseWidth = width;
  5103. texture._baseHeight = height;
  5104. texture._width = potWidth;
  5105. texture._height = potHeight;
  5106. texture.isReady = true;
  5107. processFunction(potWidth, potHeight);
  5108. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5111. if (!noMipmap && !isCompressed) {
  5112. gl.generateMipmap(gl.TEXTURE_2D);
  5113. }
  5114. gl.bindTexture(gl.TEXTURE_2D, null);
  5115. engine.resetTextureCache();
  5116. scene._removePendingData(texture);
  5117. };
  5118. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5119. var img;
  5120. var onload = function () {
  5121. loadedImages[index] = img;
  5122. loadedImages._internalCount++;
  5123. scene._removePendingData(img);
  5124. if (loadedImages._internalCount === 6) {
  5125. onfinish(loadedImages);
  5126. }
  5127. };
  5128. var onerror = function () {
  5129. scene._removePendingData(img);
  5130. };
  5131. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5132. scene._addPendingData(img);
  5133. };
  5134. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5135. var loadedImages = [];
  5136. loadedImages._internalCount = 0;
  5137. for (var index = 0; index < 6; index++) {
  5138. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5139. }
  5140. };
  5141. var EngineCapabilities = (function () {
  5142. function EngineCapabilities() {
  5143. }
  5144. return EngineCapabilities;
  5145. })();
  5146. BABYLON.EngineCapabilities = EngineCapabilities;
  5147. /**
  5148. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5149. */
  5150. var Engine = (function () {
  5151. /**
  5152. * @constructor
  5153. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5154. * @param {boolean} [antialias] - enable antialias
  5155. * @param options - further options to be sent to the getContext function
  5156. */
  5157. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5158. var _this = this;
  5159. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5160. // Public members
  5161. this.isFullscreen = false;
  5162. this.isPointerLock = false;
  5163. this.cullBackFaces = true;
  5164. this.renderEvenInBackground = true;
  5165. // To enable/disable IDB support and avoid XHR on .manifest
  5166. this.enableOfflineSupport = true;
  5167. this.scenes = new Array();
  5168. this._windowIsBackground = false;
  5169. this._drawCalls = 0;
  5170. this._renderingQueueLaunched = false;
  5171. this._activeRenderLoops = [];
  5172. // FPS
  5173. this.fpsRange = 60;
  5174. this.previousFramesDuration = [];
  5175. this.fps = 60;
  5176. this.deltaTime = 0;
  5177. // States
  5178. this._depthCullingState = new _DepthCullingState();
  5179. this._alphaState = new _AlphaState();
  5180. this._alphaMode = Engine.ALPHA_DISABLE;
  5181. // Cache
  5182. this._loadedTexturesCache = new Array();
  5183. this._maxTextureChannels = 16;
  5184. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5185. this._compiledEffects = {};
  5186. this._uintIndicesCurrentlySet = false;
  5187. this._renderingCanvas = canvas;
  5188. options = options || {};
  5189. options.antialias = antialias;
  5190. if (options.preserveDrawingBuffer === undefined) {
  5191. options.preserveDrawingBuffer = false;
  5192. }
  5193. // GL
  5194. try {
  5195. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5196. }
  5197. catch (e) {
  5198. throw new Error("WebGL not supported");
  5199. }
  5200. if (!this._gl) {
  5201. throw new Error("WebGL not supported");
  5202. }
  5203. this._onBlur = function () {
  5204. _this._windowIsBackground = true;
  5205. };
  5206. this._onFocus = function () {
  5207. _this._windowIsBackground = false;
  5208. };
  5209. window.addEventListener("blur", this._onBlur);
  5210. window.addEventListener("focus", this._onFocus);
  5211. // Viewport
  5212. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5213. this.resize();
  5214. // Caps
  5215. this._caps = new EngineCapabilities();
  5216. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5217. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5218. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5219. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5220. // Infos
  5221. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5222. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5223. if (rendererInfo != null) {
  5224. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5225. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5226. }
  5227. if (!this._glVendor) {
  5228. this._glVendor = "Unknown vendor";
  5229. }
  5230. if (!this._glRenderer) {
  5231. this._glRenderer = "Unknown renderer";
  5232. }
  5233. // Extensions
  5234. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5235. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5236. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5237. 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');
  5238. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5239. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5240. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5241. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5242. this._caps.highPrecisionShaderSupported = true;
  5243. if (this._gl.getShaderPrecisionFormat) {
  5244. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5245. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5246. }
  5247. // Depth buffer
  5248. this.setDepthBuffer(true);
  5249. this.setDepthFunctionToLessOrEqual();
  5250. this.setDepthWrite(true);
  5251. // Fullscreen
  5252. this._onFullscreenChange = function () {
  5253. if (document.fullscreen !== undefined) {
  5254. _this.isFullscreen = document.fullscreen;
  5255. }
  5256. else if (document.mozFullScreen !== undefined) {
  5257. _this.isFullscreen = document.mozFullScreen;
  5258. }
  5259. else if (document.webkitIsFullScreen !== undefined) {
  5260. _this.isFullscreen = document.webkitIsFullScreen;
  5261. }
  5262. else if (document.msIsFullScreen !== undefined) {
  5263. _this.isFullscreen = document.msIsFullScreen;
  5264. }
  5265. // Pointer lock
  5266. if (_this.isFullscreen && _this._pointerLockRequested) {
  5267. canvas.requestPointerLock = canvas.requestPointerLock ||
  5268. canvas.msRequestPointerLock ||
  5269. canvas.mozRequestPointerLock ||
  5270. canvas.webkitRequestPointerLock;
  5271. if (canvas.requestPointerLock) {
  5272. canvas.requestPointerLock();
  5273. }
  5274. }
  5275. };
  5276. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5277. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5278. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5279. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5280. // Pointer lock
  5281. this._onPointerLockChange = function () {
  5282. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5283. document.webkitPointerLockElement === canvas ||
  5284. document.msPointerLockElement === canvas ||
  5285. document.pointerLockElement === canvas);
  5286. };
  5287. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5288. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5289. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5290. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5291. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5292. Engine.audioEngine = new BABYLON.AudioEngine();
  5293. }
  5294. //default loading screen
  5295. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5296. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5297. }
  5298. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5299. get: function () {
  5300. return Engine._ALPHA_DISABLE;
  5301. },
  5302. enumerable: true,
  5303. configurable: true
  5304. });
  5305. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5306. get: function () {
  5307. return Engine._ALPHA_ONEONE;
  5308. },
  5309. enumerable: true,
  5310. configurable: true
  5311. });
  5312. Object.defineProperty(Engine, "ALPHA_ADD", {
  5313. get: function () {
  5314. return Engine._ALPHA_ADD;
  5315. },
  5316. enumerable: true,
  5317. configurable: true
  5318. });
  5319. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5320. get: function () {
  5321. return Engine._ALPHA_COMBINE;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5327. get: function () {
  5328. return Engine._ALPHA_SUBTRACT;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5334. get: function () {
  5335. return Engine._ALPHA_MULTIPLY;
  5336. },
  5337. enumerable: true,
  5338. configurable: true
  5339. });
  5340. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5341. get: function () {
  5342. return Engine._ALPHA_MAXIMIZED;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5348. get: function () {
  5349. return Engine._DELAYLOADSTATE_NONE;
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5355. get: function () {
  5356. return Engine._DELAYLOADSTATE_LOADED;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5362. get: function () {
  5363. return Engine._DELAYLOADSTATE_LOADING;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5369. get: function () {
  5370. return Engine._DELAYLOADSTATE_NOTLOADED;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5376. get: function () {
  5377. return Engine._TEXTUREFORMAT_ALPHA;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5383. get: function () {
  5384. return Engine._TEXTUREFORMAT_LUMINANCE;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5390. get: function () {
  5391. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5397. get: function () {
  5398. return Engine._TEXTUREFORMAT_RGB;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5404. get: function () {
  5405. return Engine._TEXTUREFORMAT_RGBA;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5411. get: function () {
  5412. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5418. get: function () {
  5419. return Engine._TEXTURETYPE_FLOAT;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "Version", {
  5425. get: function () {
  5426. return "2.3.0-beta";
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Engine.prototype._prepareWorkingCanvas = function () {
  5432. if (this._workingCanvas) {
  5433. return;
  5434. }
  5435. this._workingCanvas = document.createElement("canvas");
  5436. this._workingContext = this._workingCanvas.getContext("2d");
  5437. };
  5438. Engine.prototype.resetTextureCache = function () {
  5439. for (var index = 0; index < this._maxTextureChannels; index++) {
  5440. this._activeTexturesCache[index] = null;
  5441. }
  5442. };
  5443. Engine.prototype.getGlInfo = function () {
  5444. return {
  5445. vendor: this._glVendor,
  5446. renderer: this._glRenderer,
  5447. version: this._glVersion
  5448. };
  5449. };
  5450. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5451. if (useScreen === void 0) { useScreen = false; }
  5452. var viewport = camera.viewport;
  5453. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5454. };
  5455. Engine.prototype.getRenderWidth = function (useScreen) {
  5456. if (useScreen === void 0) { useScreen = false; }
  5457. if (!useScreen && this._currentRenderTarget) {
  5458. return this._currentRenderTarget._width;
  5459. }
  5460. return this._renderingCanvas.width;
  5461. };
  5462. Engine.prototype.getRenderHeight = function (useScreen) {
  5463. if (useScreen === void 0) { useScreen = false; }
  5464. if (!useScreen && this._currentRenderTarget) {
  5465. return this._currentRenderTarget._height;
  5466. }
  5467. return this._renderingCanvas.height;
  5468. };
  5469. Engine.prototype.getRenderingCanvas = function () {
  5470. return this._renderingCanvas;
  5471. };
  5472. Engine.prototype.getRenderingCanvasClientRect = function () {
  5473. return this._renderingCanvas.getBoundingClientRect();
  5474. };
  5475. Engine.prototype.setHardwareScalingLevel = function (level) {
  5476. this._hardwareScalingLevel = level;
  5477. this.resize();
  5478. };
  5479. Engine.prototype.getHardwareScalingLevel = function () {
  5480. return this._hardwareScalingLevel;
  5481. };
  5482. Engine.prototype.getLoadedTexturesCache = function () {
  5483. return this._loadedTexturesCache;
  5484. };
  5485. Engine.prototype.getCaps = function () {
  5486. return this._caps;
  5487. };
  5488. Object.defineProperty(Engine.prototype, "drawCalls", {
  5489. get: function () {
  5490. return this._drawCalls;
  5491. },
  5492. enumerable: true,
  5493. configurable: true
  5494. });
  5495. // Methods
  5496. Engine.prototype.resetDrawCalls = function () {
  5497. this._drawCalls = 0;
  5498. };
  5499. Engine.prototype.setDepthFunctionToGreater = function () {
  5500. this._depthCullingState.depthFunc = this._gl.GREATER;
  5501. };
  5502. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5503. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5504. };
  5505. Engine.prototype.setDepthFunctionToLess = function () {
  5506. this._depthCullingState.depthFunc = this._gl.LESS;
  5507. };
  5508. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5509. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5510. };
  5511. /**
  5512. * stop executing a render loop function and remove it from the execution array
  5513. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5514. */
  5515. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5516. if (!renderFunction) {
  5517. this._activeRenderLoops = [];
  5518. return;
  5519. }
  5520. var index = this._activeRenderLoops.indexOf(renderFunction);
  5521. if (index >= 0) {
  5522. this._activeRenderLoops.splice(index, 1);
  5523. }
  5524. };
  5525. Engine.prototype._renderLoop = function () {
  5526. var shouldRender = true;
  5527. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5528. shouldRender = false;
  5529. }
  5530. if (shouldRender) {
  5531. // Start new frame
  5532. this.beginFrame();
  5533. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5534. var renderFunction = this._activeRenderLoops[index];
  5535. renderFunction();
  5536. }
  5537. // Present
  5538. this.endFrame();
  5539. }
  5540. if (this._activeRenderLoops.length > 0) {
  5541. // Register new frame
  5542. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5543. }
  5544. else {
  5545. this._renderingQueueLaunched = false;
  5546. }
  5547. };
  5548. /**
  5549. * Register and execute a render loop. The engine can have more than one render function.
  5550. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5551. * @example
  5552. * engine.runRenderLoop(function () {
  5553. * scene.render()
  5554. * })
  5555. */
  5556. Engine.prototype.runRenderLoop = function (renderFunction) {
  5557. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5558. return;
  5559. }
  5560. this._activeRenderLoops.push(renderFunction);
  5561. if (!this._renderingQueueLaunched) {
  5562. this._renderingQueueLaunched = true;
  5563. this._bindedRenderFunction = this._renderLoop.bind(this);
  5564. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5565. }
  5566. };
  5567. /**
  5568. * Toggle full screen mode.
  5569. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5570. */
  5571. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5572. if (this.isFullscreen) {
  5573. BABYLON.Tools.ExitFullscreen();
  5574. }
  5575. else {
  5576. this._pointerLockRequested = requestPointerLock;
  5577. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5578. }
  5579. };
  5580. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5581. this.applyStates();
  5582. if (backBuffer) {
  5583. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5584. }
  5585. if (depthStencil && this._depthCullingState.depthMask) {
  5586. this._gl.clearDepth(1.0);
  5587. }
  5588. var mode = 0;
  5589. if (backBuffer) {
  5590. mode |= this._gl.COLOR_BUFFER_BIT;
  5591. }
  5592. if (depthStencil && this._depthCullingState.depthMask) {
  5593. mode |= this._gl.DEPTH_BUFFER_BIT;
  5594. }
  5595. this._gl.clear(mode);
  5596. };
  5597. /**
  5598. * Set the WebGL's viewport
  5599. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5600. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5601. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5602. */
  5603. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5604. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5605. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5606. var x = viewport.x || 0;
  5607. var y = viewport.y || 0;
  5608. this._cachedViewport = viewport;
  5609. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5610. };
  5611. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5612. this._cachedViewport = null;
  5613. this._gl.viewport(x, y, width, height);
  5614. };
  5615. Engine.prototype.beginFrame = function () {
  5616. this._measureFps();
  5617. };
  5618. Engine.prototype.endFrame = function () {
  5619. //this.flushFramebuffer();
  5620. };
  5621. /**
  5622. * resize the view according to the canvas' size.
  5623. * @example
  5624. * window.addEventListener("resize", function () {
  5625. * engine.resize();
  5626. * });
  5627. */
  5628. Engine.prototype.resize = function () {
  5629. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5630. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5631. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5632. for (var index = 0; index < this.scenes.length; index++) {
  5633. var scene = this.scenes[index];
  5634. if (scene.debugLayer.isVisible()) {
  5635. scene.debugLayer._syncPositions();
  5636. }
  5637. }
  5638. };
  5639. /**
  5640. * force a specific size of the canvas
  5641. * @param {number} width - the new canvas' width
  5642. * @param {number} height - the new canvas' height
  5643. */
  5644. Engine.prototype.setSize = function (width, height) {
  5645. this._renderingCanvas.width = width;
  5646. this._renderingCanvas.height = height;
  5647. for (var index = 0; index < this.scenes.length; index++) {
  5648. var scene = this.scenes[index];
  5649. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5650. var cam = scene.cameras[camIndex];
  5651. cam._currentRenderId = 0;
  5652. }
  5653. }
  5654. };
  5655. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5656. this._currentRenderTarget = texture;
  5657. var gl = this._gl;
  5658. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5659. if (texture.isCube) {
  5660. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5661. }
  5662. else {
  5663. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5664. }
  5665. this._gl.viewport(0, 0, texture._width, texture._height);
  5666. this.wipeCaches();
  5667. };
  5668. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5669. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5670. this._currentRenderTarget = null;
  5671. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5672. var gl = this._gl;
  5673. gl.bindTexture(gl.TEXTURE_2D, texture);
  5674. gl.generateMipmap(gl.TEXTURE_2D);
  5675. gl.bindTexture(gl.TEXTURE_2D, null);
  5676. }
  5677. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5678. };
  5679. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5680. if (texture.generateMipMaps) {
  5681. var gl = this._gl;
  5682. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5683. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5684. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5685. }
  5686. };
  5687. Engine.prototype.flushFramebuffer = function () {
  5688. this._gl.flush();
  5689. };
  5690. Engine.prototype.restoreDefaultFramebuffer = function () {
  5691. this._currentRenderTarget = null;
  5692. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5693. this.setViewport(this._cachedViewport);
  5694. this.wipeCaches();
  5695. };
  5696. // VBOs
  5697. Engine.prototype._resetVertexBufferBinding = function () {
  5698. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5699. this._cachedVertexBuffers = null;
  5700. };
  5701. Engine.prototype.createVertexBuffer = function (vertices) {
  5702. var vbo = this._gl.createBuffer();
  5703. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5704. if (vertices instanceof Float32Array) {
  5705. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5706. }
  5707. else {
  5708. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5709. }
  5710. this._resetVertexBufferBinding();
  5711. vbo.references = 1;
  5712. return vbo;
  5713. };
  5714. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5715. var vbo = this._gl.createBuffer();
  5716. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5717. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5718. this._resetVertexBufferBinding();
  5719. vbo.references = 1;
  5720. return vbo;
  5721. };
  5722. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5723. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5724. if (offset === undefined) {
  5725. offset = 0;
  5726. }
  5727. if (vertices instanceof Float32Array) {
  5728. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5729. }
  5730. else {
  5731. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5732. }
  5733. this._resetVertexBufferBinding();
  5734. };
  5735. Engine.prototype._resetIndexBufferBinding = function () {
  5736. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5737. this._cachedIndexBuffer = null;
  5738. };
  5739. Engine.prototype.createIndexBuffer = function (indices) {
  5740. var vbo = this._gl.createBuffer();
  5741. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5742. // Check for 32 bits indices
  5743. var arrayBuffer;
  5744. var need32Bits = false;
  5745. if (this._caps.uintIndices) {
  5746. for (var index = 0; index < indices.length; index++) {
  5747. if (indices[index] > 65535) {
  5748. need32Bits = true;
  5749. break;
  5750. }
  5751. }
  5752. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5753. }
  5754. else {
  5755. arrayBuffer = new Uint16Array(indices);
  5756. }
  5757. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5758. this._resetIndexBufferBinding();
  5759. vbo.references = 1;
  5760. vbo.is32Bits = need32Bits;
  5761. return vbo;
  5762. };
  5763. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5764. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5765. this._cachedVertexBuffers = vertexBuffer;
  5766. this._cachedEffectForVertexBuffers = effect;
  5767. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5768. var offset = 0;
  5769. for (var index = 0; index < vertexDeclaration.length; index++) {
  5770. var order = effect.getAttributeLocation(index);
  5771. if (order >= 0) {
  5772. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5773. }
  5774. offset += vertexDeclaration[index] * 4;
  5775. }
  5776. }
  5777. if (this._cachedIndexBuffer !== indexBuffer) {
  5778. this._cachedIndexBuffer = indexBuffer;
  5779. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5780. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5781. }
  5782. };
  5783. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5784. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5785. this._cachedVertexBuffers = vertexBuffers;
  5786. this._cachedEffectForVertexBuffers = effect;
  5787. var attributes = effect.getAttributesNames();
  5788. for (var index = 0; index < attributes.length; index++) {
  5789. var order = effect.getAttributeLocation(index);
  5790. if (order >= 0) {
  5791. var vertexBuffer = vertexBuffers[attributes[index]];
  5792. if (!vertexBuffer) {
  5793. continue;
  5794. }
  5795. var stride = vertexBuffer.getStrideSize();
  5796. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5797. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5798. }
  5799. }
  5800. }
  5801. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5802. this._cachedIndexBuffer = indexBuffer;
  5803. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5804. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5805. }
  5806. };
  5807. Engine.prototype._releaseBuffer = function (buffer) {
  5808. buffer.references--;
  5809. if (buffer.references === 0) {
  5810. this._gl.deleteBuffer(buffer);
  5811. return true;
  5812. }
  5813. return false;
  5814. };
  5815. Engine.prototype.createInstancesBuffer = function (capacity) {
  5816. var buffer = this._gl.createBuffer();
  5817. buffer.capacity = capacity;
  5818. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5819. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5820. return buffer;
  5821. };
  5822. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5823. this._gl.deleteBuffer(buffer);
  5824. };
  5825. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5826. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5827. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5828. for (var index = 0; index < 4; index++) {
  5829. var offsetLocation = offsetLocations[index];
  5830. this._gl.enableVertexAttribArray(offsetLocation);
  5831. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5832. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5833. }
  5834. };
  5835. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5836. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5837. for (var index = 0; index < 4; index++) {
  5838. var offsetLocation = offsetLocations[index];
  5839. this._gl.disableVertexAttribArray(offsetLocation);
  5840. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5841. }
  5842. };
  5843. Engine.prototype.applyStates = function () {
  5844. this._depthCullingState.apply(this._gl);
  5845. this._alphaState.apply(this._gl);
  5846. };
  5847. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5848. // Apply states
  5849. this.applyStates();
  5850. this._drawCalls++;
  5851. // Render
  5852. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5853. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5854. if (instancesCount) {
  5855. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5856. return;
  5857. }
  5858. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5859. };
  5860. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5861. // Apply states
  5862. this.applyStates();
  5863. this._drawCalls++;
  5864. if (instancesCount) {
  5865. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5866. return;
  5867. }
  5868. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5869. };
  5870. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5871. // Apply states
  5872. this.applyStates();
  5873. this._drawCalls++;
  5874. if (instancesCount) {
  5875. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5876. return;
  5877. }
  5878. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5879. };
  5880. // Shaders
  5881. Engine.prototype._releaseEffect = function (effect) {
  5882. if (this._compiledEffects[effect._key]) {
  5883. delete this._compiledEffects[effect._key];
  5884. if (effect.getProgram()) {
  5885. this._gl.deleteProgram(effect.getProgram());
  5886. }
  5887. }
  5888. };
  5889. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5890. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5891. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5892. var name = vertex + "+" + fragment + "@" + defines;
  5893. if (this._compiledEffects[name]) {
  5894. return this._compiledEffects[name];
  5895. }
  5896. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5897. effect._key = name;
  5898. this._compiledEffects[name] = effect;
  5899. return effect;
  5900. };
  5901. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5902. if (uniformsNames === void 0) { uniformsNames = []; }
  5903. if (samplers === void 0) { samplers = []; }
  5904. if (defines === void 0) { defines = ""; }
  5905. return this.createEffect({
  5906. vertex: "particles",
  5907. fragmentElement: fragmentName
  5908. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5909. };
  5910. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5911. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5912. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5913. var shaderProgram = this._gl.createProgram();
  5914. this._gl.attachShader(shaderProgram, vertexShader);
  5915. this._gl.attachShader(shaderProgram, fragmentShader);
  5916. this._gl.linkProgram(shaderProgram);
  5917. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5918. if (!linked) {
  5919. var error = this._gl.getProgramInfoLog(shaderProgram);
  5920. if (error) {
  5921. throw new Error(error);
  5922. }
  5923. }
  5924. this._gl.deleteShader(vertexShader);
  5925. this._gl.deleteShader(fragmentShader);
  5926. return shaderProgram;
  5927. };
  5928. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5929. var results = [];
  5930. for (var index = 0; index < uniformsNames.length; index++) {
  5931. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5932. }
  5933. return results;
  5934. };
  5935. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5936. var results = [];
  5937. for (var index = 0; index < attributesNames.length; index++) {
  5938. try {
  5939. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5940. }
  5941. catch (e) {
  5942. results.push(-1);
  5943. }
  5944. }
  5945. return results;
  5946. };
  5947. Engine.prototype.enableEffect = function (effect) {
  5948. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5949. if (effect && effect.onBind) {
  5950. effect.onBind(effect);
  5951. }
  5952. return;
  5953. }
  5954. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5955. // Use program
  5956. this._gl.useProgram(effect.getProgram());
  5957. for (var i in this._vertexAttribArrays) {
  5958. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5959. continue;
  5960. }
  5961. this._vertexAttribArrays[i] = false;
  5962. this._gl.disableVertexAttribArray(i);
  5963. }
  5964. var attributesCount = effect.getAttributesCount();
  5965. for (var index = 0; index < attributesCount; index++) {
  5966. // Attributes
  5967. var order = effect.getAttributeLocation(index);
  5968. if (order >= 0) {
  5969. this._vertexAttribArrays[order] = true;
  5970. this._gl.enableVertexAttribArray(order);
  5971. }
  5972. }
  5973. this._currentEffect = effect;
  5974. if (effect.onBind) {
  5975. effect.onBind(effect);
  5976. }
  5977. };
  5978. Engine.prototype.setArray = function (uniform, array) {
  5979. if (!uniform)
  5980. return;
  5981. this._gl.uniform1fv(uniform, array);
  5982. };
  5983. Engine.prototype.setArray2 = function (uniform, array) {
  5984. if (!uniform || array.length % 2 !== 0)
  5985. return;
  5986. this._gl.uniform2fv(uniform, array);
  5987. };
  5988. Engine.prototype.setArray3 = function (uniform, array) {
  5989. if (!uniform || array.length % 3 !== 0)
  5990. return;
  5991. this._gl.uniform3fv(uniform, array);
  5992. };
  5993. Engine.prototype.setArray4 = function (uniform, array) {
  5994. if (!uniform || array.length % 4 !== 0)
  5995. return;
  5996. this._gl.uniform4fv(uniform, array);
  5997. };
  5998. Engine.prototype.setMatrices = function (uniform, matrices) {
  5999. if (!uniform)
  6000. return;
  6001. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6002. };
  6003. Engine.prototype.setMatrix = function (uniform, matrix) {
  6004. if (!uniform)
  6005. return;
  6006. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6007. };
  6008. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6009. if (!uniform)
  6010. return;
  6011. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6012. };
  6013. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6014. if (!uniform)
  6015. return;
  6016. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6017. };
  6018. Engine.prototype.setFloat = function (uniform, value) {
  6019. if (!uniform)
  6020. return;
  6021. this._gl.uniform1f(uniform, value);
  6022. };
  6023. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6024. if (!uniform)
  6025. return;
  6026. this._gl.uniform2f(uniform, x, y);
  6027. };
  6028. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6029. if (!uniform)
  6030. return;
  6031. this._gl.uniform3f(uniform, x, y, z);
  6032. };
  6033. Engine.prototype.setBool = function (uniform, bool) {
  6034. if (!uniform)
  6035. return;
  6036. this._gl.uniform1i(uniform, bool);
  6037. };
  6038. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6039. if (!uniform)
  6040. return;
  6041. this._gl.uniform4f(uniform, x, y, z, w);
  6042. };
  6043. Engine.prototype.setColor3 = function (uniform, color3) {
  6044. if (!uniform)
  6045. return;
  6046. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6047. };
  6048. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6049. if (!uniform)
  6050. return;
  6051. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6052. };
  6053. // States
  6054. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6055. if (zOffset === void 0) { zOffset = 0; }
  6056. if (reverseSide === void 0) { reverseSide = false; }
  6057. // Culling
  6058. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6059. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6060. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6061. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6062. if (culling) {
  6063. this._depthCullingState.cullFace = cullFace;
  6064. this._depthCullingState.cull = true;
  6065. }
  6066. else {
  6067. this._depthCullingState.cull = false;
  6068. }
  6069. }
  6070. // Z offset
  6071. this._depthCullingState.zOffset = zOffset;
  6072. };
  6073. Engine.prototype.setDepthBuffer = function (enable) {
  6074. this._depthCullingState.depthTest = enable;
  6075. };
  6076. Engine.prototype.getDepthWrite = function () {
  6077. return this._depthCullingState.depthMask;
  6078. };
  6079. Engine.prototype.setDepthWrite = function (enable) {
  6080. this._depthCullingState.depthMask = enable;
  6081. };
  6082. Engine.prototype.setColorWrite = function (enable) {
  6083. this._gl.colorMask(enable, enable, enable, enable);
  6084. };
  6085. Engine.prototype.setAlphaMode = function (mode) {
  6086. if (this._alphaMode === mode) {
  6087. return;
  6088. }
  6089. switch (mode) {
  6090. case Engine.ALPHA_DISABLE:
  6091. this.setDepthWrite(true);
  6092. this._alphaState.alphaBlend = false;
  6093. break;
  6094. case Engine.ALPHA_COMBINE:
  6095. this.setDepthWrite(false);
  6096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6097. this._alphaState.alphaBlend = true;
  6098. break;
  6099. case Engine.ALPHA_ONEONE:
  6100. this.setDepthWrite(false);
  6101. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6102. this._alphaState.alphaBlend = true;
  6103. break;
  6104. case Engine.ALPHA_ADD:
  6105. this.setDepthWrite(false);
  6106. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6107. this._alphaState.alphaBlend = true;
  6108. break;
  6109. case Engine.ALPHA_SUBTRACT:
  6110. this.setDepthWrite(false);
  6111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6112. this._alphaState.alphaBlend = true;
  6113. break;
  6114. case Engine.ALPHA_MULTIPLY:
  6115. this.setDepthWrite(false);
  6116. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6117. this._alphaState.alphaBlend = true;
  6118. break;
  6119. case Engine.ALPHA_MAXIMIZED:
  6120. this.setDepthWrite(false);
  6121. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6122. this._alphaState.alphaBlend = true;
  6123. break;
  6124. }
  6125. this._alphaMode = mode;
  6126. };
  6127. Engine.prototype.getAlphaMode = function () {
  6128. return this._alphaMode;
  6129. };
  6130. Engine.prototype.setAlphaTesting = function (enable) {
  6131. this._alphaTest = enable;
  6132. };
  6133. Engine.prototype.getAlphaTesting = function () {
  6134. return this._alphaTest;
  6135. };
  6136. // Textures
  6137. Engine.prototype.wipeCaches = function () {
  6138. this.resetTextureCache();
  6139. this._currentEffect = null;
  6140. this._depthCullingState.reset();
  6141. this._alphaState.reset();
  6142. this._cachedVertexBuffers = null;
  6143. this._cachedIndexBuffer = null;
  6144. this._cachedEffectForVertexBuffers = null;
  6145. };
  6146. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6147. var gl = this._gl;
  6148. gl.bindTexture(gl.TEXTURE_2D, texture);
  6149. var magFilter = gl.NEAREST;
  6150. var minFilter = gl.NEAREST;
  6151. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6152. magFilter = gl.LINEAR;
  6153. minFilter = gl.LINEAR;
  6154. }
  6155. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6156. magFilter = gl.LINEAR;
  6157. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6158. }
  6159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6161. gl.bindTexture(gl.TEXTURE_2D, null);
  6162. texture.samplingMode = samplingMode;
  6163. };
  6164. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6165. var _this = this;
  6166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6167. if (onLoad === void 0) { onLoad = null; }
  6168. if (onError === void 0) { onError = null; }
  6169. if (buffer === void 0) { buffer = null; }
  6170. var texture = this._gl.createTexture();
  6171. var extension;
  6172. var fromData = false;
  6173. if (url.substr(0, 5) === "data:") {
  6174. fromData = true;
  6175. }
  6176. if (!fromData)
  6177. extension = url.substr(url.length - 4, 4).toLowerCase();
  6178. else {
  6179. var oldUrl = url;
  6180. fromData = oldUrl.split(':');
  6181. url = oldUrl;
  6182. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6183. }
  6184. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6185. var isTGA = (extension === ".tga");
  6186. scene._addPendingData(texture);
  6187. texture.url = url;
  6188. texture.noMipmap = noMipmap;
  6189. texture.references = 1;
  6190. texture.samplingMode = samplingMode;
  6191. this._loadedTexturesCache.push(texture);
  6192. var onerror = function () {
  6193. scene._removePendingData(texture);
  6194. if (onError) {
  6195. onError();
  6196. }
  6197. };
  6198. var callback;
  6199. if (isTGA) {
  6200. callback = function (arrayBuffer) {
  6201. var data = new Uint8Array(arrayBuffer);
  6202. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6203. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6204. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6205. if (onLoad) {
  6206. onLoad();
  6207. }
  6208. }, samplingMode);
  6209. };
  6210. if (!(fromData instanceof Array))
  6211. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6212. callback(arrayBuffer);
  6213. }, onerror, scene.database, true);
  6214. else
  6215. callback(buffer);
  6216. }
  6217. else if (isDDS) {
  6218. callback = function (data) {
  6219. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6220. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6221. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6222. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6223. if (onLoad) {
  6224. onLoad();
  6225. }
  6226. }, samplingMode);
  6227. };
  6228. if (!(fromData instanceof Array))
  6229. BABYLON.Tools.LoadFile(url, function (data) {
  6230. callback(data);
  6231. }, onerror, scene.database, true);
  6232. else
  6233. callback(buffer);
  6234. }
  6235. else {
  6236. var onload = function (img) {
  6237. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6238. var isPot = (img.width === potWidth && img.height === potHeight);
  6239. if (!isPot) {
  6240. _this._prepareWorkingCanvas();
  6241. _this._workingCanvas.width = potWidth;
  6242. _this._workingCanvas.height = potHeight;
  6243. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6244. _this._workingContext.imageSmoothingEnabled = false;
  6245. _this._workingContext.mozImageSmoothingEnabled = false;
  6246. _this._workingContext.oImageSmoothingEnabled = false;
  6247. _this._workingContext.webkitImageSmoothingEnabled = false;
  6248. _this._workingContext.msImageSmoothingEnabled = false;
  6249. }
  6250. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6251. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6252. _this._workingContext.imageSmoothingEnabled = true;
  6253. _this._workingContext.mozImageSmoothingEnabled = true;
  6254. _this._workingContext.oImageSmoothingEnabled = true;
  6255. _this._workingContext.webkitImageSmoothingEnabled = true;
  6256. _this._workingContext.msImageSmoothingEnabled = true;
  6257. }
  6258. }
  6259. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6260. if (onLoad) {
  6261. onLoad();
  6262. }
  6263. }, samplingMode);
  6264. };
  6265. if (!(fromData instanceof Array))
  6266. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6267. else
  6268. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6269. }
  6270. return texture;
  6271. };
  6272. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6273. if (compression === void 0) { compression = null; }
  6274. var internalFormat = this._gl.RGBA;
  6275. switch (format) {
  6276. case Engine.TEXTUREFORMAT_ALPHA:
  6277. internalFormat = this._gl.ALPHA;
  6278. break;
  6279. case Engine.TEXTUREFORMAT_LUMINANCE:
  6280. internalFormat = this._gl.LUMINANCE;
  6281. break;
  6282. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6283. internalFormat = this._gl.LUMINANCE_ALPHA;
  6284. break;
  6285. case Engine.TEXTUREFORMAT_RGB:
  6286. internalFormat = this._gl.RGB;
  6287. break;
  6288. case Engine.TEXTUREFORMAT_RGBA:
  6289. internalFormat = this._gl.RGBA;
  6290. break;
  6291. }
  6292. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6293. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6294. if (compression) {
  6295. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6296. }
  6297. else {
  6298. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6299. }
  6300. if (texture.generateMipMaps) {
  6301. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6302. }
  6303. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6304. this.resetTextureCache();
  6305. texture.isReady = true;
  6306. };
  6307. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6308. if (compression === void 0) { compression = null; }
  6309. var texture = this._gl.createTexture();
  6310. texture._baseWidth = width;
  6311. texture._baseHeight = height;
  6312. texture._width = width;
  6313. texture._height = height;
  6314. texture.references = 1;
  6315. this.updateRawTexture(texture, data, format, invertY, compression);
  6316. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6317. // Filters
  6318. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6322. texture.samplingMode = samplingMode;
  6323. this._loadedTexturesCache.push(texture);
  6324. return texture;
  6325. };
  6326. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6327. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6328. var texture = this._gl.createTexture();
  6329. texture._baseWidth = width;
  6330. texture._baseHeight = height;
  6331. if (forceExponantOfTwo) {
  6332. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6333. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6334. }
  6335. this.resetTextureCache();
  6336. texture._width = width;
  6337. texture._height = height;
  6338. texture.isReady = false;
  6339. texture.generateMipMaps = generateMipMaps;
  6340. texture.references = 1;
  6341. texture.samplingMode = samplingMode;
  6342. this.updateTextureSamplingMode(samplingMode, texture);
  6343. this._loadedTexturesCache.push(texture);
  6344. return texture;
  6345. };
  6346. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6347. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6348. if (texture.isCube) {
  6349. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6350. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6351. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6352. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6353. }
  6354. else {
  6355. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6356. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6357. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6358. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6359. }
  6360. };
  6361. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6362. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6363. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6365. if (texture.generateMipMaps) {
  6366. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6367. }
  6368. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6369. this.resetTextureCache();
  6370. texture.isReady = true;
  6371. };
  6372. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6373. if (texture._isDisabled) {
  6374. return;
  6375. }
  6376. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6378. try {
  6379. // Testing video texture support
  6380. if (this._videoTextureSupported === undefined) {
  6381. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6382. if (this._gl.getError() !== 0) {
  6383. this._videoTextureSupported = false;
  6384. }
  6385. else {
  6386. this._videoTextureSupported = true;
  6387. }
  6388. }
  6389. // Copy video through the current working canvas if video texture is not supported
  6390. if (!this._videoTextureSupported) {
  6391. if (!texture._workingCanvas) {
  6392. texture._workingCanvas = document.createElement("canvas");
  6393. texture._workingContext = texture._workingCanvas.getContext("2d");
  6394. texture._workingCanvas.width = texture._width;
  6395. texture._workingCanvas.height = texture._height;
  6396. }
  6397. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6398. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6399. }
  6400. else {
  6401. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6402. }
  6403. if (texture.generateMipMaps) {
  6404. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6405. }
  6406. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6407. this.resetTextureCache();
  6408. texture.isReady = true;
  6409. }
  6410. catch (ex) {
  6411. // Something unexpected
  6412. // Let's disable the texture
  6413. texture._isDisabled = true;
  6414. }
  6415. };
  6416. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6417. // old version had a "generateMipMaps" arg instead of options.
  6418. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6419. // in the same way, generateDepthBuffer is defaulted to true
  6420. var generateMipMaps = false;
  6421. var generateDepthBuffer = true;
  6422. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6423. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6424. if (options !== undefined) {
  6425. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6426. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6427. type = options.type === undefined ? type : options.type;
  6428. if (options.samplingMode !== undefined) {
  6429. samplingMode = options.samplingMode;
  6430. }
  6431. if (type === Engine.TEXTURETYPE_FLOAT) {
  6432. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6433. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6434. }
  6435. }
  6436. var gl = this._gl;
  6437. var texture = gl.createTexture();
  6438. gl.bindTexture(gl.TEXTURE_2D, texture);
  6439. var width = size.width || size;
  6440. var height = size.height || size;
  6441. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6442. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6443. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6444. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6445. }
  6446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6450. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6451. var depthBuffer;
  6452. // Create the depth buffer
  6453. if (generateDepthBuffer) {
  6454. depthBuffer = gl.createRenderbuffer();
  6455. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6456. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6457. }
  6458. // Create the framebuffer
  6459. var framebuffer = gl.createFramebuffer();
  6460. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6461. if (generateDepthBuffer) {
  6462. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6463. }
  6464. if (generateMipMaps) {
  6465. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6466. }
  6467. // Unbind
  6468. gl.bindTexture(gl.TEXTURE_2D, null);
  6469. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6470. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6471. texture._framebuffer = framebuffer;
  6472. if (generateDepthBuffer) {
  6473. texture._depthBuffer = depthBuffer;
  6474. }
  6475. texture._width = width;
  6476. texture._height = height;
  6477. texture.isReady = true;
  6478. texture.generateMipMaps = generateMipMaps;
  6479. texture.references = 1;
  6480. texture.samplingMode = samplingMode;
  6481. this.resetTextureCache();
  6482. this._loadedTexturesCache.push(texture);
  6483. return texture;
  6484. };
  6485. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6486. var gl = this._gl;
  6487. var texture = gl.createTexture();
  6488. var generateMipMaps = true;
  6489. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6490. if (options !== undefined) {
  6491. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6492. if (options.samplingMode !== undefined) {
  6493. samplingMode = options.samplingMode;
  6494. }
  6495. }
  6496. texture.isCube = true;
  6497. texture.references = 1;
  6498. texture.generateMipMaps = generateMipMaps;
  6499. texture.references = 1;
  6500. texture.samplingMode = samplingMode;
  6501. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6502. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6503. for (var face = 0; face < 6; face++) {
  6504. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6505. }
  6506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6510. // Create the depth buffer
  6511. var depthBuffer = gl.createRenderbuffer();
  6512. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6513. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6514. // Create the framebuffer
  6515. var framebuffer = gl.createFramebuffer();
  6516. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6517. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6518. // mipmaps
  6519. if (texture.generateMipMaps) {
  6520. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6521. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6522. }
  6523. // Unbind
  6524. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6525. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6526. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6527. texture._framebuffer = framebuffer;
  6528. texture._depthBuffer = depthBuffer;
  6529. this.resetTextureCache();
  6530. texture._width = size;
  6531. texture._height = size;
  6532. texture.isReady = true;
  6533. return texture;
  6534. };
  6535. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6536. var _this = this;
  6537. var gl = this._gl;
  6538. var texture = gl.createTexture();
  6539. texture.isCube = true;
  6540. texture.url = rootUrl;
  6541. texture.references = 1;
  6542. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6543. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6544. if (isDDS) {
  6545. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6546. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6547. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6548. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6549. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6550. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6551. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6552. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6553. }
  6554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6558. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6559. _this.resetTextureCache();
  6560. texture._width = info.width;
  6561. texture._height = info.height;
  6562. texture.isReady = true;
  6563. }, null, null, true);
  6564. }
  6565. else {
  6566. cascadeLoad(rootUrl, scene, function (imgs) {
  6567. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6568. var height = width;
  6569. _this._prepareWorkingCanvas();
  6570. _this._workingCanvas.width = width;
  6571. _this._workingCanvas.height = height;
  6572. var faces = [
  6573. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6574. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6575. ];
  6576. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6577. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6578. for (var index = 0; index < faces.length; index++) {
  6579. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6580. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6581. }
  6582. if (!noMipmap) {
  6583. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6584. }
  6585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6589. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6590. _this.resetTextureCache();
  6591. texture._width = width;
  6592. texture._height = height;
  6593. texture.isReady = true;
  6594. }, extensions);
  6595. }
  6596. return texture;
  6597. };
  6598. Engine.prototype._releaseTexture = function (texture) {
  6599. var gl = this._gl;
  6600. if (texture._framebuffer) {
  6601. gl.deleteFramebuffer(texture._framebuffer);
  6602. }
  6603. if (texture._depthBuffer) {
  6604. gl.deleteRenderbuffer(texture._depthBuffer);
  6605. }
  6606. gl.deleteTexture(texture);
  6607. // Unbind channels
  6608. this.unbindAllTextures();
  6609. var index = this._loadedTexturesCache.indexOf(texture);
  6610. if (index !== -1) {
  6611. this._loadedTexturesCache.splice(index, 1);
  6612. }
  6613. };
  6614. Engine.prototype.bindSamplers = function (effect) {
  6615. this._gl.useProgram(effect.getProgram());
  6616. var samplers = effect.getSamplers();
  6617. for (var index = 0; index < samplers.length; index++) {
  6618. var uniform = effect.getUniform(samplers[index]);
  6619. this._gl.uniform1i(uniform, index);
  6620. }
  6621. this._currentEffect = null;
  6622. };
  6623. Engine.prototype._bindTexture = function (channel, texture) {
  6624. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6625. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6626. this._activeTexturesCache[channel] = null;
  6627. };
  6628. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6629. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6630. };
  6631. Engine.prototype.unbindAllTextures = function () {
  6632. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6633. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6634. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6635. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6636. this._activeTexturesCache[channel] = null;
  6637. }
  6638. };
  6639. Engine.prototype.setTexture = function (channel, texture) {
  6640. if (channel < 0) {
  6641. return;
  6642. }
  6643. // Not ready?
  6644. if (!texture || !texture.isReady()) {
  6645. if (this._activeTexturesCache[channel] != null) {
  6646. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6648. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6649. this._activeTexturesCache[channel] = null;
  6650. }
  6651. return;
  6652. }
  6653. // Video
  6654. var alreadyActivated = false;
  6655. if (texture instanceof BABYLON.VideoTexture) {
  6656. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6657. alreadyActivated = true;
  6658. texture.update();
  6659. }
  6660. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6661. texture.delayLoad();
  6662. return;
  6663. }
  6664. if (this._activeTexturesCache[channel] === texture) {
  6665. return;
  6666. }
  6667. this._activeTexturesCache[channel] = texture;
  6668. var internalTexture = texture.getInternalTexture();
  6669. if (!alreadyActivated) {
  6670. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6671. }
  6672. if (internalTexture.isCube) {
  6673. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6674. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6675. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6676. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6677. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6678. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6679. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6680. }
  6681. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6682. }
  6683. else {
  6684. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6685. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6686. internalTexture._cachedWrapU = texture.wrapU;
  6687. switch (texture.wrapU) {
  6688. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6689. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6690. break;
  6691. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6693. break;
  6694. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6696. break;
  6697. }
  6698. }
  6699. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6700. internalTexture._cachedWrapV = texture.wrapV;
  6701. switch (texture.wrapV) {
  6702. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6703. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6704. break;
  6705. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6707. break;
  6708. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6710. break;
  6711. }
  6712. }
  6713. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6714. }
  6715. };
  6716. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6717. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6718. var value = texture.anisotropicFilteringLevel;
  6719. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6720. value = 1;
  6721. }
  6722. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6723. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6724. texture._cachedAnisotropicFilteringLevel = value;
  6725. }
  6726. };
  6727. Engine.prototype.readPixels = function (x, y, width, height) {
  6728. var data = new Uint8Array(height * width * 4);
  6729. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6730. return data;
  6731. };
  6732. Engine.prototype.releaseInternalTexture = function (texture) {
  6733. if (!texture) {
  6734. return;
  6735. }
  6736. texture.references--;
  6737. // Final reference ?
  6738. if (texture.references === 0) {
  6739. var texturesCache = this.getLoadedTexturesCache();
  6740. var index = texturesCache.indexOf(texture);
  6741. if (index > -1) {
  6742. texturesCache.splice(index, 1);
  6743. }
  6744. this._releaseTexture(texture);
  6745. }
  6746. };
  6747. // Dispose
  6748. Engine.prototype.dispose = function () {
  6749. this.hideLoadingUI();
  6750. this.stopRenderLoop();
  6751. // Release scenes
  6752. while (this.scenes.length) {
  6753. this.scenes[0].dispose();
  6754. }
  6755. // Release audio engine
  6756. Engine.audioEngine.dispose();
  6757. // Release effects
  6758. for (var name in this._compiledEffects) {
  6759. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6760. }
  6761. // Unbind
  6762. for (var i in this._vertexAttribArrays) {
  6763. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6764. continue;
  6765. }
  6766. this._gl.disableVertexAttribArray(i);
  6767. }
  6768. this._gl = null;
  6769. // Events
  6770. window.removeEventListener("blur", this._onBlur);
  6771. window.removeEventListener("focus", this._onFocus);
  6772. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6773. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6774. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6775. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6776. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6777. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6778. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6779. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6780. };
  6781. // Loading screen
  6782. Engine.prototype.displayLoadingUI = function () {
  6783. this._loadingScreen.displayLoadingUI();
  6784. };
  6785. Engine.prototype.hideLoadingUI = function () {
  6786. this._loadingScreen.hideLoadingUI();
  6787. };
  6788. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6789. get: function () {
  6790. return this._loadingScreen;
  6791. },
  6792. set: function (loadingScreen) {
  6793. this._loadingScreen = loadingScreen;
  6794. },
  6795. enumerable: true,
  6796. configurable: true
  6797. });
  6798. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6799. set: function (text) {
  6800. this._loadingScreen.loadingUIText = text;
  6801. },
  6802. enumerable: true,
  6803. configurable: true
  6804. });
  6805. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6806. set: function (color) {
  6807. this._loadingScreen.loadingUIBackgroundColor = color;
  6808. },
  6809. enumerable: true,
  6810. configurable: true
  6811. });
  6812. // FPS
  6813. Engine.prototype.getFps = function () {
  6814. return this.fps;
  6815. };
  6816. Engine.prototype.getDeltaTime = function () {
  6817. return this.deltaTime;
  6818. };
  6819. Engine.prototype._measureFps = function () {
  6820. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6821. var length = this.previousFramesDuration.length;
  6822. if (length >= 2) {
  6823. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6824. }
  6825. if (length >= this.fpsRange) {
  6826. if (length > this.fpsRange) {
  6827. this.previousFramesDuration.splice(0, 1);
  6828. length = this.previousFramesDuration.length;
  6829. }
  6830. var sum = 0;
  6831. for (var id = 0; id < length - 1; id++) {
  6832. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6833. }
  6834. this.fps = 1000.0 / (sum / (length - 1));
  6835. }
  6836. };
  6837. // Statics
  6838. Engine.isSupported = function () {
  6839. try {
  6840. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6841. if (navigator.isCocoonJS) {
  6842. return true;
  6843. }
  6844. var tempcanvas = document.createElement("canvas");
  6845. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6846. return gl != null && !!window.WebGLRenderingContext;
  6847. }
  6848. catch (e) {
  6849. return false;
  6850. }
  6851. };
  6852. // Const statics
  6853. Engine._ALPHA_DISABLE = 0;
  6854. Engine._ALPHA_ADD = 1;
  6855. Engine._ALPHA_COMBINE = 2;
  6856. Engine._ALPHA_SUBTRACT = 3;
  6857. Engine._ALPHA_MULTIPLY = 4;
  6858. Engine._ALPHA_MAXIMIZED = 5;
  6859. Engine._ALPHA_ONEONE = 6;
  6860. Engine._DELAYLOADSTATE_NONE = 0;
  6861. Engine._DELAYLOADSTATE_LOADED = 1;
  6862. Engine._DELAYLOADSTATE_LOADING = 2;
  6863. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6864. Engine._TEXTUREFORMAT_ALPHA = 0;
  6865. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6866. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6867. Engine._TEXTUREFORMAT_RGB = 4;
  6868. Engine._TEXTUREFORMAT_RGBA = 5;
  6869. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6870. Engine._TEXTURETYPE_FLOAT = 1;
  6871. // Updatable statics so stick with vars here
  6872. Engine.Epsilon = 0.001;
  6873. Engine.CollisionsEpsilon = 0.001;
  6874. Engine.CodeRepository = "src/";
  6875. Engine.ShadersRepository = "src/Shaders/";
  6876. return Engine;
  6877. })();
  6878. BABYLON.Engine = Engine;
  6879. })(BABYLON || (BABYLON = {}));
  6880. var BABYLON;
  6881. (function (BABYLON) {
  6882. /**
  6883. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6884. */
  6885. var Node = (function () {
  6886. /**
  6887. * @constructor
  6888. * @param {string} name - the name and id to be given to this node
  6889. * @param {BABYLON.Scene} the scene this node will be added to
  6890. */
  6891. function Node(name, scene) {
  6892. this.state = "";
  6893. this.animations = new Array();
  6894. this._ranges = {};
  6895. this._childrenFlag = -1;
  6896. this._isEnabled = true;
  6897. this._isReady = true;
  6898. this._currentRenderId = -1;
  6899. this._parentRenderId = -1;
  6900. this.name = name;
  6901. this.id = name;
  6902. this._scene = scene;
  6903. this._initCache();
  6904. }
  6905. Node.prototype.getScene = function () {
  6906. return this._scene;
  6907. };
  6908. Node.prototype.getEngine = function () {
  6909. return this._scene.getEngine();
  6910. };
  6911. // override it in derived class
  6912. Node.prototype.getWorldMatrix = function () {
  6913. return BABYLON.Matrix.Identity();
  6914. };
  6915. // override it in derived class if you add new variables to the cache
  6916. // and call the parent class method
  6917. Node.prototype._initCache = function () {
  6918. this._cache = {};
  6919. this._cache.parent = undefined;
  6920. };
  6921. Node.prototype.updateCache = function (force) {
  6922. if (!force && this.isSynchronized())
  6923. return;
  6924. this._cache.parent = this.parent;
  6925. this._updateCache();
  6926. };
  6927. // override it in derived class if you add new variables to the cache
  6928. // and call the parent class method if !ignoreParentClass
  6929. Node.prototype._updateCache = function (ignoreParentClass) {
  6930. };
  6931. // override it in derived class if you add new variables to the cache
  6932. Node.prototype._isSynchronized = function () {
  6933. return true;
  6934. };
  6935. Node.prototype._markSyncedWithParent = function () {
  6936. this._parentRenderId = this.parent._currentRenderId;
  6937. };
  6938. Node.prototype.isSynchronizedWithParent = function () {
  6939. if (!this.parent) {
  6940. return true;
  6941. }
  6942. if (this._parentRenderId !== this.parent._currentRenderId) {
  6943. return false;
  6944. }
  6945. return this.parent.isSynchronized();
  6946. };
  6947. Node.prototype.isSynchronized = function (updateCache) {
  6948. var check = this.hasNewParent();
  6949. check = check || !this.isSynchronizedWithParent();
  6950. check = check || !this._isSynchronized();
  6951. if (updateCache)
  6952. this.updateCache(true);
  6953. return !check;
  6954. };
  6955. Node.prototype.hasNewParent = function (update) {
  6956. if (this._cache.parent === this.parent)
  6957. return false;
  6958. if (update)
  6959. this._cache.parent = this.parent;
  6960. return true;
  6961. };
  6962. /**
  6963. * Is this node ready to be used/rendered
  6964. * @return {boolean} is it ready
  6965. */
  6966. Node.prototype.isReady = function () {
  6967. return this._isReady;
  6968. };
  6969. /**
  6970. * Is this node enabled.
  6971. * If the node has a parent and is enabled, the parent will be inspected as well.
  6972. * @return {boolean} whether this node (and its parent) is enabled.
  6973. * @see setEnabled
  6974. */
  6975. Node.prototype.isEnabled = function () {
  6976. if (!this._isEnabled) {
  6977. return false;
  6978. }
  6979. if (this.parent) {
  6980. return this.parent.isEnabled();
  6981. }
  6982. return true;
  6983. };
  6984. /**
  6985. * Set the enabled state of this node.
  6986. * @param {boolean} value - the new enabled state
  6987. * @see isEnabled
  6988. */
  6989. Node.prototype.setEnabled = function (value) {
  6990. this._isEnabled = value;
  6991. };
  6992. /**
  6993. * Is this node a descendant of the given node.
  6994. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6995. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6996. * @see parent
  6997. */
  6998. Node.prototype.isDescendantOf = function (ancestor) {
  6999. if (this.parent) {
  7000. if (this.parent === ancestor) {
  7001. return true;
  7002. }
  7003. return this.parent.isDescendantOf(ancestor);
  7004. }
  7005. return false;
  7006. };
  7007. Node.prototype._getDescendants = function (list, results) {
  7008. for (var index = 0; index < list.length; index++) {
  7009. var item = list[index];
  7010. if (item.isDescendantOf(this)) {
  7011. results.push(item);
  7012. }
  7013. }
  7014. };
  7015. /**
  7016. * Will return all nodes that have this node as parent.
  7017. * @return {BABYLON.Node[]} all children nodes of all types.
  7018. */
  7019. Node.prototype.getDescendants = function () {
  7020. var results = [];
  7021. this._getDescendants(this._scene.meshes, results);
  7022. this._getDescendants(this._scene.lights, results);
  7023. this._getDescendants(this._scene.cameras, results);
  7024. return results;
  7025. };
  7026. Node.prototype._setReady = function (state) {
  7027. if (state === this._isReady) {
  7028. return;
  7029. }
  7030. if (!state) {
  7031. this._isReady = false;
  7032. return;
  7033. }
  7034. this._isReady = true;
  7035. if (this.onReady) {
  7036. this.onReady(this);
  7037. }
  7038. };
  7039. Node.prototype.getAnimationByName = function (name) {
  7040. for (var i = 0; i < this.animations.length; i++) {
  7041. var animation = this.animations[i];
  7042. if (animation.name === name) {
  7043. return animation;
  7044. }
  7045. }
  7046. return null;
  7047. };
  7048. Node.prototype.createAnimationRange = function (name, from, to) {
  7049. // check name not already in use
  7050. if (!this._ranges[name]) {
  7051. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7052. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7053. if (this.animations[i]) {
  7054. this.animations[i].createRange(name, from, to);
  7055. }
  7056. }
  7057. }
  7058. };
  7059. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7060. if (deleteFrames === void 0) { deleteFrames = true; }
  7061. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7062. if (this.animations[i]) {
  7063. this.animations[i].deleteRange(name, deleteFrames);
  7064. }
  7065. }
  7066. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7067. };
  7068. Node.prototype.getAnimationRange = function (name) {
  7069. return this._ranges[name];
  7070. };
  7071. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7072. var range = this.getAnimationRange(name);
  7073. if (!range) {
  7074. return null;
  7075. }
  7076. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7077. };
  7078. Node.prototype.serializeAnimationRanges = function () {
  7079. var serializationRanges = [];
  7080. for (var name in this._ranges) {
  7081. var range = {};
  7082. range.name = name;
  7083. range.from = this._ranges[name].from;
  7084. range.to = this._ranges[name].to;
  7085. serializationRanges.push(range);
  7086. }
  7087. return serializationRanges;
  7088. };
  7089. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7090. if (parsedNode.ranges) {
  7091. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7092. var data = parsedNode.ranges[index];
  7093. node.createAnimationRange(data.name, data.from, data.to);
  7094. }
  7095. }
  7096. };
  7097. return Node;
  7098. })();
  7099. BABYLON.Node = Node;
  7100. })(BABYLON || (BABYLON = {}));
  7101. var BABYLON;
  7102. (function (BABYLON) {
  7103. var FilesInput = (function () {
  7104. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7105. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7106. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7107. this._engine = p_engine;
  7108. this._canvas = p_canvas;
  7109. this._currentScene = p_scene;
  7110. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7111. this._progressCallback = p_progressCallback;
  7112. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7113. this._textureLoadingCallback = p_textureLoadingCallback;
  7114. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7115. }
  7116. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7117. var _this = this;
  7118. if (p_elementToMonitor) {
  7119. this._elementToMonitor = p_elementToMonitor;
  7120. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7121. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7122. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7123. }
  7124. };
  7125. FilesInput.prototype.renderFunction = function () {
  7126. if (this._additionnalRenderLoopLogicCallback) {
  7127. this._additionnalRenderLoopLogicCallback();
  7128. }
  7129. if (this._currentScene) {
  7130. if (this._textureLoadingCallback) {
  7131. var remaining = this._currentScene.getWaitingItemsCount();
  7132. if (remaining > 0) {
  7133. this._textureLoadingCallback(remaining);
  7134. }
  7135. }
  7136. this._currentScene.render();
  7137. }
  7138. };
  7139. FilesInput.prototype.drag = function (e) {
  7140. e.stopPropagation();
  7141. e.preventDefault();
  7142. };
  7143. FilesInput.prototype.drop = function (eventDrop) {
  7144. eventDrop.stopPropagation();
  7145. eventDrop.preventDefault();
  7146. this.loadFiles(eventDrop);
  7147. };
  7148. FilesInput.prototype.loadFiles = function (event) {
  7149. if (this._startingProcessingFilesCallback)
  7150. this._startingProcessingFilesCallback();
  7151. // Handling data transfer via drag'n'drop
  7152. if (event && event.dataTransfer && event.dataTransfer.files) {
  7153. this._filesToLoad = event.dataTransfer.files;
  7154. }
  7155. // Handling files from input files
  7156. if (event && event.target && event.target.files) {
  7157. this._filesToLoad = event.target.files;
  7158. }
  7159. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7160. for (var i = 0; i < this._filesToLoad.length; i++) {
  7161. switch (this._filesToLoad[i].type) {
  7162. case "image/jpeg":
  7163. case "image/png":
  7164. case "image/bmp":
  7165. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7166. break;
  7167. case "image/targa":
  7168. case "image/vnd.ms-dds":
  7169. case "audio/wav":
  7170. case "audio/x-wav":
  7171. case "audio/mp3":
  7172. case "audio/mpeg":
  7173. case "audio/mpeg3":
  7174. case "audio/x-mpeg-3":
  7175. case "audio/ogg":
  7176. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7177. break;
  7178. default:
  7179. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7180. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7181. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7182. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7183. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7184. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7185. this._sceneFileToLoad = this._filesToLoad[i];
  7186. }
  7187. break;
  7188. }
  7189. }
  7190. this.reload();
  7191. }
  7192. };
  7193. FilesInput.prototype.reload = function () {
  7194. var _this = this;
  7195. var that = this;
  7196. // If a ".babylon" file has been provided
  7197. if (this._sceneFileToLoad) {
  7198. if (this._currentScene) {
  7199. if (BABYLON.Tools.errorsCount > 0) {
  7200. BABYLON.Tools.ClearLogCache();
  7201. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7202. }
  7203. this._engine.stopRenderLoop();
  7204. this._currentScene.dispose();
  7205. }
  7206. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7207. that._currentScene = newScene;
  7208. // Wait for textures and shaders to be ready
  7209. that._currentScene.executeWhenReady(function () {
  7210. // Attach camera to canvas inputs
  7211. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7212. that._currentScene.createDefaultCameraOrLight();
  7213. }
  7214. that._currentScene.activeCamera.attachControl(that._canvas);
  7215. if (that._sceneLoadedCallback) {
  7216. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7217. }
  7218. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7219. });
  7220. }, function (progress) {
  7221. if (_this._progressCallback) {
  7222. _this._progressCallback(progress);
  7223. }
  7224. });
  7225. }
  7226. else {
  7227. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7228. }
  7229. };
  7230. FilesInput.FilesTextures = new Array();
  7231. FilesInput.FilesToLoad = new Array();
  7232. return FilesInput;
  7233. })();
  7234. BABYLON.FilesInput = FilesInput;
  7235. })(BABYLON || (BABYLON = {}));
  7236. var BABYLON;
  7237. (function (BABYLON) {
  7238. var IntersectionInfo = (function () {
  7239. function IntersectionInfo(bu, bv, distance) {
  7240. this.bu = bu;
  7241. this.bv = bv;
  7242. this.distance = distance;
  7243. this.faceId = 0;
  7244. this.subMeshId = 0;
  7245. }
  7246. return IntersectionInfo;
  7247. })();
  7248. BABYLON.IntersectionInfo = IntersectionInfo;
  7249. var PickingInfo = (function () {
  7250. function PickingInfo() {
  7251. this.hit = false;
  7252. this.distance = 0;
  7253. this.pickedPoint = null;
  7254. this.pickedMesh = null;
  7255. this.bu = 0;
  7256. this.bv = 0;
  7257. this.faceId = -1;
  7258. this.subMeshId = 0;
  7259. this.pickedSprite = null;
  7260. }
  7261. // Methods
  7262. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7263. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7264. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7265. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7266. return null;
  7267. }
  7268. var indices = this.pickedMesh.getIndices();
  7269. var result;
  7270. if (useVerticesNormals) {
  7271. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7272. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7273. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7274. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7275. normal0 = normal0.scale(this.bu);
  7276. normal1 = normal1.scale(this.bv);
  7277. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7278. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7279. }
  7280. else {
  7281. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7282. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7283. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7284. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7285. var p1p2 = vertex1.subtract(vertex2);
  7286. var p3p2 = vertex3.subtract(vertex2);
  7287. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7288. }
  7289. if (useWorldCoordinates) {
  7290. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7291. }
  7292. return BABYLON.Vector3.Normalize(result);
  7293. };
  7294. PickingInfo.prototype.getTextureCoordinates = function () {
  7295. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7296. return null;
  7297. }
  7298. var indices = this.pickedMesh.getIndices();
  7299. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7300. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7301. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7302. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7303. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7304. uv1 = uv1.scale(this.bu);
  7305. uv2 = uv2.scale(this.bv);
  7306. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7307. };
  7308. return PickingInfo;
  7309. })();
  7310. BABYLON.PickingInfo = PickingInfo;
  7311. })(BABYLON || (BABYLON = {}));
  7312. var BABYLON;
  7313. (function (BABYLON) {
  7314. var BoundingSphere = (function () {
  7315. function BoundingSphere(minimum, maximum) {
  7316. this.minimum = minimum;
  7317. this.maximum = maximum;
  7318. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7319. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7320. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7321. this.radius = distance * 0.5;
  7322. this.centerWorld = BABYLON.Vector3.Zero();
  7323. this._update(BABYLON.Matrix.Identity());
  7324. }
  7325. // Methods
  7326. BoundingSphere.prototype._update = function (world) {
  7327. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7328. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7329. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7330. };
  7331. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7332. for (var i = 0; i < 6; i++) {
  7333. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7334. return false;
  7335. }
  7336. return true;
  7337. };
  7338. BoundingSphere.prototype.intersectsPoint = function (point) {
  7339. var x = this.centerWorld.x - point.x;
  7340. var y = this.centerWorld.y - point.y;
  7341. var z = this.centerWorld.z - point.z;
  7342. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7343. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7344. return false;
  7345. return true;
  7346. };
  7347. // Statics
  7348. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7349. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7350. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7351. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7352. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7353. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7354. return false;
  7355. return true;
  7356. };
  7357. return BoundingSphere;
  7358. })();
  7359. BABYLON.BoundingSphere = BoundingSphere;
  7360. })(BABYLON || (BABYLON = {}));
  7361. var BABYLON;
  7362. (function (BABYLON) {
  7363. var BoundingBox = (function () {
  7364. function BoundingBox(minimum, maximum) {
  7365. this.minimum = minimum;
  7366. this.maximum = maximum;
  7367. this.vectors = new Array();
  7368. this.vectorsWorld = new Array();
  7369. // Bounding vectors
  7370. this.vectors.push(this.minimum.clone());
  7371. this.vectors.push(this.maximum.clone());
  7372. this.vectors.push(this.minimum.clone());
  7373. this.vectors[2].x = this.maximum.x;
  7374. this.vectors.push(this.minimum.clone());
  7375. this.vectors[3].y = this.maximum.y;
  7376. this.vectors.push(this.minimum.clone());
  7377. this.vectors[4].z = this.maximum.z;
  7378. this.vectors.push(this.maximum.clone());
  7379. this.vectors[5].z = this.minimum.z;
  7380. this.vectors.push(this.maximum.clone());
  7381. this.vectors[6].x = this.minimum.x;
  7382. this.vectors.push(this.maximum.clone());
  7383. this.vectors[7].y = this.minimum.y;
  7384. // OBB
  7385. this.center = this.maximum.add(this.minimum).scale(0.5);
  7386. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7387. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7388. // World
  7389. for (var index = 0; index < this.vectors.length; index++) {
  7390. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7391. }
  7392. this.minimumWorld = BABYLON.Vector3.Zero();
  7393. this.maximumWorld = BABYLON.Vector3.Zero();
  7394. this._update(BABYLON.Matrix.Identity());
  7395. }
  7396. // Methods
  7397. BoundingBox.prototype.getWorldMatrix = function () {
  7398. return this._worldMatrix;
  7399. };
  7400. BoundingBox.prototype._update = function (world) {
  7401. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7402. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7403. for (var index = 0; index < this.vectors.length; index++) {
  7404. var v = this.vectorsWorld[index];
  7405. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7406. if (v.x < this.minimumWorld.x)
  7407. this.minimumWorld.x = v.x;
  7408. if (v.y < this.minimumWorld.y)
  7409. this.minimumWorld.y = v.y;
  7410. if (v.z < this.minimumWorld.z)
  7411. this.minimumWorld.z = v.z;
  7412. if (v.x > this.maximumWorld.x)
  7413. this.maximumWorld.x = v.x;
  7414. if (v.y > this.maximumWorld.y)
  7415. this.maximumWorld.y = v.y;
  7416. if (v.z > this.maximumWorld.z)
  7417. this.maximumWorld.z = v.z;
  7418. }
  7419. // OBB
  7420. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7421. this.center.scaleInPlace(0.5);
  7422. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7423. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7424. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7425. this._worldMatrix = world;
  7426. };
  7427. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7428. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7429. };
  7430. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7431. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7432. };
  7433. BoundingBox.prototype.intersectsPoint = function (point) {
  7434. var delta = -BABYLON.Engine.Epsilon;
  7435. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7436. return false;
  7437. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7438. return false;
  7439. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7440. return false;
  7441. return true;
  7442. };
  7443. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7444. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7445. };
  7446. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7447. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7448. return false;
  7449. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7450. return false;
  7451. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7452. return false;
  7453. return true;
  7454. };
  7455. // Statics
  7456. BoundingBox.Intersects = function (box0, box1) {
  7457. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7458. return false;
  7459. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7460. return false;
  7461. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7462. return false;
  7463. return true;
  7464. };
  7465. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7466. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7467. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7468. return (num <= (sphereRadius * sphereRadius));
  7469. };
  7470. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7471. for (var p = 0; p < 6; p++) {
  7472. for (var i = 0; i < 8; i++) {
  7473. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7474. return false;
  7475. }
  7476. }
  7477. }
  7478. return true;
  7479. };
  7480. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7481. for (var p = 0; p < 6; p++) {
  7482. var inCount = 8;
  7483. for (var i = 0; i < 8; i++) {
  7484. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7485. --inCount;
  7486. }
  7487. else {
  7488. break;
  7489. }
  7490. }
  7491. if (inCount === 0)
  7492. return false;
  7493. }
  7494. return true;
  7495. };
  7496. return BoundingBox;
  7497. })();
  7498. BABYLON.BoundingBox = BoundingBox;
  7499. })(BABYLON || (BABYLON = {}));
  7500. var BABYLON;
  7501. (function (BABYLON) {
  7502. var computeBoxExtents = function (axis, box) {
  7503. var p = BABYLON.Vector3.Dot(box.center, axis);
  7504. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7505. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7506. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7507. var r = r0 + r1 + r2;
  7508. return {
  7509. min: p - r,
  7510. max: p + r
  7511. };
  7512. };
  7513. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7514. var axisOverlap = function (axis, box0, box1) {
  7515. var result0 = computeBoxExtents(axis, box0);
  7516. var result1 = computeBoxExtents(axis, box1);
  7517. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7518. };
  7519. var BoundingInfo = (function () {
  7520. function BoundingInfo(minimum, maximum) {
  7521. this.minimum = minimum;
  7522. this.maximum = maximum;
  7523. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7524. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7525. }
  7526. // Methods
  7527. BoundingInfo.prototype._update = function (world) {
  7528. this.boundingBox._update(world);
  7529. this.boundingSphere._update(world);
  7530. };
  7531. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7532. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7533. return false;
  7534. return this.boundingBox.isInFrustum(frustumPlanes);
  7535. };
  7536. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7537. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7538. };
  7539. BoundingInfo.prototype._checkCollision = function (collider) {
  7540. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7541. };
  7542. BoundingInfo.prototype.intersectsPoint = function (point) {
  7543. if (!this.boundingSphere.centerWorld) {
  7544. return false;
  7545. }
  7546. if (!this.boundingSphere.intersectsPoint(point)) {
  7547. return false;
  7548. }
  7549. if (!this.boundingBox.intersectsPoint(point)) {
  7550. return false;
  7551. }
  7552. return true;
  7553. };
  7554. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7555. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7556. return false;
  7557. }
  7558. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7559. return false;
  7560. }
  7561. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7562. return false;
  7563. }
  7564. if (!precise) {
  7565. return true;
  7566. }
  7567. var box0 = this.boundingBox;
  7568. var box1 = boundingInfo.boundingBox;
  7569. if (!axisOverlap(box0.directions[0], box0, box1))
  7570. return false;
  7571. if (!axisOverlap(box0.directions[1], box0, box1))
  7572. return false;
  7573. if (!axisOverlap(box0.directions[2], box0, box1))
  7574. return false;
  7575. if (!axisOverlap(box1.directions[0], box0, box1))
  7576. return false;
  7577. if (!axisOverlap(box1.directions[1], box0, box1))
  7578. return false;
  7579. if (!axisOverlap(box1.directions[2], box0, box1))
  7580. return false;
  7581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7582. return false;
  7583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7584. return false;
  7585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7586. return false;
  7587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7588. return false;
  7589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7590. return false;
  7591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7592. return false;
  7593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7594. return false;
  7595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7596. return false;
  7597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7598. return false;
  7599. return true;
  7600. };
  7601. return BoundingInfo;
  7602. })();
  7603. BABYLON.BoundingInfo = BoundingInfo;
  7604. })(BABYLON || (BABYLON = {}));
  7605. var BABYLON;
  7606. (function (BABYLON) {
  7607. var AbstractMesh = (function (_super) {
  7608. __extends(AbstractMesh, _super);
  7609. function AbstractMesh(name, scene) {
  7610. var _this = this;
  7611. _super.call(this, name, scene);
  7612. // Properties
  7613. this.definedFacingForward = true; // orientation for POV movement & rotation
  7614. this.position = new BABYLON.Vector3(0, 0, 0);
  7615. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7616. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7617. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7618. this.visibility = 1.0;
  7619. this.alphaIndex = Number.MAX_VALUE;
  7620. this.infiniteDistance = false;
  7621. this.isVisible = true;
  7622. this.isPickable = true;
  7623. this.showBoundingBox = false;
  7624. this.showSubMeshesBoundingBox = false;
  7625. this.onDispose = null;
  7626. this.isBlocker = false;
  7627. this.renderingGroupId = 0;
  7628. this.receiveShadows = false;
  7629. this.renderOutline = false;
  7630. this.outlineColor = BABYLON.Color3.Red();
  7631. this.outlineWidth = 0.02;
  7632. this.renderOverlay = false;
  7633. this.overlayColor = BABYLON.Color3.Red();
  7634. this.overlayAlpha = 0.5;
  7635. this.hasVertexAlpha = false;
  7636. this.useVertexColors = true;
  7637. this.applyFog = true;
  7638. this.computeBonesUsingShaders = true;
  7639. this.scalingDeterminant = 1;
  7640. this.numBoneInfluencers = 4;
  7641. this.useOctreeForRenderingSelection = true;
  7642. this.useOctreeForPicking = true;
  7643. this.useOctreeForCollisions = true;
  7644. this.layerMask = 0x0FFFFFFF;
  7645. this.alwaysSelectAsActiveMesh = false;
  7646. // Physics
  7647. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7648. // Collisions
  7649. this._checkCollisions = false;
  7650. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7651. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7652. this._collider = new BABYLON.Collider();
  7653. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7654. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7655. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7656. // Edges
  7657. this.edgesWidth = 1;
  7658. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7659. // Cache
  7660. this._localWorld = BABYLON.Matrix.Zero();
  7661. this._worldMatrix = BABYLON.Matrix.Zero();
  7662. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7663. this._absolutePosition = BABYLON.Vector3.Zero();
  7664. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7665. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7666. this._isDirty = false;
  7667. this._pivotMatrix = BABYLON.Matrix.Identity();
  7668. this._isDisposed = false;
  7669. this._renderId = 0;
  7670. this._intersectionsInProgress = new Array();
  7671. this._onAfterWorldMatrixUpdate = new Array();
  7672. this._isWorldMatrixFrozen = false;
  7673. this._unIndexed = false;
  7674. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7675. if (collidedMesh === void 0) { collidedMesh = null; }
  7676. //TODO move this to the collision coordinator!
  7677. if (_this.getScene().workerCollisions)
  7678. newPosition.multiplyInPlace(_this._collider.radius);
  7679. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7680. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7681. _this.position.addInPlace(_this._diffPositionForCollisions);
  7682. }
  7683. if (_this.onCollide && collidedMesh) {
  7684. _this.onCollide(collidedMesh);
  7685. }
  7686. if (_this.onCollisionPositionChange) {
  7687. _this.onCollisionPositionChange(_this.position);
  7688. }
  7689. };
  7690. scene.addMesh(this);
  7691. }
  7692. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7693. get: function () {
  7694. return AbstractMesh._BILLBOARDMODE_NONE;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7700. get: function () {
  7701. return AbstractMesh._BILLBOARDMODE_X;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7707. get: function () {
  7708. return AbstractMesh._BILLBOARDMODE_Y;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7714. get: function () {
  7715. return AbstractMesh._BILLBOARDMODE_Z;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7721. get: function () {
  7722. return AbstractMesh._BILLBOARDMODE_ALL;
  7723. },
  7724. enumerable: true,
  7725. configurable: true
  7726. });
  7727. // Methods
  7728. AbstractMesh.prototype.disableEdgesRendering = function () {
  7729. if (this._edgesRenderer !== undefined) {
  7730. this._edgesRenderer.dispose();
  7731. this._edgesRenderer = undefined;
  7732. }
  7733. };
  7734. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7735. if (epsilon === void 0) { epsilon = 0.95; }
  7736. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7737. this.disableEdgesRendering();
  7738. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7739. };
  7740. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7741. get: function () {
  7742. return false;
  7743. },
  7744. enumerable: true,
  7745. configurable: true
  7746. });
  7747. AbstractMesh.prototype.getLOD = function (camera) {
  7748. return this;
  7749. };
  7750. AbstractMesh.prototype.getTotalVertices = function () {
  7751. return 0;
  7752. };
  7753. AbstractMesh.prototype.getIndices = function () {
  7754. return null;
  7755. };
  7756. AbstractMesh.prototype.getVerticesData = function (kind) {
  7757. return null;
  7758. };
  7759. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7760. return false;
  7761. };
  7762. AbstractMesh.prototype.getBoundingInfo = function () {
  7763. if (this._masterMesh) {
  7764. return this._masterMesh.getBoundingInfo();
  7765. }
  7766. if (!this._boundingInfo) {
  7767. this._updateBoundingInfo();
  7768. }
  7769. return this._boundingInfo;
  7770. };
  7771. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7772. get: function () {
  7773. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7774. },
  7775. enumerable: true,
  7776. configurable: true
  7777. });
  7778. AbstractMesh.prototype._preActivate = function () {
  7779. };
  7780. AbstractMesh.prototype._activate = function (renderId) {
  7781. this._renderId = renderId;
  7782. };
  7783. AbstractMesh.prototype.getWorldMatrix = function () {
  7784. if (this._masterMesh) {
  7785. return this._masterMesh.getWorldMatrix();
  7786. }
  7787. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7788. this.computeWorldMatrix();
  7789. }
  7790. return this._worldMatrix;
  7791. };
  7792. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7793. get: function () {
  7794. return this._worldMatrix;
  7795. },
  7796. enumerable: true,
  7797. configurable: true
  7798. });
  7799. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7800. get: function () {
  7801. return this._absolutePosition;
  7802. },
  7803. enumerable: true,
  7804. configurable: true
  7805. });
  7806. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7807. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7808. this.computeWorldMatrix(true);
  7809. this._isWorldMatrixFrozen = true;
  7810. };
  7811. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7812. this._isWorldMatrixFrozen = false;
  7813. this.computeWorldMatrix(true);
  7814. };
  7815. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7816. get: function () {
  7817. return this._isWorldMatrixFrozen;
  7818. },
  7819. enumerable: true,
  7820. configurable: true
  7821. });
  7822. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7823. axis.normalize();
  7824. if (!this.rotationQuaternion) {
  7825. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7826. this.rotation = BABYLON.Vector3.Zero();
  7827. }
  7828. var rotationQuaternion;
  7829. if (!space || space === BABYLON.Space.LOCAL) {
  7830. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7831. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7832. }
  7833. else {
  7834. if (this.parent) {
  7835. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7836. invertParentWorldMatrix.invert();
  7837. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7838. }
  7839. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7840. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7841. }
  7842. };
  7843. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7844. var displacementVector = axis.scale(distance);
  7845. if (!space || space === BABYLON.Space.LOCAL) {
  7846. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7847. this.setPositionWithLocalVector(tempV3);
  7848. }
  7849. else {
  7850. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7851. }
  7852. };
  7853. AbstractMesh.prototype.getAbsolutePosition = function () {
  7854. this.computeWorldMatrix();
  7855. return this._absolutePosition;
  7856. };
  7857. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7858. if (!absolutePosition) {
  7859. return;
  7860. }
  7861. var absolutePositionX;
  7862. var absolutePositionY;
  7863. var absolutePositionZ;
  7864. if (absolutePosition.x === undefined) {
  7865. if (arguments.length < 3) {
  7866. return;
  7867. }
  7868. absolutePositionX = arguments[0];
  7869. absolutePositionY = arguments[1];
  7870. absolutePositionZ = arguments[2];
  7871. }
  7872. else {
  7873. absolutePositionX = absolutePosition.x;
  7874. absolutePositionY = absolutePosition.y;
  7875. absolutePositionZ = absolutePosition.z;
  7876. }
  7877. if (this.parent) {
  7878. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7879. invertParentWorldMatrix.invert();
  7880. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7881. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7882. }
  7883. else {
  7884. this.position.x = absolutePositionX;
  7885. this.position.y = absolutePositionY;
  7886. this.position.z = absolutePositionZ;
  7887. }
  7888. };
  7889. // ================================== Point of View Movement =================================
  7890. /**
  7891. * Perform relative position change from the point of view of behind the front of the mesh.
  7892. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7893. * Supports definition of mesh facing forward or backward.
  7894. * @param {number} amountRight
  7895. * @param {number} amountUp
  7896. * @param {number} amountForward
  7897. */
  7898. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7899. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7900. };
  7901. /**
  7902. * Calculate relative position change from the point of view of behind the front of the mesh.
  7903. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7904. * Supports definition of mesh facing forward or backward.
  7905. * @param {number} amountRight
  7906. * @param {number} amountUp
  7907. * @param {number} amountForward
  7908. */
  7909. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7910. var rotMatrix = new BABYLON.Matrix();
  7911. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7912. rotQuaternion.toRotationMatrix(rotMatrix);
  7913. var translationDelta = BABYLON.Vector3.Zero();
  7914. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7915. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7916. return translationDelta;
  7917. };
  7918. // ================================== Point of View Rotation =================================
  7919. /**
  7920. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7921. * Supports definition of mesh facing forward or backward.
  7922. * @param {number} flipBack
  7923. * @param {number} twirlClockwise
  7924. * @param {number} tiltRight
  7925. */
  7926. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7927. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7928. };
  7929. /**
  7930. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7931. * Supports definition of mesh facing forward or backward.
  7932. * @param {number} flipBack
  7933. * @param {number} twirlClockwise
  7934. * @param {number} tiltRight
  7935. */
  7936. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7937. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7938. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7939. };
  7940. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7941. this._pivotMatrix = matrix;
  7942. this._cache.pivotMatrixUpdated = true;
  7943. };
  7944. AbstractMesh.prototype.getPivotMatrix = function () {
  7945. return this._pivotMatrix;
  7946. };
  7947. AbstractMesh.prototype._isSynchronized = function () {
  7948. if (this._isDirty) {
  7949. return false;
  7950. }
  7951. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7952. return false;
  7953. if (this._cache.pivotMatrixUpdated) {
  7954. return false;
  7955. }
  7956. if (this.infiniteDistance) {
  7957. return false;
  7958. }
  7959. if (!this._cache.position.equals(this.position))
  7960. return false;
  7961. if (this.rotationQuaternion) {
  7962. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7963. return false;
  7964. }
  7965. else {
  7966. if (!this._cache.rotation.equals(this.rotation))
  7967. return false;
  7968. }
  7969. if (!this._cache.scaling.equals(this.scaling))
  7970. return false;
  7971. return true;
  7972. };
  7973. AbstractMesh.prototype._initCache = function () {
  7974. _super.prototype._initCache.call(this);
  7975. this._cache.localMatrixUpdated = false;
  7976. this._cache.position = BABYLON.Vector3.Zero();
  7977. this._cache.scaling = BABYLON.Vector3.Zero();
  7978. this._cache.rotation = BABYLON.Vector3.Zero();
  7979. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7980. this._cache.billboardMode = -1;
  7981. };
  7982. AbstractMesh.prototype.markAsDirty = function (property) {
  7983. if (property === "rotation") {
  7984. this.rotationQuaternion = null;
  7985. }
  7986. this._currentRenderId = Number.MAX_VALUE;
  7987. this._isDirty = true;
  7988. };
  7989. AbstractMesh.prototype._updateBoundingInfo = function () {
  7990. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7991. this._boundingInfo._update(this.worldMatrixFromCache);
  7992. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7993. };
  7994. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7995. if (!this.subMeshes) {
  7996. return;
  7997. }
  7998. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7999. var subMesh = this.subMeshes[subIndex];
  8000. if (!subMesh.IsGlobal) {
  8001. subMesh.updateBoundingInfo(matrix);
  8002. }
  8003. }
  8004. };
  8005. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8006. if (this._isWorldMatrixFrozen) {
  8007. return this._worldMatrix;
  8008. }
  8009. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8010. this._currentRenderId = this.getScene().getRenderId();
  8011. return this._worldMatrix;
  8012. }
  8013. this._cache.position.copyFrom(this.position);
  8014. this._cache.scaling.copyFrom(this.scaling);
  8015. this._cache.pivotMatrixUpdated = false;
  8016. this._cache.billboardMode = this.billboardMode;
  8017. this._currentRenderId = this.getScene().getRenderId();
  8018. this._isDirty = false;
  8019. // Scaling
  8020. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8021. // Rotation
  8022. if (this.rotationQuaternion) {
  8023. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8024. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8025. }
  8026. else {
  8027. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8028. this._cache.rotation.copyFrom(this.rotation);
  8029. }
  8030. // Translation
  8031. if (this.infiniteDistance && !this.parent) {
  8032. var camera = this.getScene().activeCamera;
  8033. if (camera) {
  8034. var cameraWorldMatrix = camera.getWorldMatrix();
  8035. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8036. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8037. }
  8038. }
  8039. else {
  8040. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8041. }
  8042. // Composing transformations
  8043. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8044. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8045. // Billboarding
  8046. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8047. var localPosition = this.position.clone();
  8048. var zero = this.getScene().activeCamera.globalPosition.clone();
  8049. if (this.parent && this.parent.position) {
  8050. localPosition.addInPlace(this.parent.position);
  8051. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8052. }
  8053. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8054. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8055. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8056. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8057. zero.y = localPosition.y + 0.001;
  8058. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8059. zero.z = localPosition.z + 0.001;
  8060. }
  8061. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8062. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8063. BABYLON.Tmp.Matrix[3].invert();
  8064. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8065. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8066. }
  8067. // Local world
  8068. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8069. // Parent
  8070. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8071. this._markSyncedWithParent();
  8072. if (this._meshToBoneReferal) {
  8073. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8074. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8075. }
  8076. else {
  8077. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8078. }
  8079. }
  8080. else {
  8081. this._worldMatrix.copyFrom(this._localWorld);
  8082. }
  8083. // Bounding info
  8084. this._updateBoundingInfo();
  8085. // Absolute position
  8086. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8087. // Callbacks
  8088. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8089. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8090. }
  8091. return this._worldMatrix;
  8092. };
  8093. /**
  8094. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8095. * @param func: callback function to add
  8096. */
  8097. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8098. this._onAfterWorldMatrixUpdate.push(func);
  8099. };
  8100. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8101. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8102. if (index > -1) {
  8103. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8104. }
  8105. };
  8106. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8107. this.computeWorldMatrix();
  8108. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8109. };
  8110. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8111. this.computeWorldMatrix();
  8112. var invLocalWorldMatrix = this._localWorld.clone();
  8113. invLocalWorldMatrix.invert();
  8114. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8115. };
  8116. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8117. this.computeWorldMatrix(true);
  8118. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8119. };
  8120. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8121. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8122. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8123. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8124. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8125. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8126. /// <returns>Mesh oriented towards targetMesh</returns>
  8127. yawCor = yawCor || 0; // default to zero if undefined
  8128. pitchCor = pitchCor || 0;
  8129. rollCor = rollCor || 0;
  8130. var dv = targetPoint.subtract(this.position);
  8131. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8132. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8133. var pitch = Math.atan2(dv.y, len);
  8134. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8135. };
  8136. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8137. this._meshToBoneReferal = affectedMesh;
  8138. this.parent = bone;
  8139. if (bone.getWorldMatrix().determinant() < 0) {
  8140. this.scalingDeterminant *= -1;
  8141. }
  8142. };
  8143. AbstractMesh.prototype.detachFromBone = function () {
  8144. if (this.parent.getWorldMatrix().determinant() < 0) {
  8145. this.scalingDeterminant *= -1;
  8146. }
  8147. this._meshToBoneReferal = null;
  8148. this.parent = null;
  8149. };
  8150. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8151. return this._boundingInfo.isInFrustum(frustumPlanes);
  8152. };
  8153. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8154. if (!camera) {
  8155. camera = this.getScene().activeCamera;
  8156. }
  8157. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8158. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8159. return false;
  8160. }
  8161. return true;
  8162. };
  8163. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8164. if (!this._boundingInfo || !mesh._boundingInfo) {
  8165. return false;
  8166. }
  8167. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8168. };
  8169. AbstractMesh.prototype.intersectsPoint = function (point) {
  8170. if (!this._boundingInfo) {
  8171. return false;
  8172. }
  8173. return this._boundingInfo.intersectsPoint(point);
  8174. };
  8175. // Physics
  8176. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8177. var physicsEngine = this.getScene().getPhysicsEngine();
  8178. if (!physicsEngine) {
  8179. return null;
  8180. }
  8181. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8182. if (impostor.impostor) {
  8183. // Old API
  8184. options = impostor;
  8185. impostor = impostor.impostor;
  8186. }
  8187. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8188. physicsEngine._unregisterMesh(this);
  8189. return null;
  8190. }
  8191. if (!options) {
  8192. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8193. }
  8194. else {
  8195. if (!options.mass && options.mass !== 0)
  8196. options.mass = 0;
  8197. if (!options.friction && options.friction !== 0)
  8198. options.friction = 0.2;
  8199. if (!options.restitution && options.restitution !== 0)
  8200. options.restitution = 0.2;
  8201. }
  8202. this._physicImpostor = impostor;
  8203. this._physicsMass = options.mass;
  8204. this._physicsFriction = options.friction;
  8205. this._physicRestitution = options.restitution;
  8206. return physicsEngine._registerMesh(this, impostor, options);
  8207. };
  8208. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8209. if (!this._physicImpostor) {
  8210. return BABYLON.PhysicsEngine.NoImpostor;
  8211. }
  8212. return this._physicImpostor;
  8213. };
  8214. AbstractMesh.prototype.getPhysicsMass = function () {
  8215. if (!this._physicsMass) {
  8216. return 0;
  8217. }
  8218. return this._physicsMass;
  8219. };
  8220. AbstractMesh.prototype.getPhysicsFriction = function () {
  8221. if (!this._physicsFriction) {
  8222. return 0;
  8223. }
  8224. return this._physicsFriction;
  8225. };
  8226. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8227. if (!this._physicRestitution) {
  8228. return 0;
  8229. }
  8230. return this._physicRestitution;
  8231. };
  8232. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8233. if (!camera) {
  8234. camera = this.getScene().activeCamera;
  8235. }
  8236. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8237. };
  8238. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8239. if (!camera) {
  8240. camera = this.getScene().activeCamera;
  8241. }
  8242. return this.absolutePosition.subtract(camera.position).length();
  8243. };
  8244. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8245. if (!this._physicImpostor) {
  8246. return;
  8247. }
  8248. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8249. };
  8250. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8251. if (!this._physicImpostor) {
  8252. return;
  8253. }
  8254. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8255. };
  8256. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8257. if (!this._physicImpostor) {
  8258. return;
  8259. }
  8260. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8261. };
  8262. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8263. // Collisions
  8264. get: function () {
  8265. return this._checkCollisions;
  8266. },
  8267. set: function (collisionEnabled) {
  8268. this._checkCollisions = collisionEnabled;
  8269. if (this.getScene().workerCollisions) {
  8270. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8271. }
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8277. var globalPosition = this.getAbsolutePosition();
  8278. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8279. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8280. this._collider.radius = this.ellipsoid;
  8281. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8282. };
  8283. // Submeshes octree
  8284. /**
  8285. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8286. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8287. */
  8288. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8289. if (maxCapacity === void 0) { maxCapacity = 64; }
  8290. if (maxDepth === void 0) { maxDepth = 2; }
  8291. if (!this._submeshesOctree) {
  8292. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8293. }
  8294. this.computeWorldMatrix(true);
  8295. // Update octree
  8296. var bbox = this.getBoundingInfo().boundingBox;
  8297. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8298. return this._submeshesOctree;
  8299. };
  8300. // Collisions
  8301. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8302. this._generatePointsArray();
  8303. // Transformation
  8304. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8305. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8306. subMesh._lastColliderWorldVertices = [];
  8307. subMesh._trianglePlanes = [];
  8308. var start = subMesh.verticesStart;
  8309. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8310. for (var i = start; i < end; i++) {
  8311. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8312. }
  8313. }
  8314. // Collide
  8315. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8316. if (collider.collisionFound) {
  8317. collider.collidedMesh = this;
  8318. }
  8319. };
  8320. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8321. var subMeshes;
  8322. var len;
  8323. // Octrees
  8324. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8325. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8326. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8327. len = intersections.length;
  8328. subMeshes = intersections.data;
  8329. }
  8330. else {
  8331. subMeshes = this.subMeshes;
  8332. len = subMeshes.length;
  8333. }
  8334. for (var index = 0; index < len; index++) {
  8335. var subMesh = subMeshes[index];
  8336. // Bounding test
  8337. if (len > 1 && !subMesh._checkCollision(collider))
  8338. continue;
  8339. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8340. }
  8341. };
  8342. AbstractMesh.prototype._checkCollision = function (collider) {
  8343. // Bounding box test
  8344. if (!this._boundingInfo._checkCollision(collider))
  8345. return;
  8346. // Transformation matrix
  8347. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8348. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8349. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8350. };
  8351. // Picking
  8352. AbstractMesh.prototype._generatePointsArray = function () {
  8353. return false;
  8354. };
  8355. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8356. var pickingInfo = new BABYLON.PickingInfo();
  8357. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8358. return pickingInfo;
  8359. }
  8360. if (!this._generatePointsArray()) {
  8361. return pickingInfo;
  8362. }
  8363. var intersectInfo = null;
  8364. // Octrees
  8365. var subMeshes;
  8366. var len;
  8367. if (this._submeshesOctree && this.useOctreeForPicking) {
  8368. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8369. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8370. len = intersections.length;
  8371. subMeshes = intersections.data;
  8372. }
  8373. else {
  8374. subMeshes = this.subMeshes;
  8375. len = subMeshes.length;
  8376. }
  8377. for (var index = 0; index < len; index++) {
  8378. var subMesh = subMeshes[index];
  8379. // Bounding test
  8380. if (len > 1 && !subMesh.canIntersects(ray))
  8381. continue;
  8382. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8383. if (currentIntersectInfo) {
  8384. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8385. intersectInfo = currentIntersectInfo;
  8386. intersectInfo.subMeshId = index;
  8387. if (fastCheck) {
  8388. break;
  8389. }
  8390. }
  8391. }
  8392. }
  8393. if (intersectInfo) {
  8394. // Get picked point
  8395. var world = this.getWorldMatrix();
  8396. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8397. var direction = ray.direction.clone();
  8398. direction = direction.scale(intersectInfo.distance);
  8399. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8400. var pickedPoint = worldOrigin.add(worldDirection);
  8401. // Return result
  8402. pickingInfo.hit = true;
  8403. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8404. pickingInfo.pickedPoint = pickedPoint;
  8405. pickingInfo.pickedMesh = this;
  8406. pickingInfo.bu = intersectInfo.bu;
  8407. pickingInfo.bv = intersectInfo.bv;
  8408. pickingInfo.faceId = intersectInfo.faceId;
  8409. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8410. return pickingInfo;
  8411. }
  8412. return pickingInfo;
  8413. };
  8414. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8415. return null;
  8416. };
  8417. AbstractMesh.prototype.releaseSubMeshes = function () {
  8418. if (this.subMeshes) {
  8419. while (this.subMeshes.length) {
  8420. this.subMeshes[0].dispose();
  8421. }
  8422. }
  8423. else {
  8424. this.subMeshes = new Array();
  8425. }
  8426. };
  8427. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8428. var index;
  8429. // Animations
  8430. this.getScene().stopAnimation(this);
  8431. // Physics
  8432. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8433. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8434. }
  8435. // Intersections in progress
  8436. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8437. var other = this._intersectionsInProgress[index];
  8438. var pos = other._intersectionsInProgress.indexOf(this);
  8439. other._intersectionsInProgress.splice(pos, 1);
  8440. }
  8441. this._intersectionsInProgress = [];
  8442. // Edges
  8443. if (this._edgesRenderer) {
  8444. this._edgesRenderer.dispose();
  8445. this._edgesRenderer = null;
  8446. }
  8447. // SubMeshes
  8448. this.releaseSubMeshes();
  8449. // Remove from scene
  8450. this.getScene().removeMesh(this);
  8451. if (!doNotRecurse) {
  8452. // Particles
  8453. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8454. if (this.getScene().particleSystems[index].emitter === this) {
  8455. this.getScene().particleSystems[index].dispose();
  8456. index--;
  8457. }
  8458. }
  8459. // Children
  8460. var objects = this.getScene().meshes.slice(0);
  8461. for (index = 0; index < objects.length; index++) {
  8462. if (objects[index].parent === this) {
  8463. objects[index].dispose();
  8464. }
  8465. }
  8466. }
  8467. else {
  8468. for (index = 0; index < this.getScene().meshes.length; index++) {
  8469. var obj = this.getScene().meshes[index];
  8470. if (obj.parent === this) {
  8471. obj.parent = null;
  8472. obj.computeWorldMatrix(true);
  8473. }
  8474. }
  8475. }
  8476. this._onAfterWorldMatrixUpdate = [];
  8477. this._isDisposed = true;
  8478. // Callback
  8479. if (this.onDispose) {
  8480. this.onDispose();
  8481. }
  8482. };
  8483. // Statics
  8484. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8485. AbstractMesh._BILLBOARDMODE_X = 1;
  8486. AbstractMesh._BILLBOARDMODE_Y = 2;
  8487. AbstractMesh._BILLBOARDMODE_Z = 4;
  8488. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8489. return AbstractMesh;
  8490. })(BABYLON.Node);
  8491. BABYLON.AbstractMesh = AbstractMesh;
  8492. })(BABYLON || (BABYLON = {}));
  8493. var BABYLON;
  8494. (function (BABYLON) {
  8495. var Light = (function (_super) {
  8496. __extends(Light, _super);
  8497. function Light(name, scene) {
  8498. _super.call(this, name, scene);
  8499. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8500. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8501. this.intensity = 1.0;
  8502. this.range = Number.MAX_VALUE;
  8503. this.includeOnlyWithLayerMask = 0;
  8504. this.includedOnlyMeshes = new Array();
  8505. this.excludedMeshes = new Array();
  8506. this.excludeWithLayerMask = 0;
  8507. this._excludedMeshesIds = new Array();
  8508. this._includedOnlyMeshesIds = new Array();
  8509. scene.addLight(this);
  8510. }
  8511. Light.prototype.getShadowGenerator = function () {
  8512. return this._shadowGenerator;
  8513. };
  8514. Light.prototype.getAbsolutePosition = function () {
  8515. return BABYLON.Vector3.Zero();
  8516. };
  8517. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8518. };
  8519. Light.prototype._getWorldMatrix = function () {
  8520. return BABYLON.Matrix.Identity();
  8521. };
  8522. Light.prototype.canAffectMesh = function (mesh) {
  8523. if (!mesh) {
  8524. return true;
  8525. }
  8526. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8527. return false;
  8528. }
  8529. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8530. return false;
  8531. }
  8532. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8533. return false;
  8534. }
  8535. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8536. return false;
  8537. }
  8538. return true;
  8539. };
  8540. Light.prototype.getWorldMatrix = function () {
  8541. this._currentRenderId = this.getScene().getRenderId();
  8542. var worldMatrix = this._getWorldMatrix();
  8543. if (this.parent && this.parent.getWorldMatrix) {
  8544. if (!this._parentedWorldMatrix) {
  8545. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8546. }
  8547. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8548. this._markSyncedWithParent();
  8549. return this._parentedWorldMatrix;
  8550. }
  8551. return worldMatrix;
  8552. };
  8553. Light.prototype.dispose = function () {
  8554. if (this._shadowGenerator) {
  8555. this._shadowGenerator.dispose();
  8556. this._shadowGenerator = null;
  8557. }
  8558. // Animations
  8559. this.getScene().stopAnimation(this);
  8560. // Remove from scene
  8561. this.getScene().removeLight(this);
  8562. };
  8563. Light.prototype.serialize = function () {
  8564. var serializationObject = {};
  8565. serializationObject.name = this.name;
  8566. serializationObject.id = this.id;
  8567. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8568. if (this.intensity) {
  8569. serializationObject.intensity = this.intensity;
  8570. }
  8571. serializationObject.range = this.range;
  8572. serializationObject.diffuse = this.diffuse.asArray();
  8573. serializationObject.specular = this.specular.asArray();
  8574. return serializationObject;
  8575. };
  8576. Light.Parse = function (parsedLight, scene) {
  8577. var light;
  8578. switch (parsedLight.type) {
  8579. case 0:
  8580. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8581. break;
  8582. case 1:
  8583. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8584. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8585. break;
  8586. case 2:
  8587. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8588. break;
  8589. case 3:
  8590. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8591. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8592. break;
  8593. }
  8594. light.id = parsedLight.id;
  8595. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8596. if (parsedLight.intensity !== undefined) {
  8597. light.intensity = parsedLight.intensity;
  8598. }
  8599. if (parsedLight.range) {
  8600. light.range = parsedLight.range;
  8601. }
  8602. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8603. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8604. if (parsedLight.excludedMeshesIds) {
  8605. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8606. }
  8607. // Parent
  8608. if (parsedLight.parentId) {
  8609. light._waitingParentId = parsedLight.parentId;
  8610. }
  8611. if (parsedLight.includedOnlyMeshesIds) {
  8612. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8613. }
  8614. // Animations
  8615. if (parsedLight.animations) {
  8616. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8617. var parsedAnimation = parsedLight.animations[animationIndex];
  8618. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8619. }
  8620. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8621. }
  8622. if (parsedLight.autoAnimate) {
  8623. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8624. }
  8625. return light;
  8626. };
  8627. return Light;
  8628. })(BABYLON.Node);
  8629. BABYLON.Light = Light;
  8630. })(BABYLON || (BABYLON = {}));
  8631. var BABYLON;
  8632. (function (BABYLON) {
  8633. var PointLight = (function (_super) {
  8634. __extends(PointLight, _super);
  8635. function PointLight(name, position, scene) {
  8636. _super.call(this, name, scene);
  8637. this.position = position;
  8638. }
  8639. PointLight.prototype.getAbsolutePosition = function () {
  8640. return this.transformedPosition ? this.transformedPosition : this.position;
  8641. };
  8642. PointLight.prototype.computeTransformedPosition = function () {
  8643. if (this.parent && this.parent.getWorldMatrix) {
  8644. if (!this.transformedPosition) {
  8645. this.transformedPosition = BABYLON.Vector3.Zero();
  8646. }
  8647. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8648. return true;
  8649. }
  8650. return false;
  8651. };
  8652. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8653. if (this.parent && this.parent.getWorldMatrix) {
  8654. this.computeTransformedPosition();
  8655. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8656. return;
  8657. }
  8658. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8659. };
  8660. PointLight.prototype.needCube = function () {
  8661. return true;
  8662. };
  8663. PointLight.prototype.supportsVSM = function () {
  8664. return false;
  8665. };
  8666. PointLight.prototype.needRefreshPerFrame = function () {
  8667. return false;
  8668. };
  8669. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8670. switch (faceIndex) {
  8671. case 0:
  8672. return new BABYLON.Vector3(1, 0, 0);
  8673. case 1:
  8674. return new BABYLON.Vector3(-1, 0, 0);
  8675. case 2:
  8676. return new BABYLON.Vector3(0, -1, 0);
  8677. case 3:
  8678. return new BABYLON.Vector3(0, 1, 0);
  8679. case 4:
  8680. return new BABYLON.Vector3(0, 0, 1);
  8681. case 5:
  8682. return new BABYLON.Vector3(0, 0, -1);
  8683. }
  8684. return BABYLON.Vector3.Zero();
  8685. };
  8686. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8687. var activeCamera = this.getScene().activeCamera;
  8688. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8689. };
  8690. PointLight.prototype._getWorldMatrix = function () {
  8691. if (!this._worldMatrix) {
  8692. this._worldMatrix = BABYLON.Matrix.Identity();
  8693. }
  8694. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8695. return this._worldMatrix;
  8696. };
  8697. PointLight.prototype.serialize = function () {
  8698. var serializationObject = _super.prototype.serialize.call(this);
  8699. serializationObject.type = 0;
  8700. serializationObject.position = this.position.asArray();
  8701. return serializationObject;
  8702. };
  8703. return PointLight;
  8704. })(BABYLON.Light);
  8705. BABYLON.PointLight = PointLight;
  8706. })(BABYLON || (BABYLON = {}));
  8707. var BABYLON;
  8708. (function (BABYLON) {
  8709. var SpotLight = (function (_super) {
  8710. __extends(SpotLight, _super);
  8711. function SpotLight(name, position, direction, angle, exponent, scene) {
  8712. _super.call(this, name, scene);
  8713. this.position = position;
  8714. this.direction = direction;
  8715. this.angle = angle;
  8716. this.exponent = exponent;
  8717. }
  8718. SpotLight.prototype.getAbsolutePosition = function () {
  8719. return this.transformedPosition ? this.transformedPosition : this.position;
  8720. };
  8721. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8722. var activeCamera = this.getScene().activeCamera;
  8723. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8724. };
  8725. SpotLight.prototype.needCube = function () {
  8726. return false;
  8727. };
  8728. SpotLight.prototype.supportsVSM = function () {
  8729. return true;
  8730. };
  8731. SpotLight.prototype.needRefreshPerFrame = function () {
  8732. return false;
  8733. };
  8734. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8735. return this.direction;
  8736. };
  8737. SpotLight.prototype.setDirectionToTarget = function (target) {
  8738. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8739. return this.direction;
  8740. };
  8741. SpotLight.prototype.computeTransformedPosition = function () {
  8742. if (this.parent && this.parent.getWorldMatrix) {
  8743. if (!this.transformedPosition) {
  8744. this.transformedPosition = BABYLON.Vector3.Zero();
  8745. }
  8746. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8747. return true;
  8748. }
  8749. return false;
  8750. };
  8751. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8752. var normalizeDirection;
  8753. if (this.parent && this.parent.getWorldMatrix) {
  8754. if (!this._transformedDirection) {
  8755. this._transformedDirection = BABYLON.Vector3.Zero();
  8756. }
  8757. this.computeTransformedPosition();
  8758. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8759. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8760. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8761. }
  8762. else {
  8763. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8764. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8765. }
  8766. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8767. };
  8768. SpotLight.prototype._getWorldMatrix = function () {
  8769. if (!this._worldMatrix) {
  8770. this._worldMatrix = BABYLON.Matrix.Identity();
  8771. }
  8772. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8773. return this._worldMatrix;
  8774. };
  8775. SpotLight.prototype.serialize = function () {
  8776. var serializationObject = _super.prototype.serialize.call(this);
  8777. serializationObject.type = 2;
  8778. serializationObject.position = this.position.asArray();
  8779. serializationObject.direction = this.position.asArray();
  8780. serializationObject.angle = this.angle;
  8781. serializationObject.exponent = this.exponent;
  8782. return serializationObject;
  8783. };
  8784. return SpotLight;
  8785. })(BABYLON.Light);
  8786. BABYLON.SpotLight = SpotLight;
  8787. })(BABYLON || (BABYLON = {}));
  8788. var BABYLON;
  8789. (function (BABYLON) {
  8790. var HemisphericLight = (function (_super) {
  8791. __extends(HemisphericLight, _super);
  8792. function HemisphericLight(name, direction, scene) {
  8793. _super.call(this, name, scene);
  8794. this.direction = direction;
  8795. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8796. }
  8797. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8798. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8799. return this.direction;
  8800. };
  8801. HemisphericLight.prototype.getShadowGenerator = function () {
  8802. return null;
  8803. };
  8804. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8805. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8806. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8807. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8808. };
  8809. HemisphericLight.prototype._getWorldMatrix = function () {
  8810. if (!this._worldMatrix) {
  8811. this._worldMatrix = BABYLON.Matrix.Identity();
  8812. }
  8813. return this._worldMatrix;
  8814. };
  8815. HemisphericLight.prototype.serialize = function () {
  8816. var serializationObject = _super.prototype.serialize.call(this);
  8817. serializationObject.type = 3;
  8818. serializationObject.direction = this.direction.asArray();
  8819. serializationObject.groundColor = this.groundColor.asArray();
  8820. return serializationObject;
  8821. };
  8822. return HemisphericLight;
  8823. })(BABYLON.Light);
  8824. BABYLON.HemisphericLight = HemisphericLight;
  8825. })(BABYLON || (BABYLON = {}));
  8826. var BABYLON;
  8827. (function (BABYLON) {
  8828. var DirectionalLight = (function (_super) {
  8829. __extends(DirectionalLight, _super);
  8830. function DirectionalLight(name, direction, scene) {
  8831. _super.call(this, name, scene);
  8832. this.direction = direction;
  8833. this.shadowOrthoScale = 0.5;
  8834. this.autoUpdateExtends = true;
  8835. // Cache
  8836. this._orthoLeft = Number.MAX_VALUE;
  8837. this._orthoRight = Number.MIN_VALUE;
  8838. this._orthoTop = Number.MIN_VALUE;
  8839. this._orthoBottom = Number.MAX_VALUE;
  8840. this.position = direction.scale(-1);
  8841. }
  8842. DirectionalLight.prototype.getAbsolutePosition = function () {
  8843. return this.transformedPosition ? this.transformedPosition : this.position;
  8844. };
  8845. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8846. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8847. return this.direction;
  8848. };
  8849. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8850. var activeCamera = this.getScene().activeCamera;
  8851. // Check extends
  8852. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8853. var tempVector3 = BABYLON.Vector3.Zero();
  8854. this._orthoLeft = Number.MAX_VALUE;
  8855. this._orthoRight = Number.MIN_VALUE;
  8856. this._orthoTop = Number.MIN_VALUE;
  8857. this._orthoBottom = Number.MAX_VALUE;
  8858. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8859. var mesh = renderList[meshIndex];
  8860. if (!mesh) {
  8861. continue;
  8862. }
  8863. var boundingInfo = mesh.getBoundingInfo();
  8864. if (!boundingInfo) {
  8865. continue;
  8866. }
  8867. var boundingBox = boundingInfo.boundingBox;
  8868. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8869. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8870. if (tempVector3.x < this._orthoLeft)
  8871. this._orthoLeft = tempVector3.x;
  8872. if (tempVector3.y < this._orthoBottom)
  8873. this._orthoBottom = tempVector3.y;
  8874. if (tempVector3.x > this._orthoRight)
  8875. this._orthoRight = tempVector3.x;
  8876. if (tempVector3.y > this._orthoTop)
  8877. this._orthoTop = tempVector3.y;
  8878. }
  8879. }
  8880. }
  8881. var xOffset = this._orthoRight - this._orthoLeft;
  8882. var yOffset = this._orthoTop - this._orthoBottom;
  8883. 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);
  8884. };
  8885. DirectionalLight.prototype.supportsVSM = function () {
  8886. return true;
  8887. };
  8888. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8889. return true;
  8890. };
  8891. DirectionalLight.prototype.needCube = function () {
  8892. return false;
  8893. };
  8894. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8895. return this.direction;
  8896. };
  8897. DirectionalLight.prototype.computeTransformedPosition = function () {
  8898. if (this.parent && this.parent.getWorldMatrix) {
  8899. if (!this.transformedPosition) {
  8900. this.transformedPosition = BABYLON.Vector3.Zero();
  8901. }
  8902. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8903. return true;
  8904. }
  8905. return false;
  8906. };
  8907. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8908. if (this.parent && this.parent.getWorldMatrix) {
  8909. if (!this._transformedDirection) {
  8910. this._transformedDirection = BABYLON.Vector3.Zero();
  8911. }
  8912. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8913. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8914. return;
  8915. }
  8916. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8917. };
  8918. DirectionalLight.prototype._getWorldMatrix = function () {
  8919. if (!this._worldMatrix) {
  8920. this._worldMatrix = BABYLON.Matrix.Identity();
  8921. }
  8922. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8923. return this._worldMatrix;
  8924. };
  8925. DirectionalLight.prototype.serialize = function () {
  8926. var serializationObject = _super.prototype.serialize.call(this);
  8927. serializationObject.type = 1;
  8928. serializationObject.position = this.position.asArray();
  8929. serializationObject.direction = this.direction.asArray();
  8930. return serializationObject;
  8931. };
  8932. return DirectionalLight;
  8933. })(BABYLON.Light);
  8934. BABYLON.DirectionalLight = DirectionalLight;
  8935. })(BABYLON || (BABYLON = {}));
  8936. var BABYLON;
  8937. (function (BABYLON) {
  8938. var ShadowGenerator = (function () {
  8939. function ShadowGenerator(mapSize, light) {
  8940. var _this = this;
  8941. // Members
  8942. this._filter = ShadowGenerator.FILTER_NONE;
  8943. this.blurScale = 2;
  8944. this._blurBoxOffset = 0;
  8945. this._bias = 0.00005;
  8946. this._lightDirection = BABYLON.Vector3.Zero();
  8947. this.forceBackFacesOnly = false;
  8948. this._darkness = 0;
  8949. this._transparencyShadow = false;
  8950. this._viewMatrix = BABYLON.Matrix.Zero();
  8951. this._projectionMatrix = BABYLON.Matrix.Zero();
  8952. this._transformMatrix = BABYLON.Matrix.Zero();
  8953. this._worldViewProjection = BABYLON.Matrix.Zero();
  8954. this._currentFaceIndex = 0;
  8955. this._currentFaceIndexCache = 0;
  8956. this._light = light;
  8957. this._scene = light.getScene();
  8958. this._mapSize = mapSize;
  8959. light._shadowGenerator = this;
  8960. // Render target
  8961. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8962. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8963. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8964. this._shadowMap.anisotropicFilteringLevel = 1;
  8965. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8966. this._shadowMap.renderParticles = false;
  8967. this._shadowMap.onBeforeRender = function (faceIndex) {
  8968. _this._currentFaceIndex = faceIndex;
  8969. };
  8970. this._shadowMap.onAfterUnbind = function () {
  8971. if (!_this.useBlurVarianceShadowMap) {
  8972. return;
  8973. }
  8974. if (!_this._shadowMap2) {
  8975. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8976. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8977. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8978. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8979. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8980. _this._downSamplePostprocess.onApply = function (effect) {
  8981. effect.setTexture("textureSampler", _this._shadowMap);
  8982. };
  8983. _this.blurBoxOffset = 1;
  8984. }
  8985. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8986. };
  8987. // Custom render function
  8988. var renderSubMesh = function (subMesh) {
  8989. var mesh = subMesh.getRenderingMesh();
  8990. var scene = _this._scene;
  8991. var engine = scene.getEngine();
  8992. // Culling
  8993. engine.setState(subMesh.getMaterial().backFaceCulling);
  8994. // Managing instances
  8995. var batch = mesh._getInstancesRenderList(subMesh._id);
  8996. if (batch.mustReturn) {
  8997. return;
  8998. }
  8999. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9000. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9001. engine.enableEffect(_this._effect);
  9002. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9003. var material = subMesh.getMaterial();
  9004. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9005. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9006. if (_this.getLight().needCube()) {
  9007. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9008. }
  9009. // Alpha test
  9010. if (material && material.needAlphaTesting()) {
  9011. var alphaTexture = material.getAlphaTestTexture();
  9012. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9013. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9014. }
  9015. // Bones
  9016. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9017. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9018. }
  9019. if (_this.forceBackFacesOnly) {
  9020. engine.setState(true, 0, false, true);
  9021. }
  9022. // Draw
  9023. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9024. if (_this.forceBackFacesOnly) {
  9025. engine.setState(true, 0, false, false);
  9026. }
  9027. }
  9028. else {
  9029. // Need to reset refresh rate of the shadowMap
  9030. _this._shadowMap.resetRefreshCounter();
  9031. }
  9032. };
  9033. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9034. var index;
  9035. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9036. renderSubMesh(opaqueSubMeshes.data[index]);
  9037. }
  9038. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9039. renderSubMesh(alphaTestSubMeshes.data[index]);
  9040. }
  9041. if (_this._transparencyShadow) {
  9042. for (index = 0; index < transparentSubMeshes.length; index++) {
  9043. renderSubMesh(transparentSubMeshes.data[index]);
  9044. }
  9045. }
  9046. };
  9047. this._shadowMap.onClear = function (engine) {
  9048. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9049. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9050. }
  9051. else {
  9052. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9053. }
  9054. };
  9055. }
  9056. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9057. // Static
  9058. get: function () {
  9059. return ShadowGenerator._FILTER_NONE;
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9065. get: function () {
  9066. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9072. get: function () {
  9073. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9079. get: function () {
  9080. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9086. get: function () {
  9087. return this._bias;
  9088. },
  9089. set: function (bias) {
  9090. this._bias = bias;
  9091. },
  9092. enumerable: true,
  9093. configurable: true
  9094. });
  9095. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9096. get: function () {
  9097. return this._blurBoxOffset;
  9098. },
  9099. set: function (value) {
  9100. var _this = this;
  9101. if (this._blurBoxOffset === value) {
  9102. return;
  9103. }
  9104. this._blurBoxOffset = value;
  9105. if (this._boxBlurPostprocess) {
  9106. this._boxBlurPostprocess.dispose();
  9107. }
  9108. 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);
  9109. this._boxBlurPostprocess.onApply = function (effect) {
  9110. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9111. };
  9112. },
  9113. enumerable: true,
  9114. configurable: true
  9115. });
  9116. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9117. get: function () {
  9118. return this._filter;
  9119. },
  9120. set: function (value) {
  9121. if (this._filter === value) {
  9122. return;
  9123. }
  9124. this._filter = value;
  9125. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9126. this._shadowMap.anisotropicFilteringLevel = 16;
  9127. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9128. }
  9129. else {
  9130. this._shadowMap.anisotropicFilteringLevel = 1;
  9131. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9132. }
  9133. },
  9134. enumerable: true,
  9135. configurable: true
  9136. });
  9137. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9138. get: function () {
  9139. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9140. },
  9141. set: function (value) {
  9142. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9143. },
  9144. enumerable: true,
  9145. configurable: true
  9146. });
  9147. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9148. get: function () {
  9149. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9150. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9151. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9152. },
  9153. set: function (value) {
  9154. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9155. },
  9156. enumerable: true,
  9157. configurable: true
  9158. });
  9159. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9160. get: function () {
  9161. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9162. },
  9163. set: function (value) {
  9164. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9170. var defines = [];
  9171. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9172. defines.push("#define VSM");
  9173. }
  9174. if (this.getLight().needCube()) {
  9175. defines.push("#define CUBEMAP");
  9176. }
  9177. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9178. var mesh = subMesh.getMesh();
  9179. var material = subMesh.getMaterial();
  9180. // Alpha test
  9181. if (material && material.needAlphaTesting()) {
  9182. defines.push("#define ALPHATEST");
  9183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9184. attribs.push(BABYLON.VertexBuffer.UVKind);
  9185. defines.push("#define UV1");
  9186. }
  9187. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9188. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9189. defines.push("#define UV2");
  9190. }
  9191. }
  9192. // Bones
  9193. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9194. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9195. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9196. if (mesh.numBoneInfluencers > 4) {
  9197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9199. }
  9200. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9201. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9202. }
  9203. else {
  9204. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9205. }
  9206. // Instances
  9207. if (useInstances) {
  9208. defines.push("#define INSTANCES");
  9209. attribs.push("world0");
  9210. attribs.push("world1");
  9211. attribs.push("world2");
  9212. attribs.push("world3");
  9213. }
  9214. // Get correct effect
  9215. var join = defines.join("\n");
  9216. if (this._cachedDefines !== join) {
  9217. this._cachedDefines = join;
  9218. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9219. }
  9220. return this._effect.isReady();
  9221. };
  9222. ShadowGenerator.prototype.getShadowMap = function () {
  9223. return this._shadowMap;
  9224. };
  9225. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9226. if (this._shadowMap2) {
  9227. return this._shadowMap2;
  9228. }
  9229. return this._shadowMap;
  9230. };
  9231. ShadowGenerator.prototype.getLight = function () {
  9232. return this._light;
  9233. };
  9234. // Methods
  9235. ShadowGenerator.prototype.getTransformMatrix = function () {
  9236. var scene = this._scene;
  9237. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9238. return this._transformMatrix;
  9239. }
  9240. this._currentRenderID = scene.getRenderId();
  9241. this._currentFaceIndexCache = this._currentFaceIndex;
  9242. var lightPosition = this._light.position;
  9243. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9244. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9245. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9246. }
  9247. if (this._light.computeTransformedPosition()) {
  9248. lightPosition = this._light.transformedPosition;
  9249. }
  9250. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9251. this._cachedPosition = lightPosition.clone();
  9252. this._cachedDirection = this._lightDirection.clone();
  9253. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9254. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9255. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9256. }
  9257. return this._transformMatrix;
  9258. };
  9259. ShadowGenerator.prototype.getDarkness = function () {
  9260. return this._darkness;
  9261. };
  9262. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9263. if (darkness >= 1.0)
  9264. this._darkness = 1.0;
  9265. else if (darkness <= 0.0)
  9266. this._darkness = 0.0;
  9267. else
  9268. this._darkness = darkness;
  9269. };
  9270. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9271. this._transparencyShadow = hasShadow;
  9272. };
  9273. ShadowGenerator.prototype._packHalf = function (depth) {
  9274. var scale = depth * 255.0;
  9275. var fract = scale - Math.floor(scale);
  9276. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9277. };
  9278. ShadowGenerator.prototype.dispose = function () {
  9279. this._shadowMap.dispose();
  9280. if (this._shadowMap2) {
  9281. this._shadowMap2.dispose();
  9282. }
  9283. if (this._downSamplePostprocess) {
  9284. this._downSamplePostprocess.dispose();
  9285. }
  9286. if (this._boxBlurPostprocess) {
  9287. this._boxBlurPostprocess.dispose();
  9288. }
  9289. };
  9290. ShadowGenerator.prototype.serialize = function () {
  9291. var serializationObject = {};
  9292. serializationObject.lightId = this._light.id;
  9293. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9294. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9295. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9296. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9297. serializationObject.renderList = [];
  9298. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9299. var mesh = this.getShadowMap().renderList[meshIndex];
  9300. serializationObject.renderList.push(mesh.id);
  9301. }
  9302. return serializationObject;
  9303. };
  9304. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9305. //casting to point light, as light is missing the position attr and typescript complains.
  9306. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9307. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9308. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9309. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9310. shadowGenerator.getShadowMap().renderList.push(mesh);
  9311. }
  9312. if (parsedShadowGenerator.usePoissonSampling) {
  9313. shadowGenerator.usePoissonSampling = true;
  9314. }
  9315. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9316. shadowGenerator.useVarianceShadowMap = true;
  9317. }
  9318. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9319. shadowGenerator.useBlurVarianceShadowMap = true;
  9320. if (parsedShadowGenerator.blurScale) {
  9321. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9322. }
  9323. if (parsedShadowGenerator.blurBoxOffset) {
  9324. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9325. }
  9326. }
  9327. if (parsedShadowGenerator.bias !== undefined) {
  9328. shadowGenerator.bias = parsedShadowGenerator.bias;
  9329. }
  9330. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9331. return shadowGenerator;
  9332. };
  9333. ShadowGenerator._FILTER_NONE = 0;
  9334. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9335. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9336. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9337. return ShadowGenerator;
  9338. })();
  9339. BABYLON.ShadowGenerator = ShadowGenerator;
  9340. })(BABYLON || (BABYLON = {}));
  9341. var BABYLON;
  9342. (function (BABYLON) {
  9343. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9344. if (boxMin.x > sphereCenter.x + sphereRadius)
  9345. return false;
  9346. if (sphereCenter.x - sphereRadius > boxMax.x)
  9347. return false;
  9348. if (boxMin.y > sphereCenter.y + sphereRadius)
  9349. return false;
  9350. if (sphereCenter.y - sphereRadius > boxMax.y)
  9351. return false;
  9352. if (boxMin.z > sphereCenter.z + sphereRadius)
  9353. return false;
  9354. if (sphereCenter.z - sphereRadius > boxMax.z)
  9355. return false;
  9356. return true;
  9357. };
  9358. var getLowestRoot = function (a, b, c, maxR) {
  9359. var determinant = b * b - 4.0 * a * c;
  9360. var result = { root: 0, found: false };
  9361. if (determinant < 0)
  9362. return result;
  9363. var sqrtD = Math.sqrt(determinant);
  9364. var r1 = (-b - sqrtD) / (2.0 * a);
  9365. var r2 = (-b + sqrtD) / (2.0 * a);
  9366. if (r1 > r2) {
  9367. var temp = r2;
  9368. r2 = r1;
  9369. r1 = temp;
  9370. }
  9371. if (r1 > 0 && r1 < maxR) {
  9372. result.root = r1;
  9373. result.found = true;
  9374. return result;
  9375. }
  9376. if (r2 > 0 && r2 < maxR) {
  9377. result.root = r2;
  9378. result.found = true;
  9379. return result;
  9380. }
  9381. return result;
  9382. };
  9383. var Collider = (function () {
  9384. function Collider() {
  9385. this.radius = new BABYLON.Vector3(1, 1, 1);
  9386. this.retry = 0;
  9387. this.basePointWorld = BABYLON.Vector3.Zero();
  9388. this.velocityWorld = BABYLON.Vector3.Zero();
  9389. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9390. this._collisionPoint = BABYLON.Vector3.Zero();
  9391. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9392. this._tempVector = BABYLON.Vector3.Zero();
  9393. this._tempVector2 = BABYLON.Vector3.Zero();
  9394. this._tempVector3 = BABYLON.Vector3.Zero();
  9395. this._tempVector4 = BABYLON.Vector3.Zero();
  9396. this._edge = BABYLON.Vector3.Zero();
  9397. this._baseToVertex = BABYLON.Vector3.Zero();
  9398. this._destinationPoint = BABYLON.Vector3.Zero();
  9399. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9400. this._displacementVector = BABYLON.Vector3.Zero();
  9401. }
  9402. // Methods
  9403. Collider.prototype._initialize = function (source, dir, e) {
  9404. this.velocity = dir;
  9405. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9406. this.basePoint = source;
  9407. source.multiplyToRef(this.radius, this.basePointWorld);
  9408. dir.multiplyToRef(this.radius, this.velocityWorld);
  9409. this.velocityWorldLength = this.velocityWorld.length();
  9410. this.epsilon = e;
  9411. this.collisionFound = false;
  9412. };
  9413. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9414. pa.subtractToRef(point, this._tempVector);
  9415. pb.subtractToRef(point, this._tempVector2);
  9416. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9417. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9418. if (d < 0)
  9419. return false;
  9420. pc.subtractToRef(point, this._tempVector3);
  9421. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9422. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9423. if (d < 0)
  9424. return false;
  9425. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9426. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9427. return d >= 0;
  9428. };
  9429. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9430. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9431. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9432. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9433. return false;
  9434. }
  9435. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9436. return false;
  9437. return true;
  9438. };
  9439. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9440. var t0;
  9441. var embeddedInPlane = false;
  9442. //defensive programming, actually not needed.
  9443. if (!trianglePlaneArray) {
  9444. trianglePlaneArray = [];
  9445. }
  9446. if (!trianglePlaneArray[faceIndex]) {
  9447. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9448. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9449. }
  9450. var trianglePlane = trianglePlaneArray[faceIndex];
  9451. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9452. return;
  9453. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9454. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9455. if (normalDotVelocity == 0) {
  9456. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9457. return;
  9458. embeddedInPlane = true;
  9459. t0 = 0;
  9460. }
  9461. else {
  9462. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9463. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9464. if (t0 > t1) {
  9465. var temp = t1;
  9466. t1 = t0;
  9467. t0 = temp;
  9468. }
  9469. if (t0 > 1.0 || t1 < 0.0)
  9470. return;
  9471. if (t0 < 0)
  9472. t0 = 0;
  9473. if (t0 > 1.0)
  9474. t0 = 1.0;
  9475. }
  9476. this._collisionPoint.copyFromFloats(0, 0, 0);
  9477. var found = false;
  9478. var t = 1.0;
  9479. if (!embeddedInPlane) {
  9480. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9481. this.velocity.scaleToRef(t0, this._tempVector);
  9482. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9483. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9484. found = true;
  9485. t = t0;
  9486. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9487. }
  9488. }
  9489. if (!found) {
  9490. var velocitySquaredLength = this.velocity.lengthSquared();
  9491. var a = velocitySquaredLength;
  9492. this.basePoint.subtractToRef(p1, this._tempVector);
  9493. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9494. var c = this._tempVector.lengthSquared() - 1.0;
  9495. var lowestRoot = getLowestRoot(a, b, c, t);
  9496. if (lowestRoot.found) {
  9497. t = lowestRoot.root;
  9498. found = true;
  9499. this._collisionPoint.copyFrom(p1);
  9500. }
  9501. this.basePoint.subtractToRef(p2, this._tempVector);
  9502. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9503. c = this._tempVector.lengthSquared() - 1.0;
  9504. lowestRoot = getLowestRoot(a, b, c, t);
  9505. if (lowestRoot.found) {
  9506. t = lowestRoot.root;
  9507. found = true;
  9508. this._collisionPoint.copyFrom(p2);
  9509. }
  9510. this.basePoint.subtractToRef(p3, this._tempVector);
  9511. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9512. c = this._tempVector.lengthSquared() - 1.0;
  9513. lowestRoot = getLowestRoot(a, b, c, t);
  9514. if (lowestRoot.found) {
  9515. t = lowestRoot.root;
  9516. found = true;
  9517. this._collisionPoint.copyFrom(p3);
  9518. }
  9519. p2.subtractToRef(p1, this._edge);
  9520. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9521. var edgeSquaredLength = this._edge.lengthSquared();
  9522. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9523. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9524. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9525. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9526. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9527. lowestRoot = getLowestRoot(a, b, c, t);
  9528. if (lowestRoot.found) {
  9529. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9530. if (f >= 0.0 && f <= 1.0) {
  9531. t = lowestRoot.root;
  9532. found = true;
  9533. this._edge.scaleInPlace(f);
  9534. p1.addToRef(this._edge, this._collisionPoint);
  9535. }
  9536. }
  9537. p3.subtractToRef(p2, this._edge);
  9538. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9539. edgeSquaredLength = this._edge.lengthSquared();
  9540. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9541. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9542. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9543. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9544. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9545. lowestRoot = getLowestRoot(a, b, c, t);
  9546. if (lowestRoot.found) {
  9547. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9548. if (f >= 0.0 && f <= 1.0) {
  9549. t = lowestRoot.root;
  9550. found = true;
  9551. this._edge.scaleInPlace(f);
  9552. p2.addToRef(this._edge, this._collisionPoint);
  9553. }
  9554. }
  9555. p1.subtractToRef(p3, this._edge);
  9556. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9557. edgeSquaredLength = this._edge.lengthSquared();
  9558. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9559. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9560. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9561. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9562. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9563. lowestRoot = getLowestRoot(a, b, c, t);
  9564. if (lowestRoot.found) {
  9565. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9566. if (f >= 0.0 && f <= 1.0) {
  9567. t = lowestRoot.root;
  9568. found = true;
  9569. this._edge.scaleInPlace(f);
  9570. p3.addToRef(this._edge, this._collisionPoint);
  9571. }
  9572. }
  9573. }
  9574. if (found) {
  9575. var distToCollision = t * this.velocity.length();
  9576. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9577. if (!this.intersectionPoint) {
  9578. this.intersectionPoint = this._collisionPoint.clone();
  9579. }
  9580. else {
  9581. this.intersectionPoint.copyFrom(this._collisionPoint);
  9582. }
  9583. this.nearestDistance = distToCollision;
  9584. this.collisionFound = true;
  9585. }
  9586. }
  9587. };
  9588. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9589. for (var i = indexStart; i < indexEnd; i += 3) {
  9590. var p1 = pts[indices[i] - decal];
  9591. var p2 = pts[indices[i + 1] - decal];
  9592. var p3 = pts[indices[i + 2] - decal];
  9593. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9594. }
  9595. };
  9596. Collider.prototype._getResponse = function (pos, vel) {
  9597. pos.addToRef(vel, this._destinationPoint);
  9598. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9599. this.basePoint.addToRef(vel, pos);
  9600. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9601. this._slidePlaneNormal.normalize();
  9602. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9603. pos.addInPlace(this._displacementVector);
  9604. this.intersectionPoint.addInPlace(this._displacementVector);
  9605. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9606. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9607. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9608. };
  9609. return Collider;
  9610. })();
  9611. BABYLON.Collider = Collider;
  9612. })(BABYLON || (BABYLON = {}));
  9613. var BABYLON;
  9614. (function (BABYLON) {
  9615. //WebWorker code will be inserted to this variable.
  9616. BABYLON.CollisionWorker = "";
  9617. (function (WorkerTaskType) {
  9618. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9619. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9620. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9621. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9622. var WorkerTaskType = BABYLON.WorkerTaskType;
  9623. (function (WorkerReplyType) {
  9624. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9625. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9626. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9627. var WorkerReplyType = BABYLON.WorkerReplyType;
  9628. var CollisionCoordinatorWorker = (function () {
  9629. function CollisionCoordinatorWorker() {
  9630. var _this = this;
  9631. this._scaledPosition = BABYLON.Vector3.Zero();
  9632. this._scaledVelocity = BABYLON.Vector3.Zero();
  9633. this.onMeshUpdated = function (mesh) {
  9634. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9635. };
  9636. this.onGeometryUpdated = function (geometry) {
  9637. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9638. };
  9639. this._afterRender = function () {
  9640. if (!_this._init)
  9641. return;
  9642. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9643. return;
  9644. }
  9645. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9646. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9647. if (_this._runningUpdated > 4) {
  9648. return;
  9649. }
  9650. ++_this._runningUpdated;
  9651. var payload = {
  9652. updatedMeshes: _this._addUpdateMeshesList,
  9653. updatedGeometries: _this._addUpdateGeometriesList,
  9654. removedGeometries: _this._toRemoveGeometryArray,
  9655. removedMeshes: _this._toRemoveMeshesArray
  9656. };
  9657. var message = {
  9658. payload: payload,
  9659. taskType: WorkerTaskType.UPDATE
  9660. };
  9661. var serializable = [];
  9662. for (var id in payload.updatedGeometries) {
  9663. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9664. //prepare transferables
  9665. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9666. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9667. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9668. }
  9669. }
  9670. _this._worker.postMessage(message, serializable);
  9671. _this._addUpdateMeshesList = {};
  9672. _this._addUpdateGeometriesList = {};
  9673. _this._toRemoveGeometryArray = [];
  9674. _this._toRemoveMeshesArray = [];
  9675. };
  9676. this._onMessageFromWorker = function (e) {
  9677. var returnData = e.data;
  9678. if (returnData.error != WorkerReplyType.SUCCESS) {
  9679. //TODO what errors can be returned from the worker?
  9680. BABYLON.Tools.Warn("error returned from worker!");
  9681. return;
  9682. }
  9683. switch (returnData.taskType) {
  9684. case WorkerTaskType.INIT:
  9685. _this._init = true;
  9686. //Update the worked with ALL of the scene's current state
  9687. _this._scene.meshes.forEach(function (mesh) {
  9688. _this.onMeshAdded(mesh);
  9689. });
  9690. _this._scene.getGeometries().forEach(function (geometry) {
  9691. _this.onGeometryAdded(geometry);
  9692. });
  9693. break;
  9694. case WorkerTaskType.UPDATE:
  9695. _this._runningUpdated--;
  9696. break;
  9697. case WorkerTaskType.COLLIDE:
  9698. _this._runningCollisionTask = false;
  9699. var returnPayload = returnData.payload;
  9700. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9701. return;
  9702. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9703. //cleanup
  9704. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9705. break;
  9706. }
  9707. };
  9708. this._collisionsCallbackArray = [];
  9709. this._init = false;
  9710. this._runningUpdated = 0;
  9711. this._runningCollisionTask = false;
  9712. this._addUpdateMeshesList = {};
  9713. this._addUpdateGeometriesList = {};
  9714. this._toRemoveGeometryArray = [];
  9715. this._toRemoveMeshesArray = [];
  9716. }
  9717. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9718. if (!this._init)
  9719. return;
  9720. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9721. return;
  9722. position.divideToRef(collider.radius, this._scaledPosition);
  9723. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9724. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9725. var payload = {
  9726. collider: {
  9727. position: this._scaledPosition.asArray(),
  9728. velocity: this._scaledVelocity.asArray(),
  9729. radius: collider.radius.asArray()
  9730. },
  9731. collisionId: collisionIndex,
  9732. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9733. maximumRetry: maximumRetry
  9734. };
  9735. var message = {
  9736. payload: payload,
  9737. taskType: WorkerTaskType.COLLIDE
  9738. };
  9739. this._worker.postMessage(message);
  9740. };
  9741. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9742. this._scene = scene;
  9743. this._scene.registerAfterRender(this._afterRender);
  9744. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9745. this._worker = new Worker(workerUrl);
  9746. this._worker.onmessage = this._onMessageFromWorker;
  9747. var message = {
  9748. payload: {},
  9749. taskType: WorkerTaskType.INIT
  9750. };
  9751. this._worker.postMessage(message);
  9752. };
  9753. CollisionCoordinatorWorker.prototype.destroy = function () {
  9754. this._scene.unregisterAfterRender(this._afterRender);
  9755. this._worker.terminate();
  9756. };
  9757. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9758. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9759. this.onMeshUpdated(mesh);
  9760. };
  9761. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9762. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9763. };
  9764. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9765. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9766. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9767. this.onGeometryUpdated(geometry);
  9768. };
  9769. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9770. this._toRemoveGeometryArray.push(geometry.id);
  9771. };
  9772. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9773. var submeshes = [];
  9774. if (mesh.subMeshes) {
  9775. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9776. return {
  9777. position: idx,
  9778. verticesStart: sm.verticesStart,
  9779. verticesCount: sm.verticesCount,
  9780. indexStart: sm.indexStart,
  9781. indexCount: sm.indexCount,
  9782. hasMaterial: !!sm.getMaterial(),
  9783. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9784. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9785. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9786. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9787. };
  9788. });
  9789. }
  9790. var geometryId = null;
  9791. if (mesh instanceof BABYLON.Mesh) {
  9792. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9793. }
  9794. else if (mesh instanceof BABYLON.InstancedMesh) {
  9795. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9796. }
  9797. return {
  9798. uniqueId: mesh.uniqueId,
  9799. id: mesh.id,
  9800. name: mesh.name,
  9801. geometryId: geometryId,
  9802. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9803. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9804. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9805. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9806. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9807. subMeshes: submeshes,
  9808. checkCollisions: mesh.checkCollisions
  9809. };
  9810. };
  9811. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9812. return {
  9813. id: geometry.id,
  9814. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9815. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9816. indices: new Int32Array(geometry.getIndices() || []),
  9817. };
  9818. };
  9819. return CollisionCoordinatorWorker;
  9820. })();
  9821. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9822. var CollisionCoordinatorLegacy = (function () {
  9823. function CollisionCoordinatorLegacy() {
  9824. this._scaledPosition = BABYLON.Vector3.Zero();
  9825. this._scaledVelocity = BABYLON.Vector3.Zero();
  9826. this._finalPosition = BABYLON.Vector3.Zero();
  9827. }
  9828. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9829. position.divideToRef(collider.radius, this._scaledPosition);
  9830. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9831. collider.collidedMesh = null;
  9832. collider.retry = 0;
  9833. collider.initialVelocity = this._scaledVelocity;
  9834. collider.initialPosition = this._scaledPosition;
  9835. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9836. this._finalPosition.multiplyInPlace(collider.radius);
  9837. //run the callback
  9838. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9839. };
  9840. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9841. this._scene = scene;
  9842. };
  9843. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9844. //Legacy need no destruction method.
  9845. };
  9846. //No update in legacy mode
  9847. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9848. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9849. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9850. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9851. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9852. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9853. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9854. if (excludedMesh === void 0) { excludedMesh = null; }
  9855. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9856. if (collider.retry >= maximumRetry) {
  9857. finalPosition.copyFrom(position);
  9858. return;
  9859. }
  9860. collider._initialize(position, velocity, closeDistance);
  9861. // Check all meshes
  9862. for (var index = 0; index < this._scene.meshes.length; index++) {
  9863. var mesh = this._scene.meshes[index];
  9864. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9865. mesh._checkCollision(collider);
  9866. }
  9867. }
  9868. if (!collider.collisionFound) {
  9869. position.addToRef(velocity, finalPosition);
  9870. return;
  9871. }
  9872. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9873. collider._getResponse(position, velocity);
  9874. }
  9875. if (velocity.length() <= closeDistance) {
  9876. finalPosition.copyFrom(position);
  9877. return;
  9878. }
  9879. collider.retry++;
  9880. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9881. };
  9882. return CollisionCoordinatorLegacy;
  9883. })();
  9884. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9885. })(BABYLON || (BABYLON = {}));
  9886. var BABYLON;
  9887. (function (BABYLON) {
  9888. var VRCameraMetrics = (function () {
  9889. function VRCameraMetrics() {
  9890. this.compensateDistortion = true;
  9891. }
  9892. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9893. get: function () {
  9894. return this.hResolution / (2 * this.vResolution);
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9900. get: function () {
  9901. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9907. get: function () {
  9908. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9909. var h = (4 * meters) / this.hScreenSize;
  9910. return BABYLON.Matrix.Translation(h, 0, 0);
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9916. get: function () {
  9917. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9918. var h = (4 * meters) / this.hScreenSize;
  9919. return BABYLON.Matrix.Translation(-h, 0, 0);
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9925. get: function () {
  9926. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9927. },
  9928. enumerable: true,
  9929. configurable: true
  9930. });
  9931. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9932. get: function () {
  9933. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. VRCameraMetrics.GetDefault = function () {
  9939. var result = new VRCameraMetrics();
  9940. result.hResolution = 1280;
  9941. result.vResolution = 800;
  9942. result.hScreenSize = 0.149759993;
  9943. result.vScreenSize = 0.0935999975;
  9944. result.vScreenCenter = 0.0467999987,
  9945. result.eyeToScreenDistance = 0.0410000011;
  9946. result.lensSeparationDistance = 0.0635000020;
  9947. result.interpupillaryDistance = 0.0640000030;
  9948. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9949. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9950. result.postProcessScaleFactor = 1.714605507808412;
  9951. result.lensCenterOffset = 0.151976421;
  9952. return result;
  9953. };
  9954. return VRCameraMetrics;
  9955. })();
  9956. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9957. var Camera = (function (_super) {
  9958. __extends(Camera, _super);
  9959. function Camera(name, position, scene) {
  9960. _super.call(this, name, scene);
  9961. this.position = position;
  9962. // Members
  9963. this.upVector = BABYLON.Vector3.Up();
  9964. this.orthoLeft = null;
  9965. this.orthoRight = null;
  9966. this.orthoBottom = null;
  9967. this.orthoTop = null;
  9968. this.fov = 0.8;
  9969. this.minZ = 1.0;
  9970. this.maxZ = 10000.0;
  9971. this.inertia = 0.9;
  9972. this.mode = Camera.PERSPECTIVE_CAMERA;
  9973. this.isIntermediate = false;
  9974. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9975. this.layerMask = 0x0FFFFFFF;
  9976. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9977. // Camera rig members
  9978. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9979. this._rigCameras = new Array();
  9980. // Cache
  9981. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9982. this._projectionMatrix = new BABYLON.Matrix();
  9983. this._postProcesses = new Array();
  9984. this._postProcessesTakenIndices = [];
  9985. this._activeMeshes = new BABYLON.SmartArray(256);
  9986. this._globalPosition = BABYLON.Vector3.Zero();
  9987. scene.addCamera(this);
  9988. if (!scene.activeCamera) {
  9989. scene.activeCamera = this;
  9990. }
  9991. }
  9992. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9993. get: function () {
  9994. return Camera._PERSPECTIVE_CAMERA;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10000. get: function () {
  10001. return Camera._ORTHOGRAPHIC_CAMERA;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10007. get: function () {
  10008. return Camera._FOVMODE_VERTICAL_FIXED;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10014. get: function () {
  10015. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10021. get: function () {
  10022. return Camera._RIG_MODE_NONE;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10028. get: function () {
  10029. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10035. get: function () {
  10036. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10042. get: function () {
  10043. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10049. get: function () {
  10050. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10056. get: function () {
  10057. return Camera._RIG_MODE_VR;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(Camera.prototype, "globalPosition", {
  10063. get: function () {
  10064. return this._globalPosition;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. Camera.prototype.getActiveMeshes = function () {
  10070. return this._activeMeshes;
  10071. };
  10072. Camera.prototype.isActiveMesh = function (mesh) {
  10073. return (this._activeMeshes.indexOf(mesh) !== -1);
  10074. };
  10075. //Cache
  10076. Camera.prototype._initCache = function () {
  10077. _super.prototype._initCache.call(this);
  10078. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10079. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10080. this._cache.mode = undefined;
  10081. this._cache.minZ = undefined;
  10082. this._cache.maxZ = undefined;
  10083. this._cache.fov = undefined;
  10084. this._cache.aspectRatio = undefined;
  10085. this._cache.orthoLeft = undefined;
  10086. this._cache.orthoRight = undefined;
  10087. this._cache.orthoBottom = undefined;
  10088. this._cache.orthoTop = undefined;
  10089. this._cache.renderWidth = undefined;
  10090. this._cache.renderHeight = undefined;
  10091. };
  10092. Camera.prototype._updateCache = function (ignoreParentClass) {
  10093. if (!ignoreParentClass) {
  10094. _super.prototype._updateCache.call(this);
  10095. }
  10096. var engine = this.getEngine();
  10097. this._cache.position.copyFrom(this.position);
  10098. this._cache.upVector.copyFrom(this.upVector);
  10099. this._cache.mode = this.mode;
  10100. this._cache.minZ = this.minZ;
  10101. this._cache.maxZ = this.maxZ;
  10102. this._cache.fov = this.fov;
  10103. this._cache.aspectRatio = engine.getAspectRatio(this);
  10104. this._cache.orthoLeft = this.orthoLeft;
  10105. this._cache.orthoRight = this.orthoRight;
  10106. this._cache.orthoBottom = this.orthoBottom;
  10107. this._cache.orthoTop = this.orthoTop;
  10108. this._cache.renderWidth = engine.getRenderWidth();
  10109. this._cache.renderHeight = engine.getRenderHeight();
  10110. };
  10111. Camera.prototype._updateFromScene = function () {
  10112. this.updateCache();
  10113. this._update();
  10114. };
  10115. // Synchronized
  10116. Camera.prototype._isSynchronized = function () {
  10117. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10118. };
  10119. Camera.prototype._isSynchronizedViewMatrix = function () {
  10120. if (!_super.prototype._isSynchronized.call(this))
  10121. return false;
  10122. return this._cache.position.equals(this.position)
  10123. && this._cache.upVector.equals(this.upVector)
  10124. && this.isSynchronizedWithParent();
  10125. };
  10126. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10127. var check = this._cache.mode === this.mode
  10128. && this._cache.minZ === this.minZ
  10129. && this._cache.maxZ === this.maxZ;
  10130. if (!check) {
  10131. return false;
  10132. }
  10133. var engine = this.getEngine();
  10134. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10135. check = this._cache.fov === this.fov
  10136. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10137. }
  10138. else {
  10139. check = this._cache.orthoLeft === this.orthoLeft
  10140. && this._cache.orthoRight === this.orthoRight
  10141. && this._cache.orthoBottom === this.orthoBottom
  10142. && this._cache.orthoTop === this.orthoTop
  10143. && this._cache.renderWidth === engine.getRenderWidth()
  10144. && this._cache.renderHeight === engine.getRenderHeight();
  10145. }
  10146. return check;
  10147. };
  10148. // Controls
  10149. Camera.prototype.attachControl = function (element) {
  10150. };
  10151. Camera.prototype.detachControl = function (element) {
  10152. };
  10153. Camera.prototype._update = function () {
  10154. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10155. this._updateRigCameras();
  10156. }
  10157. this._checkInputs();
  10158. };
  10159. Camera.prototype._checkInputs = function () {
  10160. };
  10161. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10162. if (insertAt === void 0) { insertAt = null; }
  10163. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10164. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10165. return 0;
  10166. }
  10167. if (insertAt == null || insertAt < 0) {
  10168. this._postProcesses.push(postProcess);
  10169. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10170. return this._postProcesses.length - 1;
  10171. }
  10172. var add = 0;
  10173. var i;
  10174. var start;
  10175. if (this._postProcesses[insertAt]) {
  10176. start = this._postProcesses.length - 1;
  10177. for (i = start; i >= insertAt + 1; --i) {
  10178. this._postProcesses[i + 1] = this._postProcesses[i];
  10179. }
  10180. add = 1;
  10181. }
  10182. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10183. if (this._postProcessesTakenIndices[i] < insertAt) {
  10184. continue;
  10185. }
  10186. start = this._postProcessesTakenIndices.length - 1;
  10187. for (var j = start; j >= i; --j) {
  10188. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10189. }
  10190. this._postProcessesTakenIndices[i] = insertAt;
  10191. break;
  10192. }
  10193. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10194. this._postProcessesTakenIndices.push(insertAt);
  10195. }
  10196. var result = insertAt + add;
  10197. this._postProcesses[result] = postProcess;
  10198. return result;
  10199. };
  10200. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10201. if (atIndices === void 0) { atIndices = null; }
  10202. var result = [];
  10203. var i;
  10204. var index;
  10205. if (!atIndices) {
  10206. var length = this._postProcesses.length;
  10207. for (i = 0; i < length; i++) {
  10208. if (this._postProcesses[i] !== postProcess) {
  10209. continue;
  10210. }
  10211. delete this._postProcesses[i];
  10212. index = this._postProcessesTakenIndices.indexOf(i);
  10213. this._postProcessesTakenIndices.splice(index, 1);
  10214. }
  10215. }
  10216. else {
  10217. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10218. for (i = 0; i < atIndices.length; i++) {
  10219. var foundPostProcess = this._postProcesses[atIndices[i]];
  10220. if (foundPostProcess !== postProcess) {
  10221. result.push(i);
  10222. continue;
  10223. }
  10224. delete this._postProcesses[atIndices[i]];
  10225. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10226. this._postProcessesTakenIndices.splice(index, 1);
  10227. }
  10228. }
  10229. return result;
  10230. };
  10231. Camera.prototype.getWorldMatrix = function () {
  10232. if (!this._worldMatrix) {
  10233. this._worldMatrix = BABYLON.Matrix.Identity();
  10234. }
  10235. var viewMatrix = this.getViewMatrix();
  10236. viewMatrix.invertToRef(this._worldMatrix);
  10237. return this._worldMatrix;
  10238. };
  10239. Camera.prototype._getViewMatrix = function () {
  10240. return BABYLON.Matrix.Identity();
  10241. };
  10242. Camera.prototype.getViewMatrix = function (force) {
  10243. this._computedViewMatrix = this._computeViewMatrix(force);
  10244. if (!force && this._isSynchronizedViewMatrix()) {
  10245. return this._computedViewMatrix;
  10246. }
  10247. if (!this.parent || !this.parent.getWorldMatrix) {
  10248. this._globalPosition.copyFrom(this.position);
  10249. }
  10250. else {
  10251. if (!this._worldMatrix) {
  10252. this._worldMatrix = BABYLON.Matrix.Identity();
  10253. }
  10254. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10255. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10256. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10257. this._computedViewMatrix.invert();
  10258. this._markSyncedWithParent();
  10259. }
  10260. this._currentRenderId = this.getScene().getRenderId();
  10261. return this._computedViewMatrix;
  10262. };
  10263. Camera.prototype._computeViewMatrix = function (force) {
  10264. if (!force && this._isSynchronizedViewMatrix()) {
  10265. return this._computedViewMatrix;
  10266. }
  10267. this._computedViewMatrix = this._getViewMatrix();
  10268. this._currentRenderId = this.getScene().getRenderId();
  10269. return this._computedViewMatrix;
  10270. };
  10271. Camera.prototype.getProjectionMatrix = function (force) {
  10272. if (!force && this._isSynchronizedProjectionMatrix()) {
  10273. return this._projectionMatrix;
  10274. }
  10275. var engine = this.getEngine();
  10276. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10277. if (this.minZ <= 0) {
  10278. this.minZ = 0.1;
  10279. }
  10280. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10281. return this._projectionMatrix;
  10282. }
  10283. var halfWidth = engine.getRenderWidth() / 2.0;
  10284. var halfHeight = engine.getRenderHeight() / 2.0;
  10285. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10286. return this._projectionMatrix;
  10287. };
  10288. Camera.prototype.dispose = function () {
  10289. // Animations
  10290. this.getScene().stopAnimation(this);
  10291. // Remove from scene
  10292. this.getScene().removeCamera(this);
  10293. while (this._rigCameras.length > 0) {
  10294. this._rigCameras.pop().dispose();
  10295. }
  10296. // Postprocesses
  10297. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10298. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10299. }
  10300. };
  10301. // ---- Camera rigs section ----
  10302. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10303. while (this._rigCameras.length > 0) {
  10304. this._rigCameras.pop().dispose();
  10305. }
  10306. this.cameraRigMode = mode;
  10307. this._cameraRigParams = {};
  10308. switch (this.cameraRigMode) {
  10309. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10310. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10311. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10312. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10313. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10314. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10315. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10316. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10317. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10318. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10319. break;
  10320. }
  10321. var postProcesses = new Array();
  10322. switch (this.cameraRigMode) {
  10323. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10324. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10325. this._rigCameras[0].isIntermediate = true;
  10326. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10327. postProcesses[1].onApply = function (effect) {
  10328. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10329. };
  10330. break;
  10331. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10332. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10333. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10334. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10335. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10336. var secondCamIndex = 1 - firstCamIndex;
  10337. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10338. this._rigCameras[firstCamIndex].isIntermediate = true;
  10339. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10340. break;
  10341. case Camera.RIG_MODE_VR:
  10342. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10343. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10344. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10345. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10346. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10347. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10348. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10349. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10350. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10351. if (metrics.compensateDistortion) {
  10352. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10353. }
  10354. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10355. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10356. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10357. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10358. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10359. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10360. if (metrics.compensateDistortion) {
  10361. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10362. }
  10363. break;
  10364. }
  10365. this._update();
  10366. };
  10367. Camera.prototype._getVRProjectionMatrix = function () {
  10368. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10369. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10370. return this._projectionMatrix;
  10371. };
  10372. Camera.prototype.setCameraRigParameter = function (name, value) {
  10373. this._cameraRigParams[name] = value;
  10374. //provisionnally:
  10375. if (name === "interaxialDistance") {
  10376. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10377. }
  10378. };
  10379. /**
  10380. * May needs to be overridden by children so sub has required properties to be copied
  10381. */
  10382. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10383. return null;
  10384. };
  10385. /**
  10386. * May needs to be overridden by children
  10387. */
  10388. Camera.prototype._updateRigCameras = function () {
  10389. for (var i = 0; i < this._rigCameras.length; i++) {
  10390. this._rigCameras[i].minZ = this.minZ;
  10391. this._rigCameras[i].maxZ = this.maxZ;
  10392. this._rigCameras[i].fov = this.fov;
  10393. }
  10394. // only update viewport when ANAGLYPH
  10395. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10396. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10397. }
  10398. };
  10399. Camera.prototype.serialize = function () {
  10400. var serializationObject = {};
  10401. serializationObject.name = this.name;
  10402. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10403. serializationObject.id = this.id;
  10404. serializationObject.position = this.position.asArray();
  10405. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10406. // Parent
  10407. if (this.parent) {
  10408. serializationObject.parentId = this.parent.id;
  10409. }
  10410. serializationObject.fov = this.fov;
  10411. serializationObject.minZ = this.minZ;
  10412. serializationObject.maxZ = this.maxZ;
  10413. serializationObject.inertia = this.inertia;
  10414. // Animations
  10415. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10416. serializationObject.ranges = this.serializeAnimationRanges();
  10417. // Layer mask
  10418. serializationObject.layerMask = this.layerMask;
  10419. return serializationObject;
  10420. };
  10421. Camera.Parse = function (parsedCamera, scene) {
  10422. var camera;
  10423. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10424. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10425. var interaxial_distance;
  10426. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10427. var alpha = parsedCamera.alpha;
  10428. var beta = parsedCamera.beta;
  10429. var radius = parsedCamera.radius;
  10430. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10431. interaxial_distance = parsedCamera.interaxial_distance;
  10432. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10433. }
  10434. else {
  10435. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10436. }
  10437. }
  10438. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10439. interaxial_distance = parsedCamera.interaxial_distance;
  10440. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10441. }
  10442. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10443. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10444. }
  10445. else if (parsedCamera.type === "FollowCamera") {
  10446. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10447. camera.heightOffset = parsedCamera.heightOffset;
  10448. camera.radius = parsedCamera.radius;
  10449. camera.rotationOffset = parsedCamera.rotationOffset;
  10450. if (lockedTargetMesh)
  10451. camera.target = lockedTargetMesh;
  10452. }
  10453. else if (parsedCamera.type === "GamepadCamera") {
  10454. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10455. }
  10456. else if (parsedCamera.type === "TouchCamera") {
  10457. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10458. }
  10459. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10460. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10461. }
  10462. else if (parsedCamera.type === "WebVRFreeCamera") {
  10463. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10464. }
  10465. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10466. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10467. }
  10468. else {
  10469. // Free Camera is the default value
  10470. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10471. }
  10472. // apply 3d rig, when found
  10473. if (parsedCamera.cameraRigMode) {
  10474. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10475. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10476. }
  10477. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10478. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10479. camera.lockedTarget = lockedTargetMesh;
  10480. }
  10481. camera.id = parsedCamera.id;
  10482. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10483. // Parent
  10484. if (parsedCamera.parentId) {
  10485. camera._waitingParentId = parsedCamera.parentId;
  10486. }
  10487. // Target
  10488. if (parsedCamera.target) {
  10489. if (camera.setTarget) {
  10490. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10491. }
  10492. else {
  10493. //For ArcRotate
  10494. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10495. }
  10496. }
  10497. else {
  10498. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10499. }
  10500. camera.fov = parsedCamera.fov;
  10501. camera.minZ = parsedCamera.minZ;
  10502. camera.maxZ = parsedCamera.maxZ;
  10503. camera.speed = parsedCamera.speed;
  10504. camera.inertia = parsedCamera.inertia;
  10505. camera.checkCollisions = parsedCamera.checkCollisions;
  10506. camera.applyGravity = parsedCamera.applyGravity;
  10507. if (parsedCamera.ellipsoid) {
  10508. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10509. }
  10510. // Animations
  10511. if (parsedCamera.animations) {
  10512. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10513. var parsedAnimation = parsedCamera.animations[animationIndex];
  10514. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10515. }
  10516. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10517. }
  10518. if (parsedCamera.autoAnimate) {
  10519. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10520. }
  10521. // Layer Mask
  10522. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10523. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10524. }
  10525. else {
  10526. camera.layerMask = 0x0FFFFFFF;
  10527. }
  10528. return camera;
  10529. };
  10530. // Statics
  10531. Camera._PERSPECTIVE_CAMERA = 0;
  10532. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10533. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10534. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10535. Camera._RIG_MODE_NONE = 0;
  10536. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10537. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10538. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10539. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10540. Camera._RIG_MODE_VR = 20;
  10541. return Camera;
  10542. })(BABYLON.Node);
  10543. BABYLON.Camera = Camera;
  10544. })(BABYLON || (BABYLON = {}));
  10545. var BABYLON;
  10546. (function (BABYLON) {
  10547. var TargetCamera = (function (_super) {
  10548. __extends(TargetCamera, _super);
  10549. function TargetCamera(name, position, scene) {
  10550. _super.call(this, name, position, scene);
  10551. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10552. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10553. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10554. this.speed = 2.0;
  10555. this.noRotationConstraint = false;
  10556. this.lockedTarget = null;
  10557. this._currentTarget = BABYLON.Vector3.Zero();
  10558. this._viewMatrix = BABYLON.Matrix.Zero();
  10559. this._camMatrix = BABYLON.Matrix.Zero();
  10560. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10561. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10562. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10563. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10564. this._lookAtTemp = BABYLON.Matrix.Zero();
  10565. this._tempMatrix = BABYLON.Matrix.Zero();
  10566. }
  10567. TargetCamera.prototype.getFrontPosition = function (distance) {
  10568. var direction = this.getTarget().subtract(this.position);
  10569. direction.normalize();
  10570. direction.scaleInPlace(distance);
  10571. return this.globalPosition.add(direction);
  10572. };
  10573. TargetCamera.prototype._getLockedTargetPosition = function () {
  10574. if (!this.lockedTarget) {
  10575. return null;
  10576. }
  10577. return this.lockedTarget.position || this.lockedTarget;
  10578. };
  10579. // Cache
  10580. TargetCamera.prototype._initCache = function () {
  10581. _super.prototype._initCache.call(this);
  10582. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10583. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10584. };
  10585. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10586. if (!ignoreParentClass) {
  10587. _super.prototype._updateCache.call(this);
  10588. }
  10589. var lockedTargetPosition = this._getLockedTargetPosition();
  10590. if (!lockedTargetPosition) {
  10591. this._cache.lockedTarget = null;
  10592. }
  10593. else {
  10594. if (!this._cache.lockedTarget) {
  10595. this._cache.lockedTarget = lockedTargetPosition.clone();
  10596. }
  10597. else {
  10598. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10599. }
  10600. }
  10601. this._cache.rotation.copyFrom(this.rotation);
  10602. };
  10603. // Synchronized
  10604. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10605. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10606. return false;
  10607. }
  10608. var lockedTargetPosition = this._getLockedTargetPosition();
  10609. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10610. && this._cache.rotation.equals(this.rotation);
  10611. };
  10612. // Methods
  10613. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10614. var engine = this.getEngine();
  10615. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10616. };
  10617. // Target
  10618. TargetCamera.prototype.setTarget = function (target) {
  10619. this.upVector.normalize();
  10620. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10621. this._camMatrix.invert();
  10622. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10623. var vDir = target.subtract(this.position);
  10624. if (vDir.x >= 0.0) {
  10625. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10626. }
  10627. else {
  10628. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10629. }
  10630. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10631. if (isNaN(this.rotation.x)) {
  10632. this.rotation.x = 0;
  10633. }
  10634. if (isNaN(this.rotation.y)) {
  10635. this.rotation.y = 0;
  10636. }
  10637. if (isNaN(this.rotation.z)) {
  10638. this.rotation.z = 0;
  10639. }
  10640. };
  10641. TargetCamera.prototype.getTarget = function () {
  10642. return this._currentTarget;
  10643. };
  10644. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10645. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10646. };
  10647. TargetCamera.prototype._updatePosition = function () {
  10648. this.position.addInPlace(this.cameraDirection);
  10649. };
  10650. TargetCamera.prototype._checkInputs = function () {
  10651. var needToMove = this._decideIfNeedsToMove();
  10652. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10653. // Move
  10654. if (needToMove) {
  10655. this._updatePosition();
  10656. }
  10657. // Rotate
  10658. if (needToRotate) {
  10659. this.rotation.x += this.cameraRotation.x;
  10660. this.rotation.y += this.cameraRotation.y;
  10661. if (!this.noRotationConstraint) {
  10662. var limit = (Math.PI / 2) * 0.95;
  10663. if (this.rotation.x > limit)
  10664. this.rotation.x = limit;
  10665. if (this.rotation.x < -limit)
  10666. this.rotation.x = -limit;
  10667. }
  10668. }
  10669. // Inertia
  10670. if (needToMove) {
  10671. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10672. this.cameraDirection.x = 0;
  10673. }
  10674. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10675. this.cameraDirection.y = 0;
  10676. }
  10677. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10678. this.cameraDirection.z = 0;
  10679. }
  10680. this.cameraDirection.scaleInPlace(this.inertia);
  10681. }
  10682. if (needToRotate) {
  10683. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10684. this.cameraRotation.x = 0;
  10685. }
  10686. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10687. this.cameraRotation.y = 0;
  10688. }
  10689. this.cameraRotation.scaleInPlace(this.inertia);
  10690. }
  10691. _super.prototype._checkInputs.call(this);
  10692. };
  10693. TargetCamera.prototype._getViewMatrix = function () {
  10694. if (!this.lockedTarget) {
  10695. // Compute
  10696. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10697. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10698. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10699. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10700. this._lookAtTemp.invert();
  10701. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10702. }
  10703. else {
  10704. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10705. }
  10706. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10707. // Computing target and final matrix
  10708. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10709. }
  10710. else {
  10711. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10712. }
  10713. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10714. return this._viewMatrix;
  10715. };
  10716. TargetCamera.prototype._getVRViewMatrix = function () {
  10717. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10718. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10719. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10720. // Computing target and final matrix
  10721. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10722. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10723. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10724. return this._viewMatrix;
  10725. };
  10726. /**
  10727. * @override
  10728. * Override Camera.createRigCamera
  10729. */
  10730. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10731. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10732. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10733. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10734. rigCamera._cameraRigParams = {};
  10735. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10736. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10737. }
  10738. return rigCamera;
  10739. }
  10740. return null;
  10741. };
  10742. /**
  10743. * @override
  10744. * Override Camera._updateRigCameras
  10745. */
  10746. TargetCamera.prototype._updateRigCameras = function () {
  10747. switch (this.cameraRigMode) {
  10748. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10752. case BABYLON.Camera.RIG_MODE_VR:
  10753. var camLeft = this._rigCameras[0];
  10754. var camRight = this._rigCameras[1];
  10755. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10756. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10757. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10758. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10759. camLeft.position.copyFrom(this.position);
  10760. camRight.position.copyFrom(this.position);
  10761. }
  10762. else {
  10763. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10764. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10765. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10766. camLeft.setTarget(this.getTarget());
  10767. camRight.setTarget(this.getTarget());
  10768. }
  10769. break;
  10770. }
  10771. _super.prototype._updateRigCameras.call(this);
  10772. };
  10773. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10774. if (!this._rigCamTransformMatrix) {
  10775. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10776. }
  10777. var target = this.getTarget();
  10778. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10779. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10780. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10781. };
  10782. TargetCamera.prototype.serialize = function () {
  10783. var serializationObject = _super.prototype.serialize.call(this);
  10784. serializationObject.speed = this.speed;
  10785. if (this.rotation) {
  10786. serializationObject.rotation = this.rotation.asArray();
  10787. }
  10788. if (this.lockedTarget && this.lockedTarget.id) {
  10789. serializationObject.lockedTargetId = this.lockedTarget.id;
  10790. }
  10791. return serializationObject;
  10792. };
  10793. return TargetCamera;
  10794. })(BABYLON.Camera);
  10795. BABYLON.TargetCamera = TargetCamera;
  10796. })(BABYLON || (BABYLON = {}));
  10797. var BABYLON;
  10798. (function (BABYLON) {
  10799. var FreeCamera = (function (_super) {
  10800. __extends(FreeCamera, _super);
  10801. function FreeCamera(name, position, scene) {
  10802. var _this = this;
  10803. _super.call(this, name, position, scene);
  10804. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10805. this.keysUp = [38];
  10806. this.keysDown = [40];
  10807. this.keysLeft = [37];
  10808. this.keysRight = [39];
  10809. this.checkCollisions = false;
  10810. this.applyGravity = false;
  10811. this.angularSensibility = 2000.0;
  10812. this._keys = [];
  10813. this._collider = new BABYLON.Collider();
  10814. this._needMoveForGravity = false;
  10815. this._oldPosition = BABYLON.Vector3.Zero();
  10816. this._diffPosition = BABYLON.Vector3.Zero();
  10817. this._newPosition = BABYLON.Vector3.Zero();
  10818. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10819. if (collidedMesh === void 0) { collidedMesh = null; }
  10820. //TODO move this to the collision coordinator!
  10821. if (_this.getScene().workerCollisions)
  10822. newPosition.multiplyInPlace(_this._collider.radius);
  10823. var updatePosition = function (newPos) {
  10824. _this._newPosition.copyFrom(newPos);
  10825. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10826. var oldPosition = _this.position.clone();
  10827. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10828. _this.position.addInPlace(_this._diffPosition);
  10829. if (_this.onCollide && collidedMesh) {
  10830. _this.onCollide(collidedMesh);
  10831. }
  10832. }
  10833. };
  10834. updatePosition(newPosition);
  10835. };
  10836. }
  10837. // Controls
  10838. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10839. var _this = this;
  10840. var previousPosition;
  10841. var engine = this.getEngine();
  10842. if (this._attachedElement) {
  10843. return;
  10844. }
  10845. this._attachedElement = element;
  10846. if (this._onMouseDown === undefined) {
  10847. this._onMouseDown = function (evt) {
  10848. previousPosition = {
  10849. x: evt.clientX,
  10850. y: evt.clientY
  10851. };
  10852. if (!noPreventDefault) {
  10853. evt.preventDefault();
  10854. }
  10855. };
  10856. this._onMouseUp = function (evt) {
  10857. previousPosition = null;
  10858. if (!noPreventDefault) {
  10859. evt.preventDefault();
  10860. }
  10861. };
  10862. this._onMouseOut = function (evt) {
  10863. previousPosition = null;
  10864. _this._keys = [];
  10865. if (!noPreventDefault) {
  10866. evt.preventDefault();
  10867. }
  10868. };
  10869. this._onMouseMove = function (evt) {
  10870. if (!previousPosition && !engine.isPointerLock) {
  10871. return;
  10872. }
  10873. var offsetX;
  10874. var offsetY;
  10875. if (!engine.isPointerLock) {
  10876. offsetX = evt.clientX - previousPosition.x;
  10877. offsetY = evt.clientY - previousPosition.y;
  10878. }
  10879. else {
  10880. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10881. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10882. }
  10883. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10884. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10885. previousPosition = {
  10886. x: evt.clientX,
  10887. y: evt.clientY
  10888. };
  10889. if (!noPreventDefault) {
  10890. evt.preventDefault();
  10891. }
  10892. };
  10893. this._onKeyDown = function (evt) {
  10894. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10895. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10896. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10897. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10898. var index = _this._keys.indexOf(evt.keyCode);
  10899. if (index === -1) {
  10900. _this._keys.push(evt.keyCode);
  10901. }
  10902. if (!noPreventDefault) {
  10903. evt.preventDefault();
  10904. }
  10905. }
  10906. };
  10907. this._onKeyUp = function (evt) {
  10908. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10909. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10910. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10911. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10912. var index = _this._keys.indexOf(evt.keyCode);
  10913. if (index >= 0) {
  10914. _this._keys.splice(index, 1);
  10915. }
  10916. if (!noPreventDefault) {
  10917. evt.preventDefault();
  10918. }
  10919. }
  10920. };
  10921. this._onLostFocus = function () {
  10922. _this._keys = [];
  10923. };
  10924. this._reset = function () {
  10925. _this._keys = [];
  10926. previousPosition = null;
  10927. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10928. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10929. };
  10930. }
  10931. element.addEventListener("mousedown", this._onMouseDown, false);
  10932. element.addEventListener("mouseup", this._onMouseUp, false);
  10933. element.addEventListener("mouseout", this._onMouseOut, false);
  10934. element.addEventListener("mousemove", this._onMouseMove, false);
  10935. BABYLON.Tools.RegisterTopRootEvents([
  10936. { name: "keydown", handler: this._onKeyDown },
  10937. { name: "keyup", handler: this._onKeyUp },
  10938. { name: "blur", handler: this._onLostFocus }
  10939. ]);
  10940. };
  10941. FreeCamera.prototype.detachControl = function (element) {
  10942. if (this._attachedElement !== element) {
  10943. return;
  10944. }
  10945. element.removeEventListener("mousedown", this._onMouseDown);
  10946. element.removeEventListener("mouseup", this._onMouseUp);
  10947. element.removeEventListener("mouseout", this._onMouseOut);
  10948. element.removeEventListener("mousemove", this._onMouseMove);
  10949. BABYLON.Tools.UnregisterTopRootEvents([
  10950. { name: "keydown", handler: this._onKeyDown },
  10951. { name: "keyup", handler: this._onKeyUp },
  10952. { name: "blur", handler: this._onLostFocus }
  10953. ]);
  10954. this._attachedElement = null;
  10955. if (this._reset) {
  10956. this._reset();
  10957. }
  10958. };
  10959. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10960. var globalPosition;
  10961. if (this.parent) {
  10962. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10963. }
  10964. else {
  10965. globalPosition = this.position;
  10966. }
  10967. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10968. this._collider.radius = this.ellipsoid;
  10969. //no need for clone, as long as gravity is not on.
  10970. var actualVelocity = velocity;
  10971. //add gravity to the velocity to prevent the dual-collision checking
  10972. if (this.applyGravity) {
  10973. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10974. actualVelocity = velocity.add(this.getScene().gravity);
  10975. }
  10976. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10977. };
  10978. FreeCamera.prototype._checkInputs = function () {
  10979. if (!this._localDirection) {
  10980. this._localDirection = BABYLON.Vector3.Zero();
  10981. this._transformedDirection = BABYLON.Vector3.Zero();
  10982. }
  10983. // Keyboard
  10984. for (var index = 0; index < this._keys.length; index++) {
  10985. var keyCode = this._keys[index];
  10986. var speed = this._computeLocalCameraSpeed();
  10987. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10988. this._localDirection.copyFromFloats(-speed, 0, 0);
  10989. }
  10990. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10991. this._localDirection.copyFromFloats(0, 0, speed);
  10992. }
  10993. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10994. this._localDirection.copyFromFloats(speed, 0, 0);
  10995. }
  10996. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10997. this._localDirection.copyFromFloats(0, 0, -speed);
  10998. }
  10999. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11000. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11001. this.cameraDirection.addInPlace(this._transformedDirection);
  11002. }
  11003. _super.prototype._checkInputs.call(this);
  11004. };
  11005. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11006. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11007. };
  11008. FreeCamera.prototype._updatePosition = function () {
  11009. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11010. this._collideWithWorld(this.cameraDirection);
  11011. }
  11012. else {
  11013. this.position.addInPlace(this.cameraDirection);
  11014. }
  11015. };
  11016. FreeCamera.prototype.serialize = function () {
  11017. var serializationObject = _super.prototype.serialize.call(this);
  11018. serializationObject.checkCollisions = this.checkCollisions;
  11019. serializationObject.applyGravity = this.applyGravity;
  11020. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11021. return serializationObject;
  11022. };
  11023. return FreeCamera;
  11024. })(BABYLON.TargetCamera);
  11025. BABYLON.FreeCamera = FreeCamera;
  11026. })(BABYLON || (BABYLON = {}));
  11027. var BABYLON;
  11028. (function (BABYLON) {
  11029. var FollowCamera = (function (_super) {
  11030. __extends(FollowCamera, _super);
  11031. function FollowCamera(name, position, scene) {
  11032. _super.call(this, name, position, scene);
  11033. this.radius = 12;
  11034. this.rotationOffset = 0;
  11035. this.heightOffset = 4;
  11036. this.cameraAcceleration = 0.05;
  11037. this.maxCameraSpeed = 20;
  11038. }
  11039. FollowCamera.prototype.getRadians = function (degrees) {
  11040. return degrees * Math.PI / 180;
  11041. };
  11042. FollowCamera.prototype.follow = function (cameraTarget) {
  11043. if (!cameraTarget)
  11044. return;
  11045. var yRotation;
  11046. if (cameraTarget.rotationQuaternion) {
  11047. var rotMatrix = new BABYLON.Matrix();
  11048. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11049. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11050. }
  11051. else {
  11052. yRotation = cameraTarget.rotation.y;
  11053. }
  11054. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11055. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11056. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11057. var dx = targetX - this.position.x;
  11058. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11059. var dz = (targetZ) - this.position.z;
  11060. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11061. var vy = dy * this.cameraAcceleration;
  11062. var vz = dz * this.cameraAcceleration * 2;
  11063. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11064. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11065. }
  11066. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11067. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11068. }
  11069. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11070. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11071. }
  11072. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11073. this.setTarget(cameraTarget.position);
  11074. };
  11075. FollowCamera.prototype._checkInputs = function () {
  11076. _super.prototype._checkInputs.call(this);
  11077. this.follow(this.target);
  11078. };
  11079. FollowCamera.prototype.serialize = function () {
  11080. var serializationObject = _super.prototype.serialize.call(this);
  11081. serializationObject.radius = this.radius;
  11082. serializationObject.heightOffset = this.heightOffset;
  11083. serializationObject.rotationOffset = this.rotationOffset;
  11084. return serializationObject;
  11085. };
  11086. return FollowCamera;
  11087. })(BABYLON.TargetCamera);
  11088. BABYLON.FollowCamera = FollowCamera;
  11089. var ArcFollowCamera = (function (_super) {
  11090. __extends(ArcFollowCamera, _super);
  11091. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11092. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11093. this.alpha = alpha;
  11094. this.beta = beta;
  11095. this.radius = radius;
  11096. this.target = target;
  11097. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11098. this.follow();
  11099. }
  11100. ArcFollowCamera.prototype.follow = function () {
  11101. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11102. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11103. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11104. this.position = this.target.position.add(this._cartesianCoordinates);
  11105. this.setTarget(this.target.position);
  11106. };
  11107. ArcFollowCamera.prototype._checkInputs = function () {
  11108. _super.prototype._checkInputs.call(this);
  11109. this.follow();
  11110. };
  11111. ArcFollowCamera.prototype.serialize = function () {
  11112. var serializationObject = _super.prototype.serialize.call(this);
  11113. serializationObject.radius = this.radius;
  11114. return serializationObject;
  11115. };
  11116. return ArcFollowCamera;
  11117. })(BABYLON.TargetCamera);
  11118. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11119. })(BABYLON || (BABYLON = {}));
  11120. var BABYLON;
  11121. (function (BABYLON) {
  11122. // We're mainly based on the logic defined into the FreeCamera code
  11123. var TouchCamera = (function (_super) {
  11124. __extends(TouchCamera, _super);
  11125. function TouchCamera(name, position, scene) {
  11126. _super.call(this, name, position, scene);
  11127. this._offsetX = null;
  11128. this._offsetY = null;
  11129. this._pointerCount = 0;
  11130. this._pointerPressed = [];
  11131. this.angularSensibility = 200000.0;
  11132. this.moveSensibility = 500.0;
  11133. }
  11134. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11135. var _this = this;
  11136. var previousPosition;
  11137. if (this._attachedCanvas) {
  11138. return;
  11139. }
  11140. this._attachedCanvas = canvas;
  11141. if (this._onPointerDown === undefined) {
  11142. this._onPointerDown = function (evt) {
  11143. if (!noPreventDefault) {
  11144. evt.preventDefault();
  11145. }
  11146. _this._pointerPressed.push(evt.pointerId);
  11147. if (_this._pointerPressed.length !== 1) {
  11148. return;
  11149. }
  11150. previousPosition = {
  11151. x: evt.clientX,
  11152. y: evt.clientY
  11153. };
  11154. };
  11155. this._onPointerUp = function (evt) {
  11156. if (!noPreventDefault) {
  11157. evt.preventDefault();
  11158. }
  11159. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11160. if (index === -1) {
  11161. return;
  11162. }
  11163. _this._pointerPressed.splice(index, 1);
  11164. if (index != 0) {
  11165. return;
  11166. }
  11167. previousPosition = null;
  11168. _this._offsetX = null;
  11169. _this._offsetY = null;
  11170. };
  11171. this._onPointerMove = function (evt) {
  11172. if (!noPreventDefault) {
  11173. evt.preventDefault();
  11174. }
  11175. if (!previousPosition) {
  11176. return;
  11177. }
  11178. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11179. if (index != 0) {
  11180. return;
  11181. }
  11182. _this._offsetX = evt.clientX - previousPosition.x;
  11183. _this._offsetY = -(evt.clientY - previousPosition.y);
  11184. };
  11185. this._onLostFocus = function () {
  11186. _this._offsetX = null;
  11187. _this._offsetY = null;
  11188. };
  11189. }
  11190. canvas.addEventListener("pointerdown", this._onPointerDown);
  11191. canvas.addEventListener("pointerup", this._onPointerUp);
  11192. canvas.addEventListener("pointerout", this._onPointerUp);
  11193. canvas.addEventListener("pointermove", this._onPointerMove);
  11194. BABYLON.Tools.RegisterTopRootEvents([
  11195. { name: "blur", handler: this._onLostFocus }
  11196. ]);
  11197. };
  11198. TouchCamera.prototype.detachControl = function (canvas) {
  11199. if (this._attachedCanvas !== canvas) {
  11200. return;
  11201. }
  11202. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11203. canvas.removeEventListener("pointerup", this._onPointerUp);
  11204. canvas.removeEventListener("pointerout", this._onPointerUp);
  11205. canvas.removeEventListener("pointermove", this._onPointerMove);
  11206. BABYLON.Tools.UnregisterTopRootEvents([
  11207. { name: "blur", handler: this._onLostFocus }
  11208. ]);
  11209. this._attachedCanvas = null;
  11210. };
  11211. TouchCamera.prototype._checkInputs = function () {
  11212. if (this._offsetX) {
  11213. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11214. if (this._pointerPressed.length > 1) {
  11215. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11216. }
  11217. else {
  11218. var speed = this._computeLocalCameraSpeed();
  11219. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11220. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11221. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11222. }
  11223. }
  11224. _super.prototype._checkInputs.call(this);
  11225. };
  11226. return TouchCamera;
  11227. })(BABYLON.FreeCamera);
  11228. BABYLON.TouchCamera = TouchCamera;
  11229. })(BABYLON || (BABYLON = {}));
  11230. var BABYLON;
  11231. (function (BABYLON) {
  11232. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11233. var ArcRotateCamera = (function (_super) {
  11234. __extends(ArcRotateCamera, _super);
  11235. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11236. var _this = this;
  11237. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11238. this.alpha = alpha;
  11239. this.beta = beta;
  11240. this.radius = radius;
  11241. this.target = target;
  11242. this.inertialAlphaOffset = 0;
  11243. this.inertialBetaOffset = 0;
  11244. this.inertialRadiusOffset = 0;
  11245. this.lowerAlphaLimit = null;
  11246. this.upperAlphaLimit = null;
  11247. this.lowerBetaLimit = 0.01;
  11248. this.upperBetaLimit = Math.PI;
  11249. this.lowerRadiusLimit = null;
  11250. this.upperRadiusLimit = null;
  11251. this.angularSensibilityX = 1000.0;
  11252. this.angularSensibilityY = 1000.0;
  11253. this.wheelPrecision = 3.0;
  11254. this.pinchPrecision = 2.0;
  11255. this.panningSensibility = 50.0;
  11256. this.inertialPanningX = 0;
  11257. this.inertialPanningY = 0;
  11258. this.keysUp = [38];
  11259. this.keysDown = [40];
  11260. this.keysLeft = [37];
  11261. this.keysRight = [39];
  11262. this.zoomOnFactor = 1;
  11263. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11264. this.pinchInwards = true;
  11265. this.allowUpsideDown = true;
  11266. this._keys = [];
  11267. this._viewMatrix = new BABYLON.Matrix();
  11268. this._isRightClick = false;
  11269. this._isCtrlPushed = false;
  11270. this.checkCollisions = false;
  11271. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11272. this._collider = new BABYLON.Collider();
  11273. this._previousPosition = BABYLON.Vector3.Zero();
  11274. this._collisionVelocity = BABYLON.Vector3.Zero();
  11275. this._newPosition = BABYLON.Vector3.Zero();
  11276. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11277. if (collidedMesh === void 0) { collidedMesh = null; }
  11278. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11279. newPosition.multiplyInPlace(_this._collider.radius);
  11280. }
  11281. if (!collidedMesh) {
  11282. _this._previousPosition.copyFrom(_this.position);
  11283. }
  11284. else {
  11285. _this.setPosition(newPosition);
  11286. if (_this.onCollide) {
  11287. _this.onCollide(collidedMesh);
  11288. }
  11289. }
  11290. // Recompute because of constraints
  11291. var cosa = Math.cos(_this.alpha);
  11292. var sina = Math.sin(_this.alpha);
  11293. var cosb = Math.cos(_this.beta);
  11294. var sinb = Math.sin(_this.beta);
  11295. var target = _this._getTargetPosition();
  11296. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11297. _this.position.copyFrom(_this._newPosition);
  11298. var up = _this.upVector;
  11299. if (_this.allowUpsideDown && _this.beta < 0) {
  11300. up = up.clone();
  11301. up = up.negate();
  11302. }
  11303. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11304. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11305. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11306. _this._collisionTriggered = false;
  11307. };
  11308. if (!this.target) {
  11309. this.target = BABYLON.Vector3.Zero();
  11310. }
  11311. this.getViewMatrix();
  11312. }
  11313. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11314. //deprecated angularSensibility support
  11315. get: function () {
  11316. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11317. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11318. },
  11319. //deprecated angularSensibility support
  11320. set: function (value) {
  11321. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11322. this.angularSensibilityX = value;
  11323. this.angularSensibilityY = value;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. ArcRotateCamera.prototype._getTargetPosition = function () {
  11329. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11330. };
  11331. // Cache
  11332. ArcRotateCamera.prototype._initCache = function () {
  11333. _super.prototype._initCache.call(this);
  11334. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11335. this._cache.alpha = undefined;
  11336. this._cache.beta = undefined;
  11337. this._cache.radius = undefined;
  11338. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11339. };
  11340. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11341. if (!ignoreParentClass) {
  11342. _super.prototype._updateCache.call(this);
  11343. }
  11344. this._cache.target.copyFrom(this._getTargetPosition());
  11345. this._cache.alpha = this.alpha;
  11346. this._cache.beta = this.beta;
  11347. this._cache.radius = this.radius;
  11348. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11349. };
  11350. // Synchronized
  11351. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11352. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11353. return false;
  11354. return this._cache.target.equals(this._getTargetPosition())
  11355. && this._cache.alpha === this.alpha
  11356. && this._cache.beta === this.beta
  11357. && this._cache.radius === this.radius
  11358. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11359. };
  11360. // Methods
  11361. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11362. var _this = this;
  11363. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11364. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11365. var previousPinchDistance = 0;
  11366. var pointers = new BABYLON.SmartCollection();
  11367. if (this._attachedElement) {
  11368. return;
  11369. }
  11370. this._attachedElement = element;
  11371. var engine = this.getEngine();
  11372. if (this._onPointerDown === undefined) {
  11373. this._onPointerDown = function (evt) {
  11374. // Manage panning with right click
  11375. _this._isRightClick = evt.button === 2;
  11376. // manage pointers
  11377. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11378. cacheSoloPointer = pointers.item(evt.pointerId);
  11379. if (!noPreventDefault) {
  11380. evt.preventDefault();
  11381. }
  11382. };
  11383. this._onPointerUp = function (evt) {
  11384. cacheSoloPointer = null;
  11385. previousPinchDistance = 0;
  11386. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11387. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11388. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11389. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11390. pointers.empty();
  11391. if (!noPreventDefault) {
  11392. evt.preventDefault();
  11393. }
  11394. };
  11395. this._onContextMenu = function (evt) {
  11396. evt.preventDefault();
  11397. };
  11398. this._onPointerMove = function (evt) {
  11399. if (!noPreventDefault) {
  11400. evt.preventDefault();
  11401. }
  11402. switch (pointers.count) {
  11403. case 1:
  11404. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11405. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11406. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11407. }
  11408. else {
  11409. var offsetX = evt.clientX - cacheSoloPointer.x;
  11410. var offsetY = evt.clientY - cacheSoloPointer.y;
  11411. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11412. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11413. }
  11414. cacheSoloPointer.x = evt.clientX;
  11415. cacheSoloPointer.y = evt.clientY;
  11416. break;
  11417. case 2:
  11418. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11419. pointers.item(evt.pointerId).x = evt.clientX;
  11420. pointers.item(evt.pointerId).y = evt.clientY;
  11421. var direction = _this.pinchInwards ? 1 : -1;
  11422. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11423. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11424. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11425. if (previousPinchDistance === 0) {
  11426. previousPinchDistance = pinchSquaredDistance;
  11427. return;
  11428. }
  11429. if (pinchSquaredDistance !== previousPinchDistance) {
  11430. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11431. previousPinchDistance = pinchSquaredDistance;
  11432. }
  11433. break;
  11434. default:
  11435. if (pointers.item(evt.pointerId)) {
  11436. pointers.item(evt.pointerId).x = evt.clientX;
  11437. pointers.item(evt.pointerId).y = evt.clientY;
  11438. }
  11439. }
  11440. };
  11441. this._onMouseMove = function (evt) {
  11442. if (!engine.isPointerLock) {
  11443. return;
  11444. }
  11445. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11446. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11447. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11448. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11449. if (!noPreventDefault) {
  11450. evt.preventDefault();
  11451. }
  11452. };
  11453. this._wheel = function (event) {
  11454. var delta = 0;
  11455. if (event.wheelDelta) {
  11456. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11457. }
  11458. else if (event.detail) {
  11459. delta = -event.detail / _this.wheelPrecision;
  11460. }
  11461. if (delta)
  11462. _this.inertialRadiusOffset += delta;
  11463. if (event.preventDefault) {
  11464. if (!noPreventDefault) {
  11465. event.preventDefault();
  11466. }
  11467. }
  11468. };
  11469. this._onKeyDown = function (evt) {
  11470. _this._isCtrlPushed = evt.ctrlKey;
  11471. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11472. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11473. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11474. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11475. var index = _this._keys.indexOf(evt.keyCode);
  11476. if (index === -1) {
  11477. _this._keys.push(evt.keyCode);
  11478. }
  11479. if (evt.preventDefault) {
  11480. if (!noPreventDefault) {
  11481. evt.preventDefault();
  11482. }
  11483. }
  11484. }
  11485. };
  11486. this._onKeyUp = function (evt) {
  11487. _this._isCtrlPushed = evt.ctrlKey;
  11488. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11489. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11490. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11491. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11492. var index = _this._keys.indexOf(evt.keyCode);
  11493. if (index >= 0) {
  11494. _this._keys.splice(index, 1);
  11495. }
  11496. if (evt.preventDefault) {
  11497. if (!noPreventDefault) {
  11498. evt.preventDefault();
  11499. }
  11500. }
  11501. }
  11502. };
  11503. this._onLostFocus = function () {
  11504. _this._keys = [];
  11505. pointers.empty();
  11506. previousPinchDistance = 0;
  11507. cacheSoloPointer = null;
  11508. };
  11509. this._onGestureStart = function (e) {
  11510. if (window.MSGesture === undefined) {
  11511. return;
  11512. }
  11513. if (!_this._MSGestureHandler) {
  11514. _this._MSGestureHandler = new MSGesture();
  11515. _this._MSGestureHandler.target = element;
  11516. }
  11517. _this._MSGestureHandler.addPointer(e.pointerId);
  11518. };
  11519. this._onGesture = function (e) {
  11520. _this.radius *= e.scale;
  11521. if (e.preventDefault) {
  11522. if (!noPreventDefault) {
  11523. e.stopPropagation();
  11524. e.preventDefault();
  11525. }
  11526. }
  11527. };
  11528. this._reset = function () {
  11529. _this._keys = [];
  11530. _this.inertialAlphaOffset = 0;
  11531. _this.inertialBetaOffset = 0;
  11532. _this.inertialRadiusOffset = 0;
  11533. pointers.empty();
  11534. previousPinchDistance = 0;
  11535. cacheSoloPointer = null;
  11536. };
  11537. }
  11538. if (!useCtrlForPanning) {
  11539. element.addEventListener("contextmenu", this._onContextMenu, false);
  11540. }
  11541. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11542. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11543. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11544. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11545. element.addEventListener("mousemove", this._onMouseMove, false);
  11546. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11547. element.addEventListener("MSGestureChange", this._onGesture, false);
  11548. element.addEventListener('mousewheel', this._wheel, false);
  11549. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11550. BABYLON.Tools.RegisterTopRootEvents([
  11551. { name: "keydown", handler: this._onKeyDown },
  11552. { name: "keyup", handler: this._onKeyUp },
  11553. { name: "blur", handler: this._onLostFocus }
  11554. ]);
  11555. };
  11556. ArcRotateCamera.prototype.detachControl = function (element) {
  11557. if (this._attachedElement !== element) {
  11558. return;
  11559. }
  11560. element.removeEventListener("contextmenu", this._onContextMenu);
  11561. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11562. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11563. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11564. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11565. element.removeEventListener("mousemove", this._onMouseMove);
  11566. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11567. element.removeEventListener("MSGestureChange", this._onGesture);
  11568. element.removeEventListener('mousewheel', this._wheel);
  11569. element.removeEventListener('DOMMouseScroll', this._wheel);
  11570. BABYLON.Tools.UnregisterTopRootEvents([
  11571. { name: "keydown", handler: this._onKeyDown },
  11572. { name: "keyup", handler: this._onKeyUp },
  11573. { name: "blur", handler: this._onLostFocus }
  11574. ]);
  11575. this._MSGestureHandler = null;
  11576. this._attachedElement = null;
  11577. if (this._reset) {
  11578. this._reset();
  11579. }
  11580. };
  11581. ArcRotateCamera.prototype._checkInputs = function () {
  11582. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11583. if (this._collisionTriggered) {
  11584. return;
  11585. }
  11586. // Keyboard
  11587. for (var index = 0; index < this._keys.length; index++) {
  11588. var keyCode = this._keys[index];
  11589. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11590. this.inertialAlphaOffset -= 0.01;
  11591. }
  11592. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11593. this.inertialBetaOffset -= 0.01;
  11594. }
  11595. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11596. this.inertialAlphaOffset += 0.01;
  11597. }
  11598. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11599. this.inertialBetaOffset += 0.01;
  11600. }
  11601. }
  11602. // Inertia
  11603. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11604. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11605. this.beta += this.inertialBetaOffset;
  11606. this.radius -= this.inertialRadiusOffset;
  11607. this.inertialAlphaOffset *= this.inertia;
  11608. this.inertialBetaOffset *= this.inertia;
  11609. this.inertialRadiusOffset *= this.inertia;
  11610. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11611. this.inertialAlphaOffset = 0;
  11612. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11613. this.inertialBetaOffset = 0;
  11614. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11615. this.inertialRadiusOffset = 0;
  11616. }
  11617. // Panning inertia
  11618. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11619. if (!this._localDirection) {
  11620. this._localDirection = BABYLON.Vector3.Zero();
  11621. this._transformedDirection = BABYLON.Vector3.Zero();
  11622. }
  11623. this.inertialPanningX *= this.inertia;
  11624. this.inertialPanningY *= this.inertia;
  11625. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11626. this.inertialPanningX = 0;
  11627. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11628. this.inertialPanningY = 0;
  11629. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11630. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11631. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11632. this.target.addInPlace(this._transformedDirection);
  11633. }
  11634. // Limits
  11635. this._checkLimits();
  11636. _super.prototype._checkInputs.call(this);
  11637. };
  11638. ArcRotateCamera.prototype._checkLimits = function () {
  11639. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11640. if (this.allowUpsideDown && this.beta > Math.PI) {
  11641. this.beta = this.beta - (2 * Math.PI);
  11642. }
  11643. }
  11644. else {
  11645. if (this.beta < this.lowerBetaLimit) {
  11646. this.beta = this.lowerBetaLimit;
  11647. }
  11648. }
  11649. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11650. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11651. this.beta = this.beta + (2 * Math.PI);
  11652. }
  11653. }
  11654. else {
  11655. if (this.beta > this.upperBetaLimit) {
  11656. this.beta = this.upperBetaLimit;
  11657. }
  11658. }
  11659. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11660. this.alpha = this.lowerAlphaLimit;
  11661. }
  11662. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11663. this.alpha = this.upperAlphaLimit;
  11664. }
  11665. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11666. this.radius = this.lowerRadiusLimit;
  11667. }
  11668. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11669. this.radius = this.upperRadiusLimit;
  11670. }
  11671. };
  11672. ArcRotateCamera.prototype.setPosition = function (position) {
  11673. if (this.position.equals(position)) {
  11674. return;
  11675. }
  11676. var radiusv3 = position.subtract(this._getTargetPosition());
  11677. this.radius = radiusv3.length();
  11678. // Alpha
  11679. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11680. if (radiusv3.z < 0) {
  11681. this.alpha = 2 * Math.PI - this.alpha;
  11682. }
  11683. // Beta
  11684. this.beta = Math.acos(radiusv3.y / this.radius);
  11685. this._checkLimits();
  11686. };
  11687. ArcRotateCamera.prototype.setTarget = function (target) {
  11688. this.target = target;
  11689. };
  11690. ArcRotateCamera.prototype._getViewMatrix = function () {
  11691. // Compute
  11692. var cosa = Math.cos(this.alpha);
  11693. var sina = Math.sin(this.alpha);
  11694. var cosb = Math.cos(this.beta);
  11695. var sinb = Math.sin(this.beta);
  11696. var target = this._getTargetPosition();
  11697. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11698. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11699. this._collider.radius = this.collisionRadius;
  11700. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11701. this._collisionTriggered = true;
  11702. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11703. }
  11704. else {
  11705. this.position.copyFrom(this._newPosition);
  11706. var up = this.upVector;
  11707. if (this.allowUpsideDown && this.beta < 0) {
  11708. up = up.clone();
  11709. up = up.negate();
  11710. }
  11711. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11712. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11713. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11714. }
  11715. return this._viewMatrix;
  11716. };
  11717. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11718. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11719. meshes = meshes || this.getScene().meshes;
  11720. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11721. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11722. this.radius = distance * this.zoomOnFactor;
  11723. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11724. };
  11725. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11726. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11727. var meshesOrMinMaxVector;
  11728. var distance;
  11729. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11730. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11731. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11732. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11733. }
  11734. else {
  11735. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11736. distance = meshesOrMinMaxVectorAndDistance.distance;
  11737. }
  11738. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11739. if (!doNotUpdateMaxZ) {
  11740. this.maxZ = distance * 2;
  11741. }
  11742. };
  11743. /**
  11744. * @override
  11745. * Override Camera.createRigCamera
  11746. */
  11747. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11748. switch (this.cameraRigMode) {
  11749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11753. case BABYLON.Camera.RIG_MODE_VR:
  11754. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11755. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11756. }
  11757. return null;
  11758. };
  11759. /**
  11760. * @override
  11761. * Override Camera._updateRigCameras
  11762. */
  11763. ArcRotateCamera.prototype._updateRigCameras = function () {
  11764. switch (this.cameraRigMode) {
  11765. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11766. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11768. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11769. case BABYLON.Camera.RIG_MODE_VR:
  11770. var camLeft = this._rigCameras[0];
  11771. var camRight = this._rigCameras[1];
  11772. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11773. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11774. camLeft.beta = camRight.beta = this.beta;
  11775. camLeft.radius = camRight.radius = this.radius;
  11776. break;
  11777. }
  11778. _super.prototype._updateRigCameras.call(this);
  11779. };
  11780. ArcRotateCamera.prototype.serialize = function () {
  11781. var serializationObject = _super.prototype.serialize.call(this);
  11782. if (this.target instanceof BABYLON.Vector3) {
  11783. serializationObject.target = this.target.asArray();
  11784. }
  11785. if (this.target && this.target.id) {
  11786. serializationObject.lockedTargetId = this.target.id;
  11787. }
  11788. serializationObject.checkCollisions = this.checkCollisions;
  11789. serializationObject.alpha = this.alpha;
  11790. serializationObject.beta = this.beta;
  11791. serializationObject.radius = this.radius;
  11792. return serializationObject;
  11793. };
  11794. return ArcRotateCamera;
  11795. })(BABYLON.TargetCamera);
  11796. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11797. })(BABYLON || (BABYLON = {}));
  11798. var BABYLON;
  11799. (function (BABYLON) {
  11800. var RenderingManager = (function () {
  11801. function RenderingManager(scene) {
  11802. this._renderingGroups = new Array();
  11803. this._scene = scene;
  11804. }
  11805. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11806. if (this._scene._activeParticleSystems.length === 0) {
  11807. return;
  11808. }
  11809. // Particles
  11810. var activeCamera = this._scene.activeCamera;
  11811. var beforeParticlesDate = BABYLON.Tools.Now;
  11812. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11813. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11814. if (particleSystem.renderingGroupId !== index) {
  11815. continue;
  11816. }
  11817. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11818. continue;
  11819. }
  11820. this._clearDepthBuffer();
  11821. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11822. this._scene._activeParticles += particleSystem.render();
  11823. }
  11824. }
  11825. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11826. };
  11827. RenderingManager.prototype._renderSprites = function (index) {
  11828. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11829. return;
  11830. }
  11831. // Sprites
  11832. var activeCamera = this._scene.activeCamera;
  11833. var beforeSpritessDate = BABYLON.Tools.Now;
  11834. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11835. var spriteManager = this._scene.spriteManagers[id];
  11836. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11837. this._clearDepthBuffer();
  11838. spriteManager.render();
  11839. }
  11840. }
  11841. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11842. };
  11843. RenderingManager.prototype._clearDepthBuffer = function () {
  11844. if (this._depthBufferAlreadyCleaned) {
  11845. return;
  11846. }
  11847. this._scene.getEngine().clear(0, false, true);
  11848. this._depthBufferAlreadyCleaned = true;
  11849. };
  11850. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11851. if (this._currentRenderSprites) {
  11852. this._renderSprites(this._currentIndex);
  11853. }
  11854. if (this._currentRenderParticles) {
  11855. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11856. }
  11857. };
  11858. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11859. this._currentActiveMeshes = activeMeshes;
  11860. this._currentRenderParticles = renderParticles;
  11861. this._currentRenderSprites = renderSprites;
  11862. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11863. this._depthBufferAlreadyCleaned = index == 0;
  11864. var renderingGroup = this._renderingGroups[index];
  11865. var needToStepBack = false;
  11866. this._currentIndex = index;
  11867. if (renderingGroup) {
  11868. this._clearDepthBuffer();
  11869. if (!renderingGroup.onBeforeTransparentRendering) {
  11870. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11871. }
  11872. if (!renderingGroup.render(customRenderFunction)) {
  11873. this._renderingGroups.splice(index, 1);
  11874. needToStepBack = true;
  11875. this._renderSpritesAndParticles();
  11876. }
  11877. }
  11878. else {
  11879. this._renderSpritesAndParticles();
  11880. }
  11881. if (needToStepBack) {
  11882. index--;
  11883. }
  11884. }
  11885. };
  11886. RenderingManager.prototype.reset = function () {
  11887. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11888. if (renderingGroup) {
  11889. renderingGroup.prepare();
  11890. }
  11891. });
  11892. };
  11893. RenderingManager.prototype.dispatch = function (subMesh) {
  11894. var mesh = subMesh.getMesh();
  11895. var renderingGroupId = mesh.renderingGroupId || 0;
  11896. if (!this._renderingGroups[renderingGroupId]) {
  11897. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11898. }
  11899. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11900. };
  11901. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11902. return RenderingManager;
  11903. })();
  11904. BABYLON.RenderingManager = RenderingManager;
  11905. })(BABYLON || (BABYLON = {}));
  11906. var BABYLON;
  11907. (function (BABYLON) {
  11908. var RenderingGroup = (function () {
  11909. function RenderingGroup(index, scene) {
  11910. this.index = index;
  11911. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11912. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11913. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11914. this._scene = scene;
  11915. }
  11916. RenderingGroup.prototype.render = function (customRenderFunction) {
  11917. if (customRenderFunction) {
  11918. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11919. return true;
  11920. }
  11921. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11922. if (this.onBeforeTransparentRendering) {
  11923. this.onBeforeTransparentRendering();
  11924. }
  11925. return false;
  11926. }
  11927. var engine = this._scene.getEngine();
  11928. // Opaque
  11929. var subIndex;
  11930. var submesh;
  11931. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11932. submesh = this._opaqueSubMeshes.data[subIndex];
  11933. submesh.render(false);
  11934. }
  11935. // Alpha test
  11936. engine.setAlphaTesting(true);
  11937. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11938. submesh = this._alphaTestSubMeshes.data[subIndex];
  11939. submesh.render(false);
  11940. }
  11941. engine.setAlphaTesting(false);
  11942. if (this.onBeforeTransparentRendering) {
  11943. this.onBeforeTransparentRendering();
  11944. }
  11945. // Transparent
  11946. if (this._transparentSubMeshes.length) {
  11947. // Sorting
  11948. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11949. submesh = this._transparentSubMeshes.data[subIndex];
  11950. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11951. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11952. }
  11953. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11954. sortedArray.sort(function (a, b) {
  11955. // Alpha index first
  11956. if (a._alphaIndex > b._alphaIndex) {
  11957. return 1;
  11958. }
  11959. if (a._alphaIndex < b._alphaIndex) {
  11960. return -1;
  11961. }
  11962. // Then distance to camera
  11963. if (a._distanceToCamera < b._distanceToCamera) {
  11964. return 1;
  11965. }
  11966. if (a._distanceToCamera > b._distanceToCamera) {
  11967. return -1;
  11968. }
  11969. return 0;
  11970. });
  11971. // Rendering
  11972. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11973. submesh = sortedArray[subIndex];
  11974. submesh.render(true);
  11975. }
  11976. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11977. }
  11978. return true;
  11979. };
  11980. RenderingGroup.prototype.prepare = function () {
  11981. this._opaqueSubMeshes.reset();
  11982. this._transparentSubMeshes.reset();
  11983. this._alphaTestSubMeshes.reset();
  11984. };
  11985. RenderingGroup.prototype.dispatch = function (subMesh) {
  11986. var material = subMesh.getMaterial();
  11987. var mesh = subMesh.getMesh();
  11988. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11989. this._transparentSubMeshes.push(subMesh);
  11990. }
  11991. else if (material.needAlphaTesting()) {
  11992. this._alphaTestSubMeshes.push(subMesh);
  11993. }
  11994. else {
  11995. this._opaqueSubMeshes.push(subMesh); // Opaque
  11996. }
  11997. };
  11998. return RenderingGroup;
  11999. })();
  12000. BABYLON.RenderingGroup = RenderingGroup;
  12001. })(BABYLON || (BABYLON = {}));
  12002. var BABYLON;
  12003. (function (BABYLON) {
  12004. /**
  12005. * Represents a scene to be rendered by the engine.
  12006. * @see http://doc.babylonjs.com/page.php?p=21911
  12007. */
  12008. var Scene = (function () {
  12009. /**
  12010. * @constructor
  12011. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12012. */
  12013. function Scene(engine) {
  12014. // Members
  12015. this.autoClear = true;
  12016. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12017. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12018. this.forceWireframe = false;
  12019. this.forcePointsCloud = false;
  12020. this.forceShowBoundingBoxes = false;
  12021. this.animationsEnabled = true;
  12022. this.constantlyUpdateMeshUnderPointer = false;
  12023. 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
  12024. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12025. this._startingPointerTime = 0;
  12026. // Fog
  12027. /**
  12028. * is fog enabled on this scene.
  12029. * @type {boolean}
  12030. */
  12031. this.fogEnabled = true;
  12032. this.fogMode = Scene.FOGMODE_NONE;
  12033. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12034. this.fogDensity = 0.1;
  12035. this.fogStart = 0;
  12036. this.fogEnd = 1000.0;
  12037. // Lights
  12038. /**
  12039. * is shadow enabled on this scene.
  12040. * @type {boolean}
  12041. */
  12042. this.shadowsEnabled = true;
  12043. /**
  12044. * is light enabled on this scene.
  12045. * @type {boolean}
  12046. */
  12047. this.lightsEnabled = true;
  12048. /**
  12049. * All of the lights added to this scene.
  12050. * @see BABYLON.Light
  12051. * @type {BABYLON.Light[]}
  12052. */
  12053. this.lights = new Array();
  12054. // Cameras
  12055. /**
  12056. * All of the cameras added to this scene.
  12057. * @see BABYLON.Camera
  12058. * @type {BABYLON.Camera[]}
  12059. */
  12060. this.cameras = new Array();
  12061. this.activeCameras = new Array();
  12062. // Meshes
  12063. /**
  12064. * All of the (abstract) meshes added to this scene.
  12065. * @see BABYLON.AbstractMesh
  12066. * @type {BABYLON.AbstractMesh[]}
  12067. */
  12068. this.meshes = new Array();
  12069. // Geometries
  12070. this._geometries = new Array();
  12071. this.materials = new Array();
  12072. this.multiMaterials = new Array();
  12073. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12074. // Textures
  12075. this.texturesEnabled = true;
  12076. this.textures = new Array();
  12077. // Particles
  12078. this.particlesEnabled = true;
  12079. this.particleSystems = new Array();
  12080. // Sprites
  12081. this.spritesEnabled = true;
  12082. this.spriteManagers = new Array();
  12083. // Layers
  12084. this.layers = new Array();
  12085. // Skeletons
  12086. this.skeletonsEnabled = true;
  12087. this.skeletons = new Array();
  12088. // Lens flares
  12089. this.lensFlaresEnabled = true;
  12090. this.lensFlareSystems = new Array();
  12091. // Collisions
  12092. this.collisionsEnabled = true;
  12093. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12094. // Postprocesses
  12095. this.postProcessesEnabled = true;
  12096. // Customs render targets
  12097. this.renderTargetsEnabled = true;
  12098. this.dumpNextRenderTargets = false;
  12099. this.customRenderTargets = new Array();
  12100. // Imported meshes
  12101. this.importedMeshesFiles = new Array();
  12102. // Probes
  12103. this.probesEnabled = true;
  12104. this.reflectionProbes = new Array();
  12105. this._actionManagers = new Array();
  12106. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12107. // Procedural textures
  12108. this.proceduralTexturesEnabled = true;
  12109. this._proceduralTextures = new Array();
  12110. this.soundTracks = new Array();
  12111. this._audioEnabled = true;
  12112. this._headphone = false;
  12113. this._totalVertices = 0;
  12114. this._activeIndices = 0;
  12115. this._activeParticles = 0;
  12116. this._lastFrameDuration = 0;
  12117. this._evaluateActiveMeshesDuration = 0;
  12118. this._renderTargetsDuration = 0;
  12119. this._particlesDuration = 0;
  12120. this._renderDuration = 0;
  12121. this._spritesDuration = 0;
  12122. this._animationRatio = 0;
  12123. this._renderId = 0;
  12124. this._executeWhenReadyTimeoutId = -1;
  12125. this._toBeDisposed = new BABYLON.SmartArray(256);
  12126. this._onReadyCallbacks = new Array();
  12127. this._pendingData = []; //ANY
  12128. this._onBeforeRenderCallbacks = new Array();
  12129. this._onAfterRenderCallbacks = new Array();
  12130. this._activeMeshes = new BABYLON.SmartArray(256);
  12131. this._processedMaterials = new BABYLON.SmartArray(256);
  12132. this._renderTargets = new BABYLON.SmartArray(256);
  12133. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12134. this._activeSkeletons = new BABYLON.SmartArray(32);
  12135. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12136. this._activeBones = 0;
  12137. this._activeAnimatables = new Array();
  12138. this._transformMatrix = BABYLON.Matrix.Zero();
  12139. this._edgesRenderers = new BABYLON.SmartArray(16);
  12140. this._uniqueIdCounter = 0;
  12141. this._engine = engine;
  12142. engine.scenes.push(this);
  12143. this._renderingManager = new BABYLON.RenderingManager(this);
  12144. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12145. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12146. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12147. if (BABYLON.OutlineRenderer) {
  12148. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12149. }
  12150. this.attachControl();
  12151. this._debugLayer = new BABYLON.DebugLayer(this);
  12152. if (BABYLON.SoundTrack) {
  12153. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12154. }
  12155. //simplification queue
  12156. if (BABYLON.SimplificationQueue) {
  12157. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12158. }
  12159. //collision coordinator initialization. For now legacy per default.
  12160. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12161. }
  12162. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12163. get: function () {
  12164. return Scene._FOGMODE_NONE;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12170. get: function () {
  12171. return Scene._FOGMODE_EXP;
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12177. get: function () {
  12178. return Scene._FOGMODE_EXP2;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12184. get: function () {
  12185. return Scene._FOGMODE_LINEAR;
  12186. },
  12187. enumerable: true,
  12188. configurable: true
  12189. });
  12190. Object.defineProperty(Scene.prototype, "debugLayer", {
  12191. // Properties
  12192. get: function () {
  12193. return this._debugLayer;
  12194. },
  12195. enumerable: true,
  12196. configurable: true
  12197. });
  12198. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12199. get: function () {
  12200. return this._workerCollisions;
  12201. },
  12202. set: function (enabled) {
  12203. enabled = (enabled && !!Worker);
  12204. this._workerCollisions = enabled;
  12205. if (this.collisionCoordinator) {
  12206. this.collisionCoordinator.destroy();
  12207. }
  12208. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12209. this.collisionCoordinator.init(this);
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12215. get: function () {
  12216. return this._selectionOctree;
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12222. /**
  12223. * The mesh that is currently under the pointer.
  12224. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12225. */
  12226. get: function () {
  12227. return this._meshUnderPointer;
  12228. },
  12229. enumerable: true,
  12230. configurable: true
  12231. });
  12232. Object.defineProperty(Scene.prototype, "pointerX", {
  12233. /**
  12234. * Current on-screen X position of the pointer
  12235. * @return {number} X position of the pointer
  12236. */
  12237. get: function () {
  12238. return this._pointerX;
  12239. },
  12240. enumerable: true,
  12241. configurable: true
  12242. });
  12243. Object.defineProperty(Scene.prototype, "pointerY", {
  12244. /**
  12245. * Current on-screen Y position of the pointer
  12246. * @return {number} Y position of the pointer
  12247. */
  12248. get: function () {
  12249. return this._pointerY;
  12250. },
  12251. enumerable: true,
  12252. configurable: true
  12253. });
  12254. Scene.prototype.getCachedMaterial = function () {
  12255. return this._cachedMaterial;
  12256. };
  12257. Scene.prototype.getBoundingBoxRenderer = function () {
  12258. return this._boundingBoxRenderer;
  12259. };
  12260. Scene.prototype.getOutlineRenderer = function () {
  12261. return this._outlineRenderer;
  12262. };
  12263. Scene.prototype.getEngine = function () {
  12264. return this._engine;
  12265. };
  12266. Scene.prototype.getTotalVertices = function () {
  12267. return this._totalVertices;
  12268. };
  12269. Scene.prototype.getActiveIndices = function () {
  12270. return this._activeIndices;
  12271. };
  12272. Scene.prototype.getActiveParticles = function () {
  12273. return this._activeParticles;
  12274. };
  12275. Scene.prototype.getActiveBones = function () {
  12276. return this._activeBones;
  12277. };
  12278. // Stats
  12279. Scene.prototype.getLastFrameDuration = function () {
  12280. return this._lastFrameDuration;
  12281. };
  12282. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12283. return this._evaluateActiveMeshesDuration;
  12284. };
  12285. Scene.prototype.getActiveMeshes = function () {
  12286. return this._activeMeshes;
  12287. };
  12288. Scene.prototype.getRenderTargetsDuration = function () {
  12289. return this._renderTargetsDuration;
  12290. };
  12291. Scene.prototype.getRenderDuration = function () {
  12292. return this._renderDuration;
  12293. };
  12294. Scene.prototype.getParticlesDuration = function () {
  12295. return this._particlesDuration;
  12296. };
  12297. Scene.prototype.getSpritesDuration = function () {
  12298. return this._spritesDuration;
  12299. };
  12300. Scene.prototype.getAnimationRatio = function () {
  12301. return this._animationRatio;
  12302. };
  12303. Scene.prototype.getRenderId = function () {
  12304. return this._renderId;
  12305. };
  12306. Scene.prototype.incrementRenderId = function () {
  12307. this._renderId++;
  12308. };
  12309. Scene.prototype._updatePointerPosition = function (evt) {
  12310. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12311. this._pointerX = evt.clientX - canvasRect.left;
  12312. this._pointerY = evt.clientY - canvasRect.top;
  12313. if (this.cameraToUseForPointers) {
  12314. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12315. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12316. }
  12317. };
  12318. // Pointers handling
  12319. Scene.prototype.attachControl = function () {
  12320. var _this = this;
  12321. var spritePredicate = function (sprite) {
  12322. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12323. };
  12324. this._onPointerMove = function (evt) {
  12325. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12326. return;
  12327. }
  12328. var canvas = _this._engine.getRenderingCanvas();
  12329. _this._updatePointerPosition(evt);
  12330. // Meshes
  12331. 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);
  12332. if (pickResult.hit && pickResult.pickedMesh) {
  12333. _this._meshUnderPointer = pickResult.pickedMesh;
  12334. _this.setPointerOverMesh(pickResult.pickedMesh);
  12335. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12336. canvas.style.cursor = "pointer";
  12337. }
  12338. else {
  12339. canvas.style.cursor = "";
  12340. }
  12341. }
  12342. else {
  12343. // Sprites
  12344. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12345. if (pickResult.hit && pickResult.pickedSprite) {
  12346. canvas.style.cursor = "pointer";
  12347. }
  12348. else {
  12349. // Restore pointer
  12350. _this.setPointerOverMesh(null);
  12351. canvas.style.cursor = "";
  12352. _this._meshUnderPointer = null;
  12353. }
  12354. }
  12355. if (_this.onPointerMove) {
  12356. _this.onPointerMove(evt, pickResult);
  12357. }
  12358. };
  12359. this._onPointerDown = function (evt) {
  12360. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12361. return;
  12362. }
  12363. _this._updatePointerPosition(evt);
  12364. _this._startingPointerPosition.x = _this._pointerX;
  12365. _this._startingPointerPosition.y = _this._pointerY;
  12366. _this._startingPointerTime = new Date().getTime();
  12367. var predicate = null;
  12368. // Meshes
  12369. if (!_this.onPointerDown) {
  12370. predicate = function (mesh) {
  12371. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12372. };
  12373. }
  12374. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12375. if (pickResult.hit && pickResult.pickedMesh) {
  12376. if (pickResult.pickedMesh.actionManager) {
  12377. switch (evt.button) {
  12378. case 0:
  12379. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12380. break;
  12381. case 1:
  12382. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12383. break;
  12384. case 2:
  12385. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12386. break;
  12387. }
  12388. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12389. }
  12390. }
  12391. if (_this.onPointerDown) {
  12392. _this.onPointerDown(evt, pickResult);
  12393. }
  12394. // Sprites
  12395. if (_this.spriteManagers.length > 0) {
  12396. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12397. if (pickResult.hit && pickResult.pickedSprite) {
  12398. if (pickResult.pickedSprite.actionManager) {
  12399. switch (evt.button) {
  12400. case 0:
  12401. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12402. break;
  12403. case 1:
  12404. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12405. break;
  12406. case 2:
  12407. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12408. break;
  12409. }
  12410. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12411. }
  12412. }
  12413. }
  12414. };
  12415. this._onPointerUp = function (evt) {
  12416. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12417. return;
  12418. }
  12419. var predicate = null;
  12420. _this._updatePointerPosition(evt);
  12421. if (!_this.onPointerUp) {
  12422. predicate = function (mesh) {
  12423. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12424. };
  12425. }
  12426. // Meshes
  12427. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12428. if (pickResult.hit && pickResult.pickedMesh) {
  12429. if (pickResult.pickedMesh.actionManager) {
  12430. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12431. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12433. if ((new Date().getTime() - _this._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) {
  12434. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12435. ;
  12436. }
  12437. }
  12438. }
  12439. }
  12440. if (_this.onPointerUp) {
  12441. _this.onPointerUp(evt, pickResult);
  12442. }
  12443. // Sprites
  12444. if (_this.spriteManagers.length > 0) {
  12445. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12446. if (pickResult.hit && pickResult.pickedSprite) {
  12447. if (pickResult.pickedSprite.actionManager) {
  12448. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12449. }
  12450. }
  12451. }
  12452. };
  12453. this._onKeyDown = function (evt) {
  12454. if (_this.actionManager) {
  12455. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12456. }
  12457. };
  12458. this._onKeyUp = function (evt) {
  12459. if (_this.actionManager) {
  12460. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12461. }
  12462. };
  12463. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12464. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12465. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12466. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12467. // Wheel
  12468. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12469. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12470. BABYLON.Tools.RegisterTopRootEvents([
  12471. { name: "keydown", handler: this._onKeyDown },
  12472. { name: "keyup", handler: this._onKeyUp }
  12473. ]);
  12474. };
  12475. Scene.prototype.detachControl = function () {
  12476. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12477. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12478. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12479. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12480. // Wheel
  12481. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12482. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12483. BABYLON.Tools.UnregisterTopRootEvents([
  12484. { name: "keydown", handler: this._onKeyDown },
  12485. { name: "keyup", handler: this._onKeyUp }
  12486. ]);
  12487. };
  12488. // Ready
  12489. Scene.prototype.isReady = function () {
  12490. if (this._pendingData.length > 0) {
  12491. return false;
  12492. }
  12493. var index;
  12494. for (index = 0; index < this._geometries.length; index++) {
  12495. var geometry = this._geometries[index];
  12496. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12497. return false;
  12498. }
  12499. }
  12500. for (index = 0; index < this.meshes.length; index++) {
  12501. var mesh = this.meshes[index];
  12502. if (!mesh.isReady()) {
  12503. return false;
  12504. }
  12505. var mat = mesh.material;
  12506. if (mat) {
  12507. if (!mat.isReady(mesh)) {
  12508. return false;
  12509. }
  12510. }
  12511. }
  12512. return true;
  12513. };
  12514. Scene.prototype.resetCachedMaterial = function () {
  12515. this._cachedMaterial = null;
  12516. };
  12517. Scene.prototype.registerBeforeRender = function (func) {
  12518. this._onBeforeRenderCallbacks.push(func);
  12519. };
  12520. Scene.prototype.unregisterBeforeRender = function (func) {
  12521. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12522. if (index > -1) {
  12523. this._onBeforeRenderCallbacks.splice(index, 1);
  12524. }
  12525. };
  12526. Scene.prototype.registerAfterRender = function (func) {
  12527. this._onAfterRenderCallbacks.push(func);
  12528. };
  12529. Scene.prototype.unregisterAfterRender = function (func) {
  12530. var index = this._onAfterRenderCallbacks.indexOf(func);
  12531. if (index > -1) {
  12532. this._onAfterRenderCallbacks.splice(index, 1);
  12533. }
  12534. };
  12535. Scene.prototype._addPendingData = function (data) {
  12536. this._pendingData.push(data);
  12537. };
  12538. Scene.prototype._removePendingData = function (data) {
  12539. var index = this._pendingData.indexOf(data);
  12540. if (index !== -1) {
  12541. this._pendingData.splice(index, 1);
  12542. }
  12543. };
  12544. Scene.prototype.getWaitingItemsCount = function () {
  12545. return this._pendingData.length;
  12546. };
  12547. /**
  12548. * Registers a function to be executed when the scene is ready.
  12549. * @param {Function} func - the function to be executed.
  12550. */
  12551. Scene.prototype.executeWhenReady = function (func) {
  12552. var _this = this;
  12553. this._onReadyCallbacks.push(func);
  12554. if (this._executeWhenReadyTimeoutId !== -1) {
  12555. return;
  12556. }
  12557. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12558. _this._checkIsReady();
  12559. }, 150);
  12560. };
  12561. Scene.prototype._checkIsReady = function () {
  12562. var _this = this;
  12563. if (this.isReady()) {
  12564. this._onReadyCallbacks.forEach(function (func) {
  12565. func();
  12566. });
  12567. this._onReadyCallbacks = [];
  12568. this._executeWhenReadyTimeoutId = -1;
  12569. return;
  12570. }
  12571. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12572. _this._checkIsReady();
  12573. }, 150);
  12574. };
  12575. // Animations
  12576. /**
  12577. * Will start the animation sequence of a given target
  12578. * @param target - the target
  12579. * @param {number} from - from which frame should animation start
  12580. * @param {number} to - till which frame should animation run.
  12581. * @param {boolean} [loop] - should the animation loop
  12582. * @param {number} [speedRatio] - the speed in which to run the animation
  12583. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12584. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12585. * @return {BABYLON.Animatable} the animatable object created for this animation
  12586. * @see BABYLON.Animatable
  12587. * @see http://doc.babylonjs.com/page.php?p=22081
  12588. */
  12589. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12590. if (speedRatio === void 0) { speedRatio = 1.0; }
  12591. this.stopAnimation(target);
  12592. if (!animatable) {
  12593. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12594. }
  12595. // Local animations
  12596. if (target.animations) {
  12597. animatable.appendAnimations(target, target.animations);
  12598. }
  12599. // Children animations
  12600. if (target.getAnimatables) {
  12601. var animatables = target.getAnimatables();
  12602. for (var index = 0; index < animatables.length; index++) {
  12603. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12604. }
  12605. }
  12606. return animatable;
  12607. };
  12608. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12609. if (speedRatio === undefined) {
  12610. speedRatio = 1.0;
  12611. }
  12612. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12613. return animatable;
  12614. };
  12615. Scene.prototype.getAnimatableByTarget = function (target) {
  12616. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12617. if (this._activeAnimatables[index].target === target) {
  12618. return this._activeAnimatables[index];
  12619. }
  12620. }
  12621. return null;
  12622. };
  12623. /**
  12624. * Will stop the animation of the given target
  12625. * @param target - the target
  12626. * @see beginAnimation
  12627. */
  12628. Scene.prototype.stopAnimation = function (target) {
  12629. var animatable = this.getAnimatableByTarget(target);
  12630. if (animatable) {
  12631. animatable.stop();
  12632. }
  12633. };
  12634. Scene.prototype._animate = function () {
  12635. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12636. return;
  12637. }
  12638. if (!this._animationStartDate) {
  12639. if (this._pendingData.length > 0) {
  12640. return;
  12641. }
  12642. this._animationStartDate = BABYLON.Tools.Now;
  12643. }
  12644. // Getting time
  12645. var now = BABYLON.Tools.Now;
  12646. var delay = now - this._animationStartDate;
  12647. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12648. this._activeAnimatables[index]._animate(delay);
  12649. }
  12650. };
  12651. // Matrix
  12652. Scene.prototype.getViewMatrix = function () {
  12653. return this._viewMatrix;
  12654. };
  12655. Scene.prototype.getProjectionMatrix = function () {
  12656. return this._projectionMatrix;
  12657. };
  12658. Scene.prototype.getTransformMatrix = function () {
  12659. return this._transformMatrix;
  12660. };
  12661. Scene.prototype.setTransformMatrix = function (view, projection) {
  12662. this._viewMatrix = view;
  12663. this._projectionMatrix = projection;
  12664. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12665. };
  12666. // Methods
  12667. Scene.prototype.addMesh = function (newMesh) {
  12668. newMesh.uniqueId = this._uniqueIdCounter++;
  12669. var position = this.meshes.push(newMesh);
  12670. //notify the collision coordinator
  12671. this.collisionCoordinator.onMeshAdded(newMesh);
  12672. if (this.onNewMeshAdded) {
  12673. this.onNewMeshAdded(newMesh, position, this);
  12674. }
  12675. };
  12676. Scene.prototype.removeMesh = function (toRemove) {
  12677. var index = this.meshes.indexOf(toRemove);
  12678. if (index !== -1) {
  12679. // Remove from the scene if mesh found
  12680. this.meshes.splice(index, 1);
  12681. }
  12682. //notify the collision coordinator
  12683. this.collisionCoordinator.onMeshRemoved(toRemove);
  12684. if (this.onMeshRemoved) {
  12685. this.onMeshRemoved(toRemove);
  12686. }
  12687. return index;
  12688. };
  12689. Scene.prototype.removeSkeleton = function (toRemove) {
  12690. var index = this.skeletons.indexOf(toRemove);
  12691. if (index !== -1) {
  12692. // Remove from the scene if mesh found
  12693. this.skeletons.splice(index, 1);
  12694. }
  12695. return index;
  12696. };
  12697. Scene.prototype.removeLight = function (toRemove) {
  12698. var index = this.lights.indexOf(toRemove);
  12699. if (index !== -1) {
  12700. // Remove from the scene if mesh found
  12701. this.lights.splice(index, 1);
  12702. }
  12703. if (this.onLightRemoved) {
  12704. this.onLightRemoved(toRemove);
  12705. }
  12706. return index;
  12707. };
  12708. Scene.prototype.removeCamera = function (toRemove) {
  12709. var index = this.cameras.indexOf(toRemove);
  12710. if (index !== -1) {
  12711. // Remove from the scene if mesh found
  12712. this.cameras.splice(index, 1);
  12713. }
  12714. // Remove from activeCameras
  12715. var index2 = this.activeCameras.indexOf(toRemove);
  12716. if (index2 !== -1) {
  12717. // Remove from the scene if mesh found
  12718. this.activeCameras.splice(index2, 1);
  12719. }
  12720. // Reset the activeCamera
  12721. if (this.activeCamera === toRemove) {
  12722. if (this.cameras.length > 0) {
  12723. this.activeCamera = this.cameras[0];
  12724. }
  12725. else {
  12726. this.activeCamera = null;
  12727. }
  12728. }
  12729. if (this.onCameraRemoved) {
  12730. this.onCameraRemoved(toRemove);
  12731. }
  12732. return index;
  12733. };
  12734. Scene.prototype.addLight = function (newLight) {
  12735. newLight.uniqueId = this._uniqueIdCounter++;
  12736. var position = this.lights.push(newLight);
  12737. if (this.onNewLightAdded) {
  12738. this.onNewLightAdded(newLight, position, this);
  12739. }
  12740. };
  12741. Scene.prototype.addCamera = function (newCamera) {
  12742. newCamera.uniqueId = this._uniqueIdCounter++;
  12743. var position = this.cameras.push(newCamera);
  12744. if (this.onNewCameraAdded) {
  12745. this.onNewCameraAdded(newCamera, position, this);
  12746. }
  12747. };
  12748. /**
  12749. * sets the active camera of the scene using its ID
  12750. * @param {string} id - the camera's ID
  12751. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12752. * @see activeCamera
  12753. */
  12754. Scene.prototype.setActiveCameraByID = function (id) {
  12755. var camera = this.getCameraByID(id);
  12756. if (camera) {
  12757. this.activeCamera = camera;
  12758. return camera;
  12759. }
  12760. return null;
  12761. };
  12762. /**
  12763. * sets the active camera of the scene using its name
  12764. * @param {string} name - the camera's name
  12765. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12766. * @see activeCamera
  12767. */
  12768. Scene.prototype.setActiveCameraByName = function (name) {
  12769. var camera = this.getCameraByName(name);
  12770. if (camera) {
  12771. this.activeCamera = camera;
  12772. return camera;
  12773. }
  12774. return null;
  12775. };
  12776. /**
  12777. * get a material using its id
  12778. * @param {string} the material's ID
  12779. * @return {BABYLON.Material|null} the material or null if none found.
  12780. */
  12781. Scene.prototype.getMaterialByID = function (id) {
  12782. for (var index = 0; index < this.materials.length; index++) {
  12783. if (this.materials[index].id === id) {
  12784. return this.materials[index];
  12785. }
  12786. }
  12787. return null;
  12788. };
  12789. /**
  12790. * get a material using its name
  12791. * @param {string} the material's name
  12792. * @return {BABYLON.Material|null} the material or null if none found.
  12793. */
  12794. Scene.prototype.getMaterialByName = function (name) {
  12795. for (var index = 0; index < this.materials.length; index++) {
  12796. if (this.materials[index].name === name) {
  12797. return this.materials[index];
  12798. }
  12799. }
  12800. return null;
  12801. };
  12802. Scene.prototype.getLensFlareSystemByName = function (name) {
  12803. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12804. if (this.lensFlareSystems[index].name === name) {
  12805. return this.lensFlareSystems[index];
  12806. }
  12807. }
  12808. return null;
  12809. };
  12810. Scene.prototype.getCameraByID = function (id) {
  12811. for (var index = 0; index < this.cameras.length; index++) {
  12812. if (this.cameras[index].id === id) {
  12813. return this.cameras[index];
  12814. }
  12815. }
  12816. return null;
  12817. };
  12818. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12819. for (var index = 0; index < this.cameras.length; index++) {
  12820. if (this.cameras[index].uniqueId === uniqueId) {
  12821. return this.cameras[index];
  12822. }
  12823. }
  12824. return null;
  12825. };
  12826. /**
  12827. * get a camera using its name
  12828. * @param {string} the camera's name
  12829. * @return {BABYLON.Camera|null} the camera or null if none found.
  12830. */
  12831. Scene.prototype.getCameraByName = function (name) {
  12832. for (var index = 0; index < this.cameras.length; index++) {
  12833. if (this.cameras[index].name === name) {
  12834. return this.cameras[index];
  12835. }
  12836. }
  12837. return null;
  12838. };
  12839. /**
  12840. * get a bone using its id
  12841. * @param {string} the bone's id
  12842. * @return {BABYLON.Bone|null} the bone or null if not found
  12843. */
  12844. Scene.prototype.getBoneByID = function (id) {
  12845. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12846. var skeleton = this.skeletons[skeletonIndex];
  12847. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12848. if (skeleton.bones[boneIndex].id === id) {
  12849. return skeleton.bones[boneIndex];
  12850. }
  12851. }
  12852. }
  12853. return null;
  12854. };
  12855. /**
  12856. * get a bone using its id
  12857. * @param {string} the bone's name
  12858. * @return {BABYLON.Bone|null} the bone or null if not found
  12859. */
  12860. Scene.prototype.getBoneByName = function (name) {
  12861. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12862. var skeleton = this.skeletons[skeletonIndex];
  12863. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12864. if (skeleton.bones[boneIndex].name === name) {
  12865. return skeleton.bones[boneIndex];
  12866. }
  12867. }
  12868. }
  12869. return null;
  12870. };
  12871. /**
  12872. * get a light node using its name
  12873. * @param {string} the light's name
  12874. * @return {BABYLON.Light|null} the light or null if none found.
  12875. */
  12876. Scene.prototype.getLightByName = function (name) {
  12877. for (var index = 0; index < this.lights.length; index++) {
  12878. if (this.lights[index].name === name) {
  12879. return this.lights[index];
  12880. }
  12881. }
  12882. return null;
  12883. };
  12884. /**
  12885. * get a light node using its ID
  12886. * @param {string} the light's id
  12887. * @return {BABYLON.Light|null} the light or null if none found.
  12888. */
  12889. Scene.prototype.getLightByID = function (id) {
  12890. for (var index = 0; index < this.lights.length; index++) {
  12891. if (this.lights[index].id === id) {
  12892. return this.lights[index];
  12893. }
  12894. }
  12895. return null;
  12896. };
  12897. /**
  12898. * get a light node using its scene-generated unique ID
  12899. * @param {number} the light's unique id
  12900. * @return {BABYLON.Light|null} the light or null if none found.
  12901. */
  12902. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12903. for (var index = 0; index < this.lights.length; index++) {
  12904. if (this.lights[index].uniqueId === uniqueId) {
  12905. return this.lights[index];
  12906. }
  12907. }
  12908. return null;
  12909. };
  12910. /**
  12911. * get a particle system by id
  12912. * @param id {number} the particle system id
  12913. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12914. */
  12915. Scene.prototype.getParticleSystemByID = function (id) {
  12916. for (var index = 0; index < this.particleSystems.length; index++) {
  12917. if (this.particleSystems[index].id === id) {
  12918. return this.particleSystems[index];
  12919. }
  12920. }
  12921. return null;
  12922. };
  12923. /**
  12924. * get a geometry using its ID
  12925. * @param {string} the geometry's id
  12926. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12927. */
  12928. Scene.prototype.getGeometryByID = function (id) {
  12929. for (var index = 0; index < this._geometries.length; index++) {
  12930. if (this._geometries[index].id === id) {
  12931. return this._geometries[index];
  12932. }
  12933. }
  12934. return null;
  12935. };
  12936. /**
  12937. * add a new geometry to this scene.
  12938. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12939. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12940. * @return {boolean} was the geometry added or not
  12941. */
  12942. Scene.prototype.pushGeometry = function (geometry, force) {
  12943. if (!force && this.getGeometryByID(geometry.id)) {
  12944. return false;
  12945. }
  12946. this._geometries.push(geometry);
  12947. //notify the collision coordinator
  12948. this.collisionCoordinator.onGeometryAdded(geometry);
  12949. if (this.onGeometryAdded) {
  12950. this.onGeometryAdded(geometry);
  12951. }
  12952. return true;
  12953. };
  12954. /**
  12955. * Removes an existing geometry
  12956. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12957. * @return {boolean} was the geometry removed or not
  12958. */
  12959. Scene.prototype.removeGeometry = function (geometry) {
  12960. var index = this._geometries.indexOf(geometry);
  12961. if (index > -1) {
  12962. this._geometries.splice(index, 1);
  12963. //notify the collision coordinator
  12964. this.collisionCoordinator.onGeometryDeleted(geometry);
  12965. if (this.onGeometryRemoved) {
  12966. this.onGeometryRemoved(geometry);
  12967. }
  12968. return true;
  12969. }
  12970. return false;
  12971. };
  12972. Scene.prototype.getGeometries = function () {
  12973. return this._geometries;
  12974. };
  12975. /**
  12976. * Get the first added mesh found of a given ID
  12977. * @param {string} id - the id to search for
  12978. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12979. */
  12980. Scene.prototype.getMeshByID = function (id) {
  12981. for (var index = 0; index < this.meshes.length; index++) {
  12982. if (this.meshes[index].id === id) {
  12983. return this.meshes[index];
  12984. }
  12985. }
  12986. return null;
  12987. };
  12988. /**
  12989. * Get a mesh with its auto-generated unique id
  12990. * @param {number} uniqueId - the unique id to search for
  12991. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12992. */
  12993. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12994. for (var index = 0; index < this.meshes.length; index++) {
  12995. if (this.meshes[index].uniqueId === uniqueId) {
  12996. return this.meshes[index];
  12997. }
  12998. }
  12999. return null;
  13000. };
  13001. /**
  13002. * Get a the last added mesh found of a given ID
  13003. * @param {string} id - the id to search for
  13004. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13005. */
  13006. Scene.prototype.getLastMeshByID = function (id) {
  13007. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13008. if (this.meshes[index].id === id) {
  13009. return this.meshes[index];
  13010. }
  13011. }
  13012. return null;
  13013. };
  13014. /**
  13015. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13016. * @param {string} id - the id to search for
  13017. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13018. */
  13019. Scene.prototype.getLastEntryByID = function (id) {
  13020. var index;
  13021. for (index = this.meshes.length - 1; index >= 0; index--) {
  13022. if (this.meshes[index].id === id) {
  13023. return this.meshes[index];
  13024. }
  13025. }
  13026. for (index = this.cameras.length - 1; index >= 0; index--) {
  13027. if (this.cameras[index].id === id) {
  13028. return this.cameras[index];
  13029. }
  13030. }
  13031. for (index = this.lights.length - 1; index >= 0; index--) {
  13032. if (this.lights[index].id === id) {
  13033. return this.lights[index];
  13034. }
  13035. }
  13036. return null;
  13037. };
  13038. Scene.prototype.getNodeByID = function (id) {
  13039. var mesh = this.getMeshByID(id);
  13040. if (mesh) {
  13041. return mesh;
  13042. }
  13043. var light = this.getLightByID(id);
  13044. if (light) {
  13045. return light;
  13046. }
  13047. var camera = this.getCameraByID(id);
  13048. if (camera) {
  13049. return camera;
  13050. }
  13051. var bone = this.getBoneByID(id);
  13052. return bone;
  13053. };
  13054. Scene.prototype.getNodeByName = function (name) {
  13055. var mesh = this.getMeshByName(name);
  13056. if (mesh) {
  13057. return mesh;
  13058. }
  13059. var light = this.getLightByName(name);
  13060. if (light) {
  13061. return light;
  13062. }
  13063. var camera = this.getCameraByName(name);
  13064. if (camera) {
  13065. return camera;
  13066. }
  13067. var bone = this.getBoneByName(name);
  13068. return bone;
  13069. };
  13070. Scene.prototype.getMeshByName = function (name) {
  13071. for (var index = 0; index < this.meshes.length; index++) {
  13072. if (this.meshes[index].name === name) {
  13073. return this.meshes[index];
  13074. }
  13075. }
  13076. return null;
  13077. };
  13078. Scene.prototype.getSoundByName = function (name) {
  13079. var index;
  13080. if (BABYLON.AudioEngine) {
  13081. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13082. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13083. return this.mainSoundTrack.soundCollection[index];
  13084. }
  13085. }
  13086. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13087. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13088. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13089. return this.soundTracks[sdIndex].soundCollection[index];
  13090. }
  13091. }
  13092. }
  13093. }
  13094. return null;
  13095. };
  13096. Scene.prototype.getLastSkeletonByID = function (id) {
  13097. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13098. if (this.skeletons[index].id === id) {
  13099. return this.skeletons[index];
  13100. }
  13101. }
  13102. return null;
  13103. };
  13104. Scene.prototype.getSkeletonById = function (id) {
  13105. for (var index = 0; index < this.skeletons.length; index++) {
  13106. if (this.skeletons[index].id === id) {
  13107. return this.skeletons[index];
  13108. }
  13109. }
  13110. return null;
  13111. };
  13112. Scene.prototype.getSkeletonByName = function (name) {
  13113. for (var index = 0; index < this.skeletons.length; index++) {
  13114. if (this.skeletons[index].name === name) {
  13115. return this.skeletons[index];
  13116. }
  13117. }
  13118. return null;
  13119. };
  13120. Scene.prototype.isActiveMesh = function (mesh) {
  13121. return (this._activeMeshes.indexOf(mesh) !== -1);
  13122. };
  13123. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13124. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13125. var material = subMesh.getMaterial();
  13126. if (mesh.showSubMeshesBoundingBox) {
  13127. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13128. }
  13129. if (material) {
  13130. // Render targets
  13131. if (material.getRenderTargetTextures) {
  13132. if (this._processedMaterials.indexOf(material) === -1) {
  13133. this._processedMaterials.push(material);
  13134. this._renderTargets.concat(material.getRenderTargetTextures());
  13135. }
  13136. }
  13137. // Dispatch
  13138. this._activeIndices += subMesh.indexCount;
  13139. this._renderingManager.dispatch(subMesh);
  13140. }
  13141. }
  13142. };
  13143. Scene.prototype._evaluateActiveMeshes = function () {
  13144. this.activeCamera._activeMeshes.reset();
  13145. this._activeMeshes.reset();
  13146. this._renderingManager.reset();
  13147. this._processedMaterials.reset();
  13148. this._activeParticleSystems.reset();
  13149. this._activeSkeletons.reset();
  13150. this._softwareSkinnedMeshes.reset();
  13151. this._boundingBoxRenderer.reset();
  13152. this._edgesRenderers.reset();
  13153. if (!this._frustumPlanes) {
  13154. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13155. }
  13156. else {
  13157. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13158. }
  13159. // Meshes
  13160. var meshes;
  13161. var len;
  13162. if (this._selectionOctree) {
  13163. var selection = this._selectionOctree.select(this._frustumPlanes);
  13164. meshes = selection.data;
  13165. len = selection.length;
  13166. }
  13167. else {
  13168. len = this.meshes.length;
  13169. meshes = this.meshes;
  13170. }
  13171. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13172. var mesh = meshes[meshIndex];
  13173. if (mesh.isBlocked) {
  13174. continue;
  13175. }
  13176. this._totalVertices += mesh.getTotalVertices();
  13177. if (!mesh.isReady() || !mesh.isEnabled()) {
  13178. continue;
  13179. }
  13180. mesh.computeWorldMatrix();
  13181. // Intersections
  13182. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13183. this._meshesForIntersections.pushNoDuplicate(mesh);
  13184. }
  13185. // Switch to current LOD
  13186. var meshLOD = mesh.getLOD(this.activeCamera);
  13187. if (!meshLOD) {
  13188. continue;
  13189. }
  13190. mesh._preActivate();
  13191. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13192. this._activeMeshes.push(mesh);
  13193. this.activeCamera._activeMeshes.push(mesh);
  13194. mesh._activate(this._renderId);
  13195. this._activeMesh(meshLOD);
  13196. }
  13197. }
  13198. // Particle systems
  13199. var beforeParticlesDate = BABYLON.Tools.Now;
  13200. if (this.particlesEnabled) {
  13201. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13202. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13203. var particleSystem = this.particleSystems[particleIndex];
  13204. if (!particleSystem.isStarted()) {
  13205. continue;
  13206. }
  13207. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13208. this._activeParticleSystems.push(particleSystem);
  13209. particleSystem.animate();
  13210. }
  13211. }
  13212. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13213. }
  13214. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13215. };
  13216. Scene.prototype._activeMesh = function (mesh) {
  13217. if (mesh.skeleton && this.skeletonsEnabled) {
  13218. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13219. if (!mesh.computeBonesUsingShaders) {
  13220. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13221. }
  13222. }
  13223. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13224. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13225. }
  13226. if (mesh._edgesRenderer) {
  13227. this._edgesRenderers.push(mesh._edgesRenderer);
  13228. }
  13229. if (mesh && mesh.subMeshes) {
  13230. // Submeshes Octrees
  13231. var len;
  13232. var subMeshes;
  13233. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13234. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13235. len = intersections.length;
  13236. subMeshes = intersections.data;
  13237. }
  13238. else {
  13239. subMeshes = mesh.subMeshes;
  13240. len = subMeshes.length;
  13241. }
  13242. for (var subIndex = 0; subIndex < len; subIndex++) {
  13243. var subMesh = subMeshes[subIndex];
  13244. this._evaluateSubMesh(subMesh, mesh);
  13245. }
  13246. }
  13247. };
  13248. Scene.prototype.updateTransformMatrix = function (force) {
  13249. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13250. };
  13251. Scene.prototype._renderForCamera = function (camera) {
  13252. var engine = this._engine;
  13253. this.activeCamera = camera;
  13254. if (!this.activeCamera)
  13255. throw new Error("Active camera not set");
  13256. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13257. // Viewport
  13258. engine.setViewport(this.activeCamera.viewport);
  13259. // Camera
  13260. this.resetCachedMaterial();
  13261. this._renderId++;
  13262. this.updateTransformMatrix();
  13263. if (this.beforeCameraRender) {
  13264. this.beforeCameraRender(this.activeCamera);
  13265. }
  13266. // Meshes
  13267. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13268. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13269. this._evaluateActiveMeshes();
  13270. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13271. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13272. // Skeletons
  13273. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13274. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13275. skeleton.prepare();
  13276. }
  13277. // Software skinning
  13278. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13279. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13280. mesh.applySkeleton(mesh.skeleton);
  13281. }
  13282. // Render targets
  13283. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13284. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13285. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13286. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13287. var renderTarget = this._renderTargets.data[renderIndex];
  13288. if (renderTarget._shouldRender()) {
  13289. this._renderId++;
  13290. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13291. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13292. }
  13293. }
  13294. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13295. this._renderId++;
  13296. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13297. }
  13298. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13299. // Prepare Frame
  13300. this.postProcessManager._prepareFrame();
  13301. var beforeRenderDate = BABYLON.Tools.Now;
  13302. // Backgrounds
  13303. var layerIndex;
  13304. var layer;
  13305. if (this.layers.length) {
  13306. engine.setDepthBuffer(false);
  13307. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13308. layer = this.layers[layerIndex];
  13309. if (layer.isBackground) {
  13310. layer.render();
  13311. }
  13312. }
  13313. engine.setDepthBuffer(true);
  13314. }
  13315. // Render
  13316. BABYLON.Tools.StartPerformanceCounter("Main render");
  13317. this._renderingManager.render(null, null, true, true);
  13318. BABYLON.Tools.EndPerformanceCounter("Main render");
  13319. // Bounding boxes
  13320. this._boundingBoxRenderer.render();
  13321. // Edges
  13322. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13323. this._edgesRenderers.data[edgesRendererIndex].render();
  13324. }
  13325. // Lens flares
  13326. if (this.lensFlaresEnabled) {
  13327. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13328. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13329. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13330. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13331. lensFlareSystem.render();
  13332. }
  13333. }
  13334. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13335. }
  13336. // Foregrounds
  13337. if (this.layers.length) {
  13338. engine.setDepthBuffer(false);
  13339. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13340. layer = this.layers[layerIndex];
  13341. if (!layer.isBackground) {
  13342. layer.render();
  13343. }
  13344. }
  13345. engine.setDepthBuffer(true);
  13346. }
  13347. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13348. // Finalize frame
  13349. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13350. // Update camera
  13351. this.activeCamera._updateFromScene();
  13352. // Reset some special arrays
  13353. this._renderTargets.reset();
  13354. if (this.afterCameraRender) {
  13355. this.afterCameraRender(this.activeCamera);
  13356. }
  13357. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13358. };
  13359. Scene.prototype._processSubCameras = function (camera) {
  13360. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13361. this._renderForCamera(camera);
  13362. return;
  13363. }
  13364. // rig cameras
  13365. for (var index = 0; index < camera._rigCameras.length; index++) {
  13366. this._renderForCamera(camera._rigCameras[index]);
  13367. }
  13368. this.activeCamera = camera;
  13369. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13370. // Update camera
  13371. this.activeCamera._updateFromScene();
  13372. };
  13373. Scene.prototype._checkIntersections = function () {
  13374. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13375. var sourceMesh = this._meshesForIntersections.data[index];
  13376. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13377. var action = sourceMesh.actionManager.actions[actionIndex];
  13378. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13379. var parameters = action.getTriggerParameter();
  13380. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13381. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13382. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13383. if (areIntersecting && currentIntersectionInProgress === -1) {
  13384. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13385. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13386. sourceMesh._intersectionsInProgress.push(otherMesh);
  13387. }
  13388. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13389. sourceMesh._intersectionsInProgress.push(otherMesh);
  13390. }
  13391. }
  13392. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13393. //They intersected, and now they don't.
  13394. //is this trigger an exit trigger? execute an event.
  13395. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13396. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13397. }
  13398. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13399. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13400. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13401. }
  13402. }
  13403. }
  13404. }
  13405. }
  13406. };
  13407. Scene.prototype.render = function () {
  13408. var startDate = BABYLON.Tools.Now;
  13409. this._particlesDuration = 0;
  13410. this._spritesDuration = 0;
  13411. this._activeParticles = 0;
  13412. this._renderDuration = 0;
  13413. this._renderTargetsDuration = 0;
  13414. this._evaluateActiveMeshesDuration = 0;
  13415. this._totalVertices = 0;
  13416. this._activeIndices = 0;
  13417. this._activeBones = 0;
  13418. this.getEngine().resetDrawCalls();
  13419. this._meshesForIntersections.reset();
  13420. this.resetCachedMaterial();
  13421. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13422. // Actions
  13423. if (this.actionManager) {
  13424. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13425. }
  13426. //Simplification Queue
  13427. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13428. this.simplificationQueue.executeNext();
  13429. }
  13430. // Animations
  13431. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13432. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13433. this._animate();
  13434. // Physics
  13435. if (this._physicsEngine) {
  13436. BABYLON.Tools.StartPerformanceCounter("Physics");
  13437. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13438. BABYLON.Tools.EndPerformanceCounter("Physics");
  13439. }
  13440. // Before render
  13441. if (this.beforeRender) {
  13442. this.beforeRender();
  13443. }
  13444. var callbackIndex;
  13445. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13446. this._onBeforeRenderCallbacks[callbackIndex]();
  13447. }
  13448. // Customs render targets
  13449. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13450. var engine = this.getEngine();
  13451. var currentActiveCamera = this.activeCamera;
  13452. if (this.renderTargetsEnabled) {
  13453. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13454. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13455. var renderTarget = this.customRenderTargets[customIndex];
  13456. if (renderTarget._shouldRender()) {
  13457. this._renderId++;
  13458. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13459. if (!this.activeCamera)
  13460. throw new Error("Active camera not set");
  13461. // Viewport
  13462. engine.setViewport(this.activeCamera.viewport);
  13463. // Camera
  13464. this.updateTransformMatrix();
  13465. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13466. }
  13467. }
  13468. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13469. this._renderId++;
  13470. }
  13471. if (this.customRenderTargets.length > 0) {
  13472. engine.restoreDefaultFramebuffer();
  13473. }
  13474. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13475. this.activeCamera = currentActiveCamera;
  13476. // Procedural textures
  13477. if (this.proceduralTexturesEnabled) {
  13478. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13479. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13480. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13481. if (proceduralTexture._shouldRender()) {
  13482. proceduralTexture.render();
  13483. }
  13484. }
  13485. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13486. }
  13487. // Clear
  13488. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13489. // Shadows
  13490. if (this.shadowsEnabled) {
  13491. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13492. var light = this.lights[lightIndex];
  13493. var shadowGenerator = light.getShadowGenerator();
  13494. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13495. this._renderTargets.push(shadowGenerator.getShadowMap());
  13496. }
  13497. }
  13498. }
  13499. // Depth renderer
  13500. if (this._depthRenderer) {
  13501. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13502. }
  13503. // RenderPipeline
  13504. this.postProcessRenderPipelineManager.update();
  13505. // Multi-cameras?
  13506. if (this.activeCameras.length > 0) {
  13507. var currentRenderId = this._renderId;
  13508. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13509. this._renderId = currentRenderId;
  13510. if (cameraIndex > 0) {
  13511. this._engine.clear(0, false, true);
  13512. }
  13513. this._processSubCameras(this.activeCameras[cameraIndex]);
  13514. }
  13515. }
  13516. else {
  13517. if (!this.activeCamera) {
  13518. throw new Error("No camera defined");
  13519. }
  13520. this._processSubCameras(this.activeCamera);
  13521. }
  13522. // Intersection checks
  13523. this._checkIntersections();
  13524. // Update the audio listener attached to the camera
  13525. if (BABYLON.AudioEngine) {
  13526. this._updateAudioParameters();
  13527. }
  13528. // After render
  13529. if (this.afterRender) {
  13530. this.afterRender();
  13531. }
  13532. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13533. this._onAfterRenderCallbacks[callbackIndex]();
  13534. }
  13535. // Cleaning
  13536. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13537. this._toBeDisposed.data[index].dispose();
  13538. this._toBeDisposed[index] = null;
  13539. }
  13540. this._toBeDisposed.reset();
  13541. if (this.dumpNextRenderTargets) {
  13542. this.dumpNextRenderTargets = false;
  13543. }
  13544. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13545. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13546. };
  13547. Scene.prototype._updateAudioParameters = function () {
  13548. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13549. return;
  13550. }
  13551. var listeningCamera;
  13552. var audioEngine = BABYLON.Engine.audioEngine;
  13553. if (this.activeCameras.length > 0) {
  13554. listeningCamera = this.activeCameras[0];
  13555. }
  13556. else {
  13557. listeningCamera = this.activeCamera;
  13558. }
  13559. if (listeningCamera && audioEngine.canUseWebAudio) {
  13560. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13561. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13562. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13563. cameraDirection.normalize();
  13564. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13565. var i;
  13566. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13567. var sound = this.mainSoundTrack.soundCollection[i];
  13568. if (sound.useCustomAttenuation) {
  13569. sound.updateDistanceFromListener();
  13570. }
  13571. }
  13572. for (i = 0; i < this.soundTracks.length; i++) {
  13573. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13574. sound = this.soundTracks[i].soundCollection[j];
  13575. if (sound.useCustomAttenuation) {
  13576. sound.updateDistanceFromListener();
  13577. }
  13578. }
  13579. }
  13580. }
  13581. };
  13582. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13583. // Audio
  13584. get: function () {
  13585. return this._audioEnabled;
  13586. },
  13587. set: function (value) {
  13588. this._audioEnabled = value;
  13589. if (BABYLON.AudioEngine) {
  13590. if (this._audioEnabled) {
  13591. this._enableAudio();
  13592. }
  13593. else {
  13594. this._disableAudio();
  13595. }
  13596. }
  13597. },
  13598. enumerable: true,
  13599. configurable: true
  13600. });
  13601. Scene.prototype._disableAudio = function () {
  13602. var i;
  13603. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13604. this.mainSoundTrack.soundCollection[i].pause();
  13605. }
  13606. for (i = 0; i < this.soundTracks.length; i++) {
  13607. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13608. this.soundTracks[i].soundCollection[j].pause();
  13609. }
  13610. }
  13611. };
  13612. Scene.prototype._enableAudio = function () {
  13613. var i;
  13614. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13615. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13616. this.mainSoundTrack.soundCollection[i].play();
  13617. }
  13618. }
  13619. for (i = 0; i < this.soundTracks.length; i++) {
  13620. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13621. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13622. this.soundTracks[i].soundCollection[j].play();
  13623. }
  13624. }
  13625. }
  13626. };
  13627. Object.defineProperty(Scene.prototype, "headphone", {
  13628. get: function () {
  13629. return this._headphone;
  13630. },
  13631. set: function (value) {
  13632. this._headphone = value;
  13633. if (BABYLON.AudioEngine) {
  13634. if (this._headphone) {
  13635. this._switchAudioModeForHeadphones();
  13636. }
  13637. else {
  13638. this._switchAudioModeForNormalSpeakers();
  13639. }
  13640. }
  13641. },
  13642. enumerable: true,
  13643. configurable: true
  13644. });
  13645. Scene.prototype._switchAudioModeForHeadphones = function () {
  13646. this.mainSoundTrack.switchPanningModelToHRTF();
  13647. for (var i = 0; i < this.soundTracks.length; i++) {
  13648. this.soundTracks[i].switchPanningModelToHRTF();
  13649. }
  13650. };
  13651. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13652. this.mainSoundTrack.switchPanningModelToEqualPower();
  13653. for (var i = 0; i < this.soundTracks.length; i++) {
  13654. this.soundTracks[i].switchPanningModelToEqualPower();
  13655. }
  13656. };
  13657. Scene.prototype.enableDepthRenderer = function () {
  13658. if (this._depthRenderer) {
  13659. return this._depthRenderer;
  13660. }
  13661. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13662. return this._depthRenderer;
  13663. };
  13664. Scene.prototype.disableDepthRenderer = function () {
  13665. if (!this._depthRenderer) {
  13666. return;
  13667. }
  13668. this._depthRenderer.dispose();
  13669. this._depthRenderer = null;
  13670. };
  13671. Scene.prototype.freezeMaterials = function () {
  13672. for (var i = 0; i < this.materials.length; i++) {
  13673. this.materials[i].freeze();
  13674. }
  13675. };
  13676. Scene.prototype.unfreezeMaterials = function () {
  13677. for (var i = 0; i < this.materials.length; i++) {
  13678. this.materials[i].unfreeze();
  13679. }
  13680. };
  13681. Scene.prototype.dispose = function () {
  13682. this.beforeRender = null;
  13683. this.afterRender = null;
  13684. this.skeletons = [];
  13685. this._boundingBoxRenderer.dispose();
  13686. if (this._depthRenderer) {
  13687. this._depthRenderer.dispose();
  13688. }
  13689. // Debug layer
  13690. this.debugLayer.hide();
  13691. // Events
  13692. if (this.onDispose) {
  13693. this.onDispose();
  13694. }
  13695. this._onBeforeRenderCallbacks = [];
  13696. this._onAfterRenderCallbacks = [];
  13697. this.detachControl();
  13698. // Release sounds & sounds tracks
  13699. if (BABYLON.AudioEngine) {
  13700. this.disposeSounds();
  13701. }
  13702. // Detach cameras
  13703. var canvas = this._engine.getRenderingCanvas();
  13704. var index;
  13705. for (index = 0; index < this.cameras.length; index++) {
  13706. this.cameras[index].detachControl(canvas);
  13707. }
  13708. // Release lights
  13709. while (this.lights.length) {
  13710. this.lights[0].dispose();
  13711. }
  13712. // Release meshes
  13713. while (this.meshes.length) {
  13714. this.meshes[0].dispose(true);
  13715. }
  13716. // Release cameras
  13717. while (this.cameras.length) {
  13718. this.cameras[0].dispose();
  13719. }
  13720. // Release materials
  13721. while (this.materials.length) {
  13722. this.materials[0].dispose();
  13723. }
  13724. // Release particles
  13725. while (this.particleSystems.length) {
  13726. this.particleSystems[0].dispose();
  13727. }
  13728. // Release sprites
  13729. while (this.spriteManagers.length) {
  13730. this.spriteManagers[0].dispose();
  13731. }
  13732. // Release layers
  13733. while (this.layers.length) {
  13734. this.layers[0].dispose();
  13735. }
  13736. // Release textures
  13737. while (this.textures.length) {
  13738. this.textures[0].dispose();
  13739. }
  13740. // Post-processes
  13741. this.postProcessManager.dispose();
  13742. // Physics
  13743. if (this._physicsEngine) {
  13744. this.disablePhysicsEngine();
  13745. }
  13746. // Remove from engine
  13747. index = this._engine.scenes.indexOf(this);
  13748. if (index > -1) {
  13749. this._engine.scenes.splice(index, 1);
  13750. }
  13751. this._engine.wipeCaches();
  13752. };
  13753. // Release sounds & sounds tracks
  13754. Scene.prototype.disposeSounds = function () {
  13755. this.mainSoundTrack.dispose();
  13756. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13757. this.soundTracks[scIndex].dispose();
  13758. }
  13759. };
  13760. // Octrees
  13761. Scene.prototype.getWorldExtends = function () {
  13762. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13763. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13764. for (var index = 0; index < this.meshes.length; index++) {
  13765. var mesh = this.meshes[index];
  13766. mesh.computeWorldMatrix(true);
  13767. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13768. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13769. BABYLON.Tools.CheckExtends(minBox, min, max);
  13770. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13771. }
  13772. return {
  13773. min: min,
  13774. max: max
  13775. };
  13776. };
  13777. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13778. if (maxCapacity === void 0) { maxCapacity = 64; }
  13779. if (maxDepth === void 0) { maxDepth = 2; }
  13780. if (!this._selectionOctree) {
  13781. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13782. }
  13783. var worldExtends = this.getWorldExtends();
  13784. // Update octree
  13785. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13786. return this._selectionOctree;
  13787. };
  13788. // Picking
  13789. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13790. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13791. var engine = this._engine;
  13792. if (!camera) {
  13793. if (!this.activeCamera)
  13794. throw new Error("Active camera not set");
  13795. camera = this.activeCamera;
  13796. }
  13797. var cameraViewport = camera.viewport;
  13798. var viewport = cameraViewport.toGlobal(engine);
  13799. // Moving coordinates to local viewport world
  13800. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13801. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13802. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13803. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13804. };
  13805. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13806. var engine = this._engine;
  13807. if (!camera) {
  13808. if (!this.activeCamera)
  13809. throw new Error("Active camera not set");
  13810. camera = this.activeCamera;
  13811. }
  13812. var cameraViewport = camera.viewport;
  13813. var viewport = cameraViewport.toGlobal(engine);
  13814. var identity = BABYLON.Matrix.Identity();
  13815. // Moving coordinates to local viewport world
  13816. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13817. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13818. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13819. };
  13820. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13821. var pickingInfo = null;
  13822. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13823. var mesh = this.meshes[meshIndex];
  13824. if (predicate) {
  13825. if (!predicate(mesh)) {
  13826. continue;
  13827. }
  13828. }
  13829. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13830. continue;
  13831. }
  13832. var world = mesh.getWorldMatrix();
  13833. var ray = rayFunction(world);
  13834. var result = mesh.intersects(ray, fastCheck);
  13835. if (!result || !result.hit)
  13836. continue;
  13837. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13838. continue;
  13839. pickingInfo = result;
  13840. if (fastCheck) {
  13841. break;
  13842. }
  13843. }
  13844. return pickingInfo || new BABYLON.PickingInfo();
  13845. };
  13846. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13847. var pickingInfo = null;
  13848. camera = camera || this.activeCamera;
  13849. if (this.spriteManagers.length > 0) {
  13850. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13851. var spriteManager = this.spriteManagers[spriteIndex];
  13852. if (!spriteManager.isPickable) {
  13853. continue;
  13854. }
  13855. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13856. if (!result || !result.hit)
  13857. continue;
  13858. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13859. continue;
  13860. pickingInfo = result;
  13861. if (fastCheck) {
  13862. break;
  13863. }
  13864. }
  13865. }
  13866. return pickingInfo || new BABYLON.PickingInfo();
  13867. };
  13868. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13869. var _this = this;
  13870. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13871. /// <param name="x">X position on screen</param>
  13872. /// <param name="y">Y position on screen</param>
  13873. /// <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>
  13874. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13875. /// <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>
  13876. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13877. };
  13878. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13879. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13880. /// <param name="x">X position on screen</param>
  13881. /// <param name="y">Y position on screen</param>
  13882. /// <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>
  13883. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13884. /// <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>
  13885. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13886. };
  13887. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13888. var _this = this;
  13889. return this._internalPick(function (world) {
  13890. if (!_this._pickWithRayInverseMatrix) {
  13891. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13892. }
  13893. world.invertToRef(_this._pickWithRayInverseMatrix);
  13894. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13895. }, predicate, fastCheck);
  13896. };
  13897. Scene.prototype.setPointerOverMesh = function (mesh) {
  13898. if (this._pointerOverMesh === mesh) {
  13899. return;
  13900. }
  13901. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13902. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13903. }
  13904. this._pointerOverMesh = mesh;
  13905. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13906. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13907. }
  13908. };
  13909. Scene.prototype.getPointerOverMesh = function () {
  13910. return this._pointerOverMesh;
  13911. };
  13912. // Physics
  13913. Scene.prototype.getPhysicsEngine = function () {
  13914. return this._physicsEngine;
  13915. };
  13916. /**
  13917. * Enables physics to the current scene
  13918. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13919. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13920. * @return {boolean} was the physics engine initialized
  13921. */
  13922. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13923. if (this._physicsEngine) {
  13924. return true;
  13925. }
  13926. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13927. if (!this._physicsEngine.isSupported()) {
  13928. this._physicsEngine = null;
  13929. return false;
  13930. }
  13931. this._physicsEngine._initialize(gravity);
  13932. return true;
  13933. };
  13934. Scene.prototype.disablePhysicsEngine = function () {
  13935. if (!this._physicsEngine) {
  13936. return;
  13937. }
  13938. this._physicsEngine.dispose();
  13939. this._physicsEngine = undefined;
  13940. };
  13941. Scene.prototype.isPhysicsEnabled = function () {
  13942. return this._physicsEngine !== undefined;
  13943. };
  13944. /**
  13945. * Sets the gravity of the physics engine (and NOT of the scene)
  13946. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13947. */
  13948. Scene.prototype.setGravity = function (gravity) {
  13949. if (!this._physicsEngine) {
  13950. return;
  13951. }
  13952. this._physicsEngine._setGravity(gravity);
  13953. };
  13954. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13955. if (parts.parts) {
  13956. options = parts;
  13957. parts = parts.parts;
  13958. }
  13959. if (!this._physicsEngine) {
  13960. return null;
  13961. }
  13962. for (var index = 0; index < parts.length; index++) {
  13963. var mesh = parts[index].mesh;
  13964. mesh._physicImpostor = parts[index].impostor;
  13965. mesh._physicsMass = options.mass / parts.length;
  13966. mesh._physicsFriction = options.friction;
  13967. mesh._physicRestitution = options.restitution;
  13968. }
  13969. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13970. };
  13971. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13972. for (var index = 0; index < compound.parts.length; index++) {
  13973. var mesh = compound.parts[index].mesh;
  13974. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13975. this._physicsEngine._unregisterMesh(mesh);
  13976. }
  13977. };
  13978. // Misc.
  13979. Scene.prototype.createDefaultCameraOrLight = function () {
  13980. // Light
  13981. if (this.lights.length === 0) {
  13982. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13983. }
  13984. // Camera
  13985. if (!this.activeCamera) {
  13986. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13987. // Compute position
  13988. var worldExtends = this.getWorldExtends();
  13989. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13990. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13991. camera.setTarget(worldCenter);
  13992. this.activeCamera = camera;
  13993. }
  13994. };
  13995. // Tags
  13996. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13997. if (tagsQuery === undefined) {
  13998. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13999. return list;
  14000. }
  14001. var listByTags = [];
  14002. forEach = forEach || (function (item) { return; });
  14003. for (var i in list) {
  14004. var item = list[i];
  14005. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14006. listByTags.push(item);
  14007. forEach(item);
  14008. }
  14009. }
  14010. return listByTags;
  14011. };
  14012. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14013. return this._getByTags(this.meshes, tagsQuery, forEach);
  14014. };
  14015. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14016. return this._getByTags(this.cameras, tagsQuery, forEach);
  14017. };
  14018. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14019. return this._getByTags(this.lights, tagsQuery, forEach);
  14020. };
  14021. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14022. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14023. };
  14024. // Statics
  14025. Scene._FOGMODE_NONE = 0;
  14026. Scene._FOGMODE_EXP = 1;
  14027. Scene._FOGMODE_EXP2 = 2;
  14028. Scene._FOGMODE_LINEAR = 3;
  14029. Scene.MinDeltaTime = 1.0;
  14030. Scene.MaxDeltaTime = 1000.0;
  14031. return Scene;
  14032. })();
  14033. BABYLON.Scene = Scene;
  14034. })(BABYLON || (BABYLON = {}));
  14035. var BABYLON;
  14036. (function (BABYLON) {
  14037. var VertexBuffer = (function () {
  14038. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14039. if (engine instanceof BABYLON.Mesh) {
  14040. this._engine = engine.getScene().getEngine();
  14041. }
  14042. else {
  14043. this._engine = engine;
  14044. }
  14045. this._updatable = updatable;
  14046. this._data = data;
  14047. if (!postponeInternalCreation) {
  14048. this.create();
  14049. }
  14050. this._kind = kind;
  14051. if (stride) {
  14052. this._strideSize = stride;
  14053. return;
  14054. }
  14055. // Deduce stride from kind
  14056. switch (kind) {
  14057. case VertexBuffer.PositionKind:
  14058. this._strideSize = 3;
  14059. break;
  14060. case VertexBuffer.NormalKind:
  14061. this._strideSize = 3;
  14062. break;
  14063. case VertexBuffer.UVKind:
  14064. case VertexBuffer.UV2Kind:
  14065. case VertexBuffer.UV3Kind:
  14066. case VertexBuffer.UV4Kind:
  14067. case VertexBuffer.UV5Kind:
  14068. case VertexBuffer.UV6Kind:
  14069. this._strideSize = 2;
  14070. break;
  14071. case VertexBuffer.ColorKind:
  14072. this._strideSize = 4;
  14073. break;
  14074. case VertexBuffer.MatricesIndicesKind:
  14075. case VertexBuffer.MatricesIndicesExtraKind:
  14076. this._strideSize = 4;
  14077. break;
  14078. case VertexBuffer.MatricesWeightsKind:
  14079. case VertexBuffer.MatricesWeightsExtraKind:
  14080. this._strideSize = 4;
  14081. break;
  14082. }
  14083. }
  14084. // Properties
  14085. VertexBuffer.prototype.isUpdatable = function () {
  14086. return this._updatable;
  14087. };
  14088. VertexBuffer.prototype.getData = function () {
  14089. return this._data;
  14090. };
  14091. VertexBuffer.prototype.getBuffer = function () {
  14092. return this._buffer;
  14093. };
  14094. VertexBuffer.prototype.getStrideSize = function () {
  14095. return this._strideSize;
  14096. };
  14097. // Methods
  14098. VertexBuffer.prototype.create = function (data) {
  14099. if (!data && this._buffer) {
  14100. return; // nothing to do
  14101. }
  14102. data = data || this._data;
  14103. if (!this._buffer) {
  14104. if (this._updatable) {
  14105. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14106. }
  14107. else {
  14108. this._buffer = this._engine.createVertexBuffer(data);
  14109. }
  14110. }
  14111. if (this._updatable) {
  14112. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14113. this._data = data;
  14114. }
  14115. };
  14116. VertexBuffer.prototype.update = function (data) {
  14117. this.create(data);
  14118. };
  14119. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14120. if (!this._buffer) {
  14121. return;
  14122. }
  14123. if (this._updatable) {
  14124. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14125. this._data = null;
  14126. }
  14127. };
  14128. VertexBuffer.prototype.dispose = function () {
  14129. if (!this._buffer) {
  14130. return;
  14131. }
  14132. if (this._engine._releaseBuffer(this._buffer)) {
  14133. this._buffer = null;
  14134. }
  14135. };
  14136. Object.defineProperty(VertexBuffer, "PositionKind", {
  14137. get: function () {
  14138. return VertexBuffer._PositionKind;
  14139. },
  14140. enumerable: true,
  14141. configurable: true
  14142. });
  14143. Object.defineProperty(VertexBuffer, "NormalKind", {
  14144. get: function () {
  14145. return VertexBuffer._NormalKind;
  14146. },
  14147. enumerable: true,
  14148. configurable: true
  14149. });
  14150. Object.defineProperty(VertexBuffer, "UVKind", {
  14151. get: function () {
  14152. return VertexBuffer._UVKind;
  14153. },
  14154. enumerable: true,
  14155. configurable: true
  14156. });
  14157. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14158. get: function () {
  14159. return VertexBuffer._UV2Kind;
  14160. },
  14161. enumerable: true,
  14162. configurable: true
  14163. });
  14164. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14165. get: function () {
  14166. return VertexBuffer._UV3Kind;
  14167. },
  14168. enumerable: true,
  14169. configurable: true
  14170. });
  14171. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14172. get: function () {
  14173. return VertexBuffer._UV4Kind;
  14174. },
  14175. enumerable: true,
  14176. configurable: true
  14177. });
  14178. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14179. get: function () {
  14180. return VertexBuffer._UV5Kind;
  14181. },
  14182. enumerable: true,
  14183. configurable: true
  14184. });
  14185. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14186. get: function () {
  14187. return VertexBuffer._UV6Kind;
  14188. },
  14189. enumerable: true,
  14190. configurable: true
  14191. });
  14192. Object.defineProperty(VertexBuffer, "ColorKind", {
  14193. get: function () {
  14194. return VertexBuffer._ColorKind;
  14195. },
  14196. enumerable: true,
  14197. configurable: true
  14198. });
  14199. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14200. get: function () {
  14201. return VertexBuffer._MatricesIndicesKind;
  14202. },
  14203. enumerable: true,
  14204. configurable: true
  14205. });
  14206. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14207. get: function () {
  14208. return VertexBuffer._MatricesWeightsKind;
  14209. },
  14210. enumerable: true,
  14211. configurable: true
  14212. });
  14213. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14214. get: function () {
  14215. return VertexBuffer._MatricesIndicesExtraKind;
  14216. },
  14217. enumerable: true,
  14218. configurable: true
  14219. });
  14220. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14221. get: function () {
  14222. return VertexBuffer._MatricesWeightsExtraKind;
  14223. },
  14224. enumerable: true,
  14225. configurable: true
  14226. });
  14227. // Enums
  14228. VertexBuffer._PositionKind = "position";
  14229. VertexBuffer._NormalKind = "normal";
  14230. VertexBuffer._UVKind = "uv";
  14231. VertexBuffer._UV2Kind = "uv2";
  14232. VertexBuffer._UV3Kind = "uv3";
  14233. VertexBuffer._UV4Kind = "uv4";
  14234. VertexBuffer._UV5Kind = "uv5";
  14235. VertexBuffer._UV6Kind = "uv6";
  14236. VertexBuffer._ColorKind = "color";
  14237. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14238. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14239. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14240. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14241. return VertexBuffer;
  14242. })();
  14243. BABYLON.VertexBuffer = VertexBuffer;
  14244. })(BABYLON || (BABYLON = {}));
  14245. var BABYLON;
  14246. (function (BABYLON) {
  14247. /**
  14248. * Creates an instance based on a source mesh.
  14249. */
  14250. var InstancedMesh = (function (_super) {
  14251. __extends(InstancedMesh, _super);
  14252. function InstancedMesh(name, source) {
  14253. _super.call(this, name, source.getScene());
  14254. source.instances.push(this);
  14255. this._sourceMesh = source;
  14256. this.position.copyFrom(source.position);
  14257. this.rotation.copyFrom(source.rotation);
  14258. this.scaling.copyFrom(source.scaling);
  14259. if (source.rotationQuaternion) {
  14260. this.rotationQuaternion = source.rotationQuaternion.clone();
  14261. }
  14262. this.infiniteDistance = source.infiniteDistance;
  14263. this.setPivotMatrix(source.getPivotMatrix());
  14264. this.refreshBoundingInfo();
  14265. this._syncSubMeshes();
  14266. }
  14267. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14268. // Methods
  14269. get: function () {
  14270. return this._sourceMesh.receiveShadows;
  14271. },
  14272. enumerable: true,
  14273. configurable: true
  14274. });
  14275. Object.defineProperty(InstancedMesh.prototype, "material", {
  14276. get: function () {
  14277. return this._sourceMesh.material;
  14278. },
  14279. enumerable: true,
  14280. configurable: true
  14281. });
  14282. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14283. get: function () {
  14284. return this._sourceMesh.visibility;
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14290. get: function () {
  14291. return this._sourceMesh.skeleton;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14297. get: function () {
  14298. return this._sourceMesh.renderingGroupId;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. InstancedMesh.prototype.getTotalVertices = function () {
  14304. return this._sourceMesh.getTotalVertices();
  14305. };
  14306. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14307. get: function () {
  14308. return this._sourceMesh;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14314. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14315. };
  14316. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14317. return this._sourceMesh.isVerticesDataPresent(kind);
  14318. };
  14319. InstancedMesh.prototype.getIndices = function () {
  14320. return this._sourceMesh.getIndices();
  14321. };
  14322. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14323. get: function () {
  14324. return this._sourceMesh._positions;
  14325. },
  14326. enumerable: true,
  14327. configurable: true
  14328. });
  14329. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14330. var meshBB = this._sourceMesh.getBoundingInfo();
  14331. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14332. this._updateBoundingInfo();
  14333. };
  14334. InstancedMesh.prototype._preActivate = function () {
  14335. if (this._currentLOD) {
  14336. this._currentLOD._preActivate();
  14337. }
  14338. };
  14339. InstancedMesh.prototype._activate = function (renderId) {
  14340. if (this._currentLOD) {
  14341. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14342. }
  14343. };
  14344. InstancedMesh.prototype.getLOD = function (camera) {
  14345. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14346. if (this._currentLOD === this.sourceMesh) {
  14347. return this;
  14348. }
  14349. return this._currentLOD;
  14350. };
  14351. InstancedMesh.prototype._syncSubMeshes = function () {
  14352. this.releaseSubMeshes();
  14353. if (this._sourceMesh.subMeshes) {
  14354. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14355. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14356. }
  14357. }
  14358. };
  14359. InstancedMesh.prototype._generatePointsArray = function () {
  14360. return this._sourceMesh._generatePointsArray();
  14361. };
  14362. // Clone
  14363. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14364. var result = this._sourceMesh.createInstance(name);
  14365. // Deep copy
  14366. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14367. // Bounding info
  14368. this.refreshBoundingInfo();
  14369. // Parent
  14370. if (newParent) {
  14371. result.parent = newParent;
  14372. }
  14373. if (!doNotCloneChildren) {
  14374. // Children
  14375. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14376. var mesh = this.getScene().meshes[index];
  14377. if (mesh.parent === this) {
  14378. mesh.clone(mesh.name, result);
  14379. }
  14380. }
  14381. }
  14382. result.computeWorldMatrix(true);
  14383. return result;
  14384. };
  14385. // Dispoe
  14386. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14387. // Remove from mesh
  14388. var index = this._sourceMesh.instances.indexOf(this);
  14389. this._sourceMesh.instances.splice(index, 1);
  14390. _super.prototype.dispose.call(this, doNotRecurse);
  14391. };
  14392. return InstancedMesh;
  14393. })(BABYLON.AbstractMesh);
  14394. BABYLON.InstancedMesh = InstancedMesh;
  14395. })(BABYLON || (BABYLON = {}));
  14396. var BABYLON;
  14397. (function (BABYLON) {
  14398. var _InstancesBatch = (function () {
  14399. function _InstancesBatch() {
  14400. this.mustReturn = false;
  14401. this.visibleInstances = new Array();
  14402. this.renderSelf = new Array();
  14403. }
  14404. return _InstancesBatch;
  14405. })();
  14406. BABYLON._InstancesBatch = _InstancesBatch;
  14407. var Mesh = (function (_super) {
  14408. __extends(Mesh, _super);
  14409. /**
  14410. * @constructor
  14411. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14412. * @param {Scene} scene - The scene to add this mesh to.
  14413. * @param {Node} parent - The parent of this mesh, if it has one
  14414. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14415. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14416. * When false, achieved by calling a clone(), also passing False.
  14417. * This will make creation of children, recursive.
  14418. */
  14419. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14420. if (parent === void 0) { parent = null; }
  14421. _super.call(this, name, scene);
  14422. // Members
  14423. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14424. this.instances = new Array();
  14425. this._LODLevels = new Array();
  14426. this._onBeforeRenderCallbacks = new Array();
  14427. this._onAfterRenderCallbacks = new Array();
  14428. this._visibleInstances = {};
  14429. this._renderIdForInstances = new Array();
  14430. this._batchCache = new _InstancesBatch();
  14431. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14432. this._sideOrientation = Mesh._DEFAULTSIDE;
  14433. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14434. if (source) {
  14435. // Geometry
  14436. if (source._geometry) {
  14437. source._geometry.applyToMesh(this);
  14438. }
  14439. // Deep copy
  14440. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14441. this.id = name + "." + source.id;
  14442. // Material
  14443. this.material = source.material;
  14444. var index;
  14445. if (!doNotCloneChildren) {
  14446. // Children
  14447. for (index = 0; index < scene.meshes.length; index++) {
  14448. var mesh = scene.meshes[index];
  14449. if (mesh.parent === source) {
  14450. // doNotCloneChildren is always going to be False
  14451. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14452. }
  14453. }
  14454. }
  14455. // Particles
  14456. for (index = 0; index < scene.particleSystems.length; index++) {
  14457. var system = scene.particleSystems[index];
  14458. if (system.emitter === source) {
  14459. system.clone(system.name, this);
  14460. }
  14461. }
  14462. this.computeWorldMatrix(true);
  14463. }
  14464. // Parent
  14465. if (parent !== null) {
  14466. this.parent = parent;
  14467. }
  14468. }
  14469. Object.defineProperty(Mesh, "FRONTSIDE", {
  14470. get: function () {
  14471. return Mesh._FRONTSIDE;
  14472. },
  14473. enumerable: true,
  14474. configurable: true
  14475. });
  14476. Object.defineProperty(Mesh, "BACKSIDE", {
  14477. get: function () {
  14478. return Mesh._BACKSIDE;
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14484. get: function () {
  14485. return Mesh._DOUBLESIDE;
  14486. },
  14487. enumerable: true,
  14488. configurable: true
  14489. });
  14490. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14491. get: function () {
  14492. return Mesh._DEFAULTSIDE;
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(Mesh, "NO_CAP", {
  14498. get: function () {
  14499. return Mesh._NO_CAP;
  14500. },
  14501. enumerable: true,
  14502. configurable: true
  14503. });
  14504. Object.defineProperty(Mesh, "CAP_START", {
  14505. get: function () {
  14506. return Mesh._CAP_START;
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(Mesh, "CAP_END", {
  14512. get: function () {
  14513. return Mesh._CAP_END;
  14514. },
  14515. enumerable: true,
  14516. configurable: true
  14517. });
  14518. Object.defineProperty(Mesh, "CAP_ALL", {
  14519. get: function () {
  14520. return Mesh._CAP_ALL;
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14526. // Methods
  14527. get: function () {
  14528. return this._LODLevels.length > 0;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. Mesh.prototype._sortLODLevels = function () {
  14534. this._LODLevels.sort(function (a, b) {
  14535. if (a.distance < b.distance) {
  14536. return 1;
  14537. }
  14538. if (a.distance > b.distance) {
  14539. return -1;
  14540. }
  14541. return 0;
  14542. });
  14543. };
  14544. /**
  14545. * Add a mesh as LOD level triggered at the given distance.
  14546. * @param {number} distance - the distance from the center of the object to show this level
  14547. * @param {Mesh} mesh - the mesh to be added as LOD level
  14548. * @return {Mesh} this mesh (for chaining)
  14549. */
  14550. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14551. if (mesh && mesh._masterMesh) {
  14552. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14553. return this;
  14554. }
  14555. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14556. this._LODLevels.push(level);
  14557. if (mesh) {
  14558. mesh._masterMesh = this;
  14559. }
  14560. this._sortLODLevels();
  14561. return this;
  14562. };
  14563. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14564. for (var index = 0; index < this._LODLevels.length; index++) {
  14565. var level = this._LODLevels[index];
  14566. if (level.distance === distance) {
  14567. return level.mesh;
  14568. }
  14569. }
  14570. return null;
  14571. };
  14572. /**
  14573. * Remove a mesh from the LOD array
  14574. * @param {Mesh} mesh - the mesh to be removed.
  14575. * @return {Mesh} this mesh (for chaining)
  14576. */
  14577. Mesh.prototype.removeLODLevel = function (mesh) {
  14578. for (var index = 0; index < this._LODLevels.length; index++) {
  14579. if (this._LODLevels[index].mesh === mesh) {
  14580. this._LODLevels.splice(index, 1);
  14581. if (mesh) {
  14582. mesh._masterMesh = null;
  14583. }
  14584. }
  14585. }
  14586. this._sortLODLevels();
  14587. return this;
  14588. };
  14589. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14590. if (!this._LODLevels || this._LODLevels.length === 0) {
  14591. return this;
  14592. }
  14593. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14594. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14595. if (this.onLODLevelSelection) {
  14596. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14597. }
  14598. return this;
  14599. }
  14600. for (var index = 0; index < this._LODLevels.length; index++) {
  14601. var level = this._LODLevels[index];
  14602. if (level.distance < distanceToCamera) {
  14603. if (level.mesh) {
  14604. level.mesh._preActivate();
  14605. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14606. }
  14607. if (this.onLODLevelSelection) {
  14608. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14609. }
  14610. return level.mesh;
  14611. }
  14612. }
  14613. if (this.onLODLevelSelection) {
  14614. this.onLODLevelSelection(distanceToCamera, this, this);
  14615. }
  14616. return this;
  14617. };
  14618. Object.defineProperty(Mesh.prototype, "geometry", {
  14619. get: function () {
  14620. return this._geometry;
  14621. },
  14622. enumerable: true,
  14623. configurable: true
  14624. });
  14625. Mesh.prototype.getTotalVertices = function () {
  14626. if (!this._geometry) {
  14627. return 0;
  14628. }
  14629. return this._geometry.getTotalVertices();
  14630. };
  14631. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14632. if (!this._geometry) {
  14633. return null;
  14634. }
  14635. return this._geometry.getVerticesData(kind, copyWhenShared);
  14636. };
  14637. Mesh.prototype.getVertexBuffer = function (kind) {
  14638. if (!this._geometry) {
  14639. return undefined;
  14640. }
  14641. return this._geometry.getVertexBuffer(kind);
  14642. };
  14643. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14644. if (!this._geometry) {
  14645. if (this._delayInfo) {
  14646. return this._delayInfo.indexOf(kind) !== -1;
  14647. }
  14648. return false;
  14649. }
  14650. return this._geometry.isVerticesDataPresent(kind);
  14651. };
  14652. Mesh.prototype.getVerticesDataKinds = function () {
  14653. if (!this._geometry) {
  14654. var result = [];
  14655. if (this._delayInfo) {
  14656. for (var kind in this._delayInfo) {
  14657. result.push(kind);
  14658. }
  14659. }
  14660. return result;
  14661. }
  14662. return this._geometry.getVerticesDataKinds();
  14663. };
  14664. Mesh.prototype.getTotalIndices = function () {
  14665. if (!this._geometry) {
  14666. return 0;
  14667. }
  14668. return this._geometry.getTotalIndices();
  14669. };
  14670. Mesh.prototype.getIndices = function (copyWhenShared) {
  14671. if (!this._geometry) {
  14672. return [];
  14673. }
  14674. return this._geometry.getIndices(copyWhenShared);
  14675. };
  14676. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14677. get: function () {
  14678. return this._masterMesh !== null && this._masterMesh !== undefined;
  14679. },
  14680. enumerable: true,
  14681. configurable: true
  14682. });
  14683. Mesh.prototype.isReady = function () {
  14684. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14685. return false;
  14686. }
  14687. return _super.prototype.isReady.call(this);
  14688. };
  14689. Mesh.prototype.isDisposed = function () {
  14690. return this._isDisposed;
  14691. };
  14692. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14693. get: function () {
  14694. return this._sideOrientation;
  14695. },
  14696. set: function (sideO) {
  14697. this._sideOrientation = sideO;
  14698. },
  14699. enumerable: true,
  14700. configurable: true
  14701. });
  14702. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14703. get: function () {
  14704. return this._areNormalsFrozen;
  14705. },
  14706. enumerable: true,
  14707. configurable: true
  14708. });
  14709. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14710. Mesh.prototype.freezeNormals = function () {
  14711. this._areNormalsFrozen = true;
  14712. };
  14713. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14714. Mesh.prototype.unfreezeNormals = function () {
  14715. this._areNormalsFrozen = false;
  14716. };
  14717. // Methods
  14718. Mesh.prototype._preActivate = function () {
  14719. var sceneRenderId = this.getScene().getRenderId();
  14720. if (this._preActivateId === sceneRenderId) {
  14721. return;
  14722. }
  14723. this._preActivateId = sceneRenderId;
  14724. this._visibleInstances = null;
  14725. };
  14726. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14727. if (!this._visibleInstances) {
  14728. this._visibleInstances = {};
  14729. this._visibleInstances.defaultRenderId = renderId;
  14730. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14731. }
  14732. if (!this._visibleInstances[renderId]) {
  14733. this._visibleInstances[renderId] = new Array();
  14734. }
  14735. this._visibleInstances[renderId].push(instance);
  14736. };
  14737. Mesh.prototype.refreshBoundingInfo = function () {
  14738. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14739. if (data) {
  14740. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14741. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14742. }
  14743. if (this.subMeshes) {
  14744. for (var index = 0; index < this.subMeshes.length; index++) {
  14745. this.subMeshes[index].refreshBoundingInfo();
  14746. }
  14747. }
  14748. this._updateBoundingInfo();
  14749. };
  14750. Mesh.prototype._createGlobalSubMesh = function () {
  14751. var totalVertices = this.getTotalVertices();
  14752. if (!totalVertices || !this.getIndices()) {
  14753. return null;
  14754. }
  14755. this.releaseSubMeshes();
  14756. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14757. };
  14758. Mesh.prototype.subdivide = function (count) {
  14759. if (count < 1) {
  14760. return;
  14761. }
  14762. var totalIndices = this.getTotalIndices();
  14763. var subdivisionSize = (totalIndices / count) | 0;
  14764. var offset = 0;
  14765. // Ensure that subdivisionSize is a multiple of 3
  14766. while (subdivisionSize % 3 !== 0) {
  14767. subdivisionSize++;
  14768. }
  14769. this.releaseSubMeshes();
  14770. for (var index = 0; index < count; index++) {
  14771. if (offset >= totalIndices) {
  14772. break;
  14773. }
  14774. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14775. offset += subdivisionSize;
  14776. }
  14777. this.synchronizeInstances();
  14778. };
  14779. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14780. if (!this._geometry) {
  14781. var vertexData = new BABYLON.VertexData();
  14782. vertexData.set(data, kind);
  14783. var scene = this.getScene();
  14784. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14785. }
  14786. else {
  14787. this._geometry.setVerticesData(kind, data, updatable, stride);
  14788. }
  14789. };
  14790. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14791. if (!this._geometry) {
  14792. return;
  14793. }
  14794. if (!makeItUnique) {
  14795. this._geometry.updateVerticesData(kind, data, updateExtends);
  14796. }
  14797. else {
  14798. this.makeGeometryUnique();
  14799. this.updateVerticesData(kind, data, updateExtends, false);
  14800. }
  14801. };
  14802. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14803. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14804. if (!this._geometry) {
  14805. return;
  14806. }
  14807. if (!makeItUnique) {
  14808. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14809. }
  14810. else {
  14811. this.makeGeometryUnique();
  14812. this.updateVerticesDataDirectly(kind, data, offset, false);
  14813. }
  14814. };
  14815. // Mesh positions update function :
  14816. // updates the mesh positions according to the positionFunction returned values.
  14817. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14818. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14819. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14820. if (computeNormals === void 0) { computeNormals = true; }
  14821. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14822. positionFunction(positions);
  14823. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14824. if (computeNormals) {
  14825. var indices = this.getIndices();
  14826. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14827. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14828. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14829. }
  14830. };
  14831. Mesh.prototype.makeGeometryUnique = function () {
  14832. if (!this._geometry) {
  14833. return;
  14834. }
  14835. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14836. geometry.applyToMesh(this);
  14837. };
  14838. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14839. if (!this._geometry) {
  14840. var vertexData = new BABYLON.VertexData();
  14841. vertexData.indices = indices;
  14842. var scene = this.getScene();
  14843. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14844. }
  14845. else {
  14846. this._geometry.setIndices(indices, totalVertices);
  14847. }
  14848. };
  14849. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14850. var engine = this.getScene().getEngine();
  14851. // Wireframe
  14852. var indexToBind;
  14853. if (this._unIndexed) {
  14854. indexToBind = null;
  14855. }
  14856. else {
  14857. switch (fillMode) {
  14858. case BABYLON.Material.PointFillMode:
  14859. indexToBind = null;
  14860. break;
  14861. case BABYLON.Material.WireFrameFillMode:
  14862. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14863. break;
  14864. default:
  14865. case BABYLON.Material.TriangleFillMode:
  14866. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  14867. break;
  14868. }
  14869. }
  14870. // VBOs
  14871. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14872. };
  14873. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14874. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14875. return;
  14876. }
  14877. var engine = this.getScene().getEngine();
  14878. // Draw order
  14879. switch (fillMode) {
  14880. case BABYLON.Material.PointFillMode:
  14881. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14882. break;
  14883. case BABYLON.Material.WireFrameFillMode:
  14884. if (this._unIndexed) {
  14885. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14886. }
  14887. else {
  14888. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14889. }
  14890. break;
  14891. default:
  14892. if (this._unIndexed) {
  14893. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14894. }
  14895. else {
  14896. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14897. }
  14898. }
  14899. };
  14900. Mesh.prototype.registerBeforeRender = function (func) {
  14901. this._onBeforeRenderCallbacks.push(func);
  14902. };
  14903. Mesh.prototype.unregisterBeforeRender = function (func) {
  14904. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14905. if (index > -1) {
  14906. this._onBeforeRenderCallbacks.splice(index, 1);
  14907. }
  14908. };
  14909. Mesh.prototype.registerAfterRender = function (func) {
  14910. this._onAfterRenderCallbacks.push(func);
  14911. };
  14912. Mesh.prototype.unregisterAfterRender = function (func) {
  14913. var index = this._onAfterRenderCallbacks.indexOf(func);
  14914. if (index > -1) {
  14915. this._onAfterRenderCallbacks.splice(index, 1);
  14916. }
  14917. };
  14918. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14919. var scene = this.getScene();
  14920. this._batchCache.mustReturn = false;
  14921. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14922. this._batchCache.visibleInstances[subMeshId] = null;
  14923. if (this._visibleInstances) {
  14924. var currentRenderId = scene.getRenderId();
  14925. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14926. var selfRenderId = this._renderId;
  14927. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14928. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14929. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14930. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14931. }
  14932. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14933. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14934. this._batchCache.mustReturn = true;
  14935. return this._batchCache;
  14936. }
  14937. if (currentRenderId !== selfRenderId) {
  14938. this._batchCache.renderSelf[subMeshId] = false;
  14939. }
  14940. }
  14941. this._renderIdForInstances[subMeshId] = currentRenderId;
  14942. }
  14943. return this._batchCache;
  14944. };
  14945. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14946. var visibleInstances = batch.visibleInstances[subMesh._id];
  14947. var matricesCount = visibleInstances.length + 1;
  14948. var bufferSize = matricesCount * 16 * 4;
  14949. while (this._instancesBufferSize < bufferSize) {
  14950. this._instancesBufferSize *= 2;
  14951. }
  14952. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14953. if (this._worldMatricesInstancesBuffer) {
  14954. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14955. }
  14956. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14957. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14958. }
  14959. var offset = 0;
  14960. var instancesCount = 0;
  14961. var world = this.getWorldMatrix();
  14962. if (batch.renderSelf[subMesh._id]) {
  14963. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14964. offset += 16;
  14965. instancesCount++;
  14966. }
  14967. if (visibleInstances) {
  14968. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14969. var instance = visibleInstances[instanceIndex];
  14970. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14971. offset += 16;
  14972. instancesCount++;
  14973. }
  14974. }
  14975. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14976. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14977. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14978. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14979. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14980. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14981. this._draw(subMesh, fillMode, instancesCount);
  14982. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14983. };
  14984. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14985. var scene = this.getScene();
  14986. var engine = scene.getEngine();
  14987. if (hardwareInstancedRendering) {
  14988. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14989. }
  14990. else {
  14991. if (batch.renderSelf[subMesh._id]) {
  14992. // Draw
  14993. if (onBeforeDraw) {
  14994. onBeforeDraw(false, this.getWorldMatrix());
  14995. }
  14996. this._draw(subMesh, fillMode);
  14997. }
  14998. if (batch.visibleInstances[subMesh._id]) {
  14999. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15000. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15001. // World
  15002. var world = instance.getWorldMatrix();
  15003. if (onBeforeDraw) {
  15004. onBeforeDraw(true, world);
  15005. }
  15006. // Draw
  15007. this._draw(subMesh, fillMode);
  15008. }
  15009. }
  15010. }
  15011. };
  15012. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15013. var scene = this.getScene();
  15014. // Managing instances
  15015. var batch = this._getInstancesRenderList(subMesh._id);
  15016. if (batch.mustReturn) {
  15017. return;
  15018. }
  15019. // Checking geometry state
  15020. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15021. return;
  15022. }
  15023. var callbackIndex;
  15024. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15025. this._onBeforeRenderCallbacks[callbackIndex](this);
  15026. }
  15027. var engine = scene.getEngine();
  15028. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15029. // Material
  15030. var effectiveMaterial = subMesh.getMaterial();
  15031. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15032. return;
  15033. }
  15034. // Outline - step 1
  15035. var savedDepthWrite = engine.getDepthWrite();
  15036. if (this.renderOutline) {
  15037. engine.setDepthWrite(false);
  15038. scene.getOutlineRenderer().render(subMesh, batch);
  15039. engine.setDepthWrite(savedDepthWrite);
  15040. }
  15041. effectiveMaterial._preBind();
  15042. var effect = effectiveMaterial.getEffect();
  15043. // Bind
  15044. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15045. this._bind(subMesh, effect, fillMode);
  15046. var world = this.getWorldMatrix();
  15047. effectiveMaterial.bind(world, this);
  15048. // Alpha mode
  15049. if (enableAlphaMode) {
  15050. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15051. }
  15052. // Draw
  15053. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15054. if (isInstance) {
  15055. effectiveMaterial.bindOnlyWorldMatrix(world);
  15056. }
  15057. });
  15058. // Unbind
  15059. effectiveMaterial.unbind();
  15060. // Outline - step 2
  15061. if (this.renderOutline && savedDepthWrite) {
  15062. engine.setDepthWrite(true);
  15063. engine.setColorWrite(false);
  15064. scene.getOutlineRenderer().render(subMesh, batch);
  15065. engine.setColorWrite(true);
  15066. }
  15067. // Overlay
  15068. if (this.renderOverlay) {
  15069. var currentMode = engine.getAlphaMode();
  15070. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15071. scene.getOutlineRenderer().render(subMesh, batch, true);
  15072. engine.setAlphaMode(currentMode);
  15073. }
  15074. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15075. this._onAfterRenderCallbacks[callbackIndex](this);
  15076. }
  15077. };
  15078. Mesh.prototype.getEmittedParticleSystems = function () {
  15079. var results = new Array();
  15080. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15081. var particleSystem = this.getScene().particleSystems[index];
  15082. if (particleSystem.emitter === this) {
  15083. results.push(particleSystem);
  15084. }
  15085. }
  15086. return results;
  15087. };
  15088. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15089. var results = new Array();
  15090. var descendants = this.getDescendants();
  15091. descendants.push(this);
  15092. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15093. var particleSystem = this.getScene().particleSystems[index];
  15094. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15095. results.push(particleSystem);
  15096. }
  15097. }
  15098. return results;
  15099. };
  15100. Mesh.prototype.getChildren = function () {
  15101. var results = [];
  15102. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15103. var mesh = this.getScene().meshes[index];
  15104. if (mesh.parent === this) {
  15105. results.push(mesh);
  15106. }
  15107. }
  15108. return results;
  15109. };
  15110. Mesh.prototype._checkDelayState = function () {
  15111. var _this = this;
  15112. var that = this;
  15113. var scene = this.getScene();
  15114. if (this._geometry) {
  15115. this._geometry.load(scene);
  15116. }
  15117. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15118. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15119. scene._addPendingData(that);
  15120. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15121. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15122. if (data instanceof ArrayBuffer) {
  15123. _this._delayLoadingFunction(data, _this);
  15124. }
  15125. else {
  15126. _this._delayLoadingFunction(JSON.parse(data), _this);
  15127. }
  15128. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15129. scene._removePendingData(_this);
  15130. }, function () { }, scene.database, getBinaryData);
  15131. }
  15132. };
  15133. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15134. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15135. return false;
  15136. }
  15137. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15138. return false;
  15139. }
  15140. this._checkDelayState();
  15141. return true;
  15142. };
  15143. Mesh.prototype.setMaterialByID = function (id) {
  15144. var materials = this.getScene().materials;
  15145. var index;
  15146. for (index = 0; index < materials.length; index++) {
  15147. if (materials[index].id === id) {
  15148. this.material = materials[index];
  15149. return;
  15150. }
  15151. }
  15152. // Multi
  15153. var multiMaterials = this.getScene().multiMaterials;
  15154. for (index = 0; index < multiMaterials.length; index++) {
  15155. if (multiMaterials[index].id === id) {
  15156. this.material = multiMaterials[index];
  15157. return;
  15158. }
  15159. }
  15160. };
  15161. Mesh.prototype.getAnimatables = function () {
  15162. var results = [];
  15163. if (this.material) {
  15164. results.push(this.material);
  15165. }
  15166. if (this.skeleton) {
  15167. results.push(this.skeleton);
  15168. }
  15169. return results;
  15170. };
  15171. // Geometry
  15172. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15173. // Position
  15174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15175. return;
  15176. }
  15177. this._resetPointsArrayCache();
  15178. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15179. var temp = [];
  15180. var index;
  15181. for (index = 0; index < data.length; index += 3) {
  15182. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15183. }
  15184. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15185. // Normals
  15186. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15187. return;
  15188. }
  15189. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15190. temp = [];
  15191. for (index = 0; index < data.length; index += 3) {
  15192. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15193. }
  15194. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15195. // flip faces?
  15196. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15197. this.flipFaces();
  15198. }
  15199. };
  15200. // Will apply current transform to mesh and reset world matrix
  15201. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15202. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15203. this.scaling.copyFromFloats(1, 1, 1);
  15204. this.position.copyFromFloats(0, 0, 0);
  15205. this.rotation.copyFromFloats(0, 0, 0);
  15206. //only if quaternion is already set
  15207. if (this.rotationQuaternion) {
  15208. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15209. }
  15210. this._worldMatrix = BABYLON.Matrix.Identity();
  15211. };
  15212. // Cache
  15213. Mesh.prototype._resetPointsArrayCache = function () {
  15214. this._positions = null;
  15215. };
  15216. Mesh.prototype._generatePointsArray = function () {
  15217. if (this._positions)
  15218. return true;
  15219. this._positions = [];
  15220. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15221. if (!data) {
  15222. return false;
  15223. }
  15224. for (var index = 0; index < data.length; index += 3) {
  15225. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15226. }
  15227. return true;
  15228. };
  15229. // Clone
  15230. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15231. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15232. };
  15233. // Dispose
  15234. Mesh.prototype.dispose = function (doNotRecurse) {
  15235. if (this._geometry) {
  15236. this._geometry.releaseForMesh(this, true);
  15237. }
  15238. // Instances
  15239. if (this._worldMatricesInstancesBuffer) {
  15240. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15241. this._worldMatricesInstancesBuffer = null;
  15242. }
  15243. while (this.instances.length) {
  15244. this.instances[0].dispose();
  15245. }
  15246. _super.prototype.dispose.call(this, doNotRecurse);
  15247. };
  15248. // Geometric tools
  15249. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15250. var _this = this;
  15251. var scene = this.getScene();
  15252. var onload = function (img) {
  15253. // Getting height map data
  15254. var canvas = document.createElement("canvas");
  15255. var context = canvas.getContext("2d");
  15256. var heightMapWidth = img.width;
  15257. var heightMapHeight = img.height;
  15258. canvas.width = heightMapWidth;
  15259. canvas.height = heightMapHeight;
  15260. context.drawImage(img, 0, 0);
  15261. // Create VertexData from map data
  15262. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15263. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15264. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15265. //execute success callback, if set
  15266. if (onSuccess) {
  15267. onSuccess(_this);
  15268. }
  15269. };
  15270. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15271. };
  15272. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15273. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15274. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15275. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15276. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15277. return;
  15278. }
  15279. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15280. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15281. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15282. var position = BABYLON.Vector3.Zero();
  15283. var normal = BABYLON.Vector3.Zero();
  15284. var uv = BABYLON.Vector2.Zero();
  15285. for (var index = 0; index < positions.length; index += 3) {
  15286. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15287. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15288. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15289. // Compute height
  15290. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15291. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15292. var pos = (u + v * heightMapWidth) * 4;
  15293. var r = buffer[pos] / 255.0;
  15294. var g = buffer[pos + 1] / 255.0;
  15295. var b = buffer[pos + 2] / 255.0;
  15296. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15297. normal.normalize();
  15298. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15299. position = position.add(normal);
  15300. position.toArray(positions, index);
  15301. }
  15302. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15303. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15304. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15305. };
  15306. Mesh.prototype.convertToFlatShadedMesh = function () {
  15307. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15308. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15309. var kinds = this.getVerticesDataKinds();
  15310. var vbs = [];
  15311. var data = [];
  15312. var newdata = [];
  15313. var updatableNormals = false;
  15314. var kindIndex;
  15315. var kind;
  15316. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15317. kind = kinds[kindIndex];
  15318. var vertexBuffer = this.getVertexBuffer(kind);
  15319. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15320. updatableNormals = vertexBuffer.isUpdatable();
  15321. kinds.splice(kindIndex, 1);
  15322. kindIndex--;
  15323. continue;
  15324. }
  15325. vbs[kind] = vertexBuffer;
  15326. data[kind] = vbs[kind].getData();
  15327. newdata[kind] = [];
  15328. }
  15329. // Save previous submeshes
  15330. var previousSubmeshes = this.subMeshes.slice(0);
  15331. var indices = this.getIndices();
  15332. var totalIndices = this.getTotalIndices();
  15333. // Generating unique vertices per face
  15334. var index;
  15335. for (index = 0; index < totalIndices; index++) {
  15336. var vertexIndex = indices[index];
  15337. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15338. kind = kinds[kindIndex];
  15339. var stride = vbs[kind].getStrideSize();
  15340. for (var offset = 0; offset < stride; offset++) {
  15341. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15342. }
  15343. }
  15344. }
  15345. // Updating faces & normal
  15346. var normals = [];
  15347. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15348. for (index = 0; index < totalIndices; index += 3) {
  15349. indices[index] = index;
  15350. indices[index + 1] = index + 1;
  15351. indices[index + 2] = index + 2;
  15352. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15353. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15354. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15355. var p1p2 = p1.subtract(p2);
  15356. var p3p2 = p3.subtract(p2);
  15357. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15358. // Store same normals for every vertex
  15359. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15360. normals.push(normal.x);
  15361. normals.push(normal.y);
  15362. normals.push(normal.z);
  15363. }
  15364. }
  15365. this.setIndices(indices);
  15366. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15367. // Updating vertex buffers
  15368. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15369. kind = kinds[kindIndex];
  15370. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15371. }
  15372. // Updating submeshes
  15373. this.releaseSubMeshes();
  15374. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15375. var previousOne = previousSubmeshes[submeshIndex];
  15376. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15377. }
  15378. this.synchronizeInstances();
  15379. };
  15380. Mesh.prototype.convertToUnIndexedMesh = function () {
  15381. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15382. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15383. var kinds = this.getVerticesDataKinds();
  15384. var vbs = [];
  15385. var data = [];
  15386. var newdata = [];
  15387. var updatableNormals = false;
  15388. var kindIndex;
  15389. var kind;
  15390. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15391. kind = kinds[kindIndex];
  15392. var vertexBuffer = this.getVertexBuffer(kind);
  15393. vbs[kind] = vertexBuffer;
  15394. data[kind] = vbs[kind].getData();
  15395. newdata[kind] = [];
  15396. }
  15397. // Save previous submeshes
  15398. var previousSubmeshes = this.subMeshes.slice(0);
  15399. var indices = this.getIndices();
  15400. var totalIndices = this.getTotalIndices();
  15401. // Generating unique vertices per face
  15402. var index;
  15403. for (index = 0; index < totalIndices; index++) {
  15404. var vertexIndex = indices[index];
  15405. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15406. kind = kinds[kindIndex];
  15407. var stride = vbs[kind].getStrideSize();
  15408. for (var offset = 0; offset < stride; offset++) {
  15409. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15410. }
  15411. }
  15412. }
  15413. // Updating indices
  15414. for (index = 0; index < totalIndices; index += 3) {
  15415. indices[index] = index;
  15416. indices[index + 1] = index + 1;
  15417. indices[index + 2] = index + 2;
  15418. }
  15419. this.setIndices(indices);
  15420. // Updating vertex buffers
  15421. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15422. kind = kinds[kindIndex];
  15423. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15424. }
  15425. // Updating submeshes
  15426. this.releaseSubMeshes();
  15427. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15428. var previousOne = previousSubmeshes[submeshIndex];
  15429. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15430. }
  15431. this._unIndexed = true;
  15432. this.synchronizeInstances();
  15433. };
  15434. // will inverse faces orientations, and invert normals too if specified
  15435. Mesh.prototype.flipFaces = function (flipNormals) {
  15436. if (flipNormals === void 0) { flipNormals = false; }
  15437. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15438. var i;
  15439. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15440. for (i = 0; i < vertex_data.normals.length; i++) {
  15441. vertex_data.normals[i] *= -1;
  15442. }
  15443. }
  15444. var temp;
  15445. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15446. // reassign indices
  15447. temp = vertex_data.indices[i + 1];
  15448. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15449. vertex_data.indices[i + 2] = temp;
  15450. }
  15451. vertex_data.applyToMesh(this);
  15452. };
  15453. // Instances
  15454. Mesh.prototype.createInstance = function (name) {
  15455. return new BABYLON.InstancedMesh(name, this);
  15456. };
  15457. Mesh.prototype.synchronizeInstances = function () {
  15458. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15459. var instance = this.instances[instanceIndex];
  15460. instance._syncSubMeshes();
  15461. }
  15462. };
  15463. /**
  15464. * Simplify the mesh according to the given array of settings.
  15465. * Function will return immediately and will simplify async.
  15466. * @param settings a collection of simplification settings.
  15467. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15468. * @param type the type of simplification to run.
  15469. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15470. */
  15471. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15472. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15473. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15474. this.getScene().simplificationQueue.addTask({
  15475. settings: settings,
  15476. parallelProcessing: parallelProcessing,
  15477. mesh: this,
  15478. simplificationType: simplificationType,
  15479. successCallback: successCallback
  15480. });
  15481. };
  15482. /**
  15483. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15484. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15485. * This should be used together with the simplification to avoid disappearing triangles.
  15486. * @param successCallback an optional success callback to be called after the optimization finished.
  15487. */
  15488. Mesh.prototype.optimizeIndices = function (successCallback) {
  15489. var _this = this;
  15490. var indices = this.getIndices();
  15491. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15492. var vectorPositions = [];
  15493. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15494. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15495. }
  15496. var dupes = [];
  15497. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15498. var realPos = vectorPositions.length - 1 - iteration;
  15499. var testedPosition = vectorPositions[realPos];
  15500. for (var j = 0; j < realPos; ++j) {
  15501. var againstPosition = vectorPositions[j];
  15502. if (testedPosition.equals(againstPosition)) {
  15503. dupes[realPos] = j;
  15504. break;
  15505. }
  15506. }
  15507. }, function () {
  15508. for (var i = 0; i < indices.length; ++i) {
  15509. indices[i] = dupes[indices[i]] || indices[i];
  15510. }
  15511. //indices are now reordered
  15512. var originalSubMeshes = _this.subMeshes.slice(0);
  15513. _this.setIndices(indices);
  15514. _this.subMeshes = originalSubMeshes;
  15515. if (successCallback) {
  15516. successCallback(_this);
  15517. }
  15518. });
  15519. };
  15520. // Statics
  15521. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15522. var mesh = new Mesh(parsedMesh.name, scene);
  15523. mesh.id = parsedMesh.id;
  15524. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15525. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15526. if (parsedMesh.rotationQuaternion) {
  15527. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15528. }
  15529. else if (parsedMesh.rotation) {
  15530. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15531. }
  15532. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15533. if (parsedMesh.localMatrix) {
  15534. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15535. }
  15536. else if (parsedMesh.pivotMatrix) {
  15537. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15538. }
  15539. mesh.setEnabled(parsedMesh.isEnabled);
  15540. mesh.isVisible = parsedMesh.isVisible;
  15541. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15542. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15543. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15544. if (parsedMesh.applyFog !== undefined) {
  15545. mesh.applyFog = parsedMesh.applyFog;
  15546. }
  15547. if (parsedMesh.pickable !== undefined) {
  15548. mesh.isPickable = parsedMesh.pickable;
  15549. }
  15550. if (parsedMesh.alphaIndex !== undefined) {
  15551. mesh.alphaIndex = parsedMesh.alphaIndex;
  15552. }
  15553. mesh.receiveShadows = parsedMesh.receiveShadows;
  15554. mesh.billboardMode = parsedMesh.billboardMode;
  15555. if (parsedMesh.visibility !== undefined) {
  15556. mesh.visibility = parsedMesh.visibility;
  15557. }
  15558. mesh.checkCollisions = parsedMesh.checkCollisions;
  15559. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15560. // freezeWorldMatrix
  15561. if (parsedMesh.freezeWorldMatrix) {
  15562. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15563. }
  15564. // Parent
  15565. if (parsedMesh.parentId) {
  15566. mesh._waitingParentId = parsedMesh.parentId;
  15567. }
  15568. // Actions
  15569. if (parsedMesh.actions !== undefined) {
  15570. mesh._waitingActions = parsedMesh.actions;
  15571. }
  15572. // Geometry
  15573. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15574. if (parsedMesh.delayLoadingFile) {
  15575. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15576. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15577. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15578. if (parsedMesh._binaryInfo) {
  15579. mesh._binaryInfo = parsedMesh._binaryInfo;
  15580. }
  15581. mesh._delayInfo = [];
  15582. if (parsedMesh.hasUVs) {
  15583. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15584. }
  15585. if (parsedMesh.hasUVs2) {
  15586. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15587. }
  15588. if (parsedMesh.hasUVs3) {
  15589. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15590. }
  15591. if (parsedMesh.hasUVs4) {
  15592. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15593. }
  15594. if (parsedMesh.hasUVs5) {
  15595. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15596. }
  15597. if (parsedMesh.hasUVs6) {
  15598. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15599. }
  15600. if (parsedMesh.hasColors) {
  15601. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15602. }
  15603. if (parsedMesh.hasMatricesIndices) {
  15604. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15605. }
  15606. if (parsedMesh.hasMatricesWeights) {
  15607. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15608. }
  15609. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15610. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15611. mesh._checkDelayState();
  15612. }
  15613. }
  15614. else {
  15615. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15616. }
  15617. // Material
  15618. if (parsedMesh.materialId) {
  15619. mesh.setMaterialByID(parsedMesh.materialId);
  15620. }
  15621. else {
  15622. mesh.material = null;
  15623. }
  15624. // Skeleton
  15625. if (parsedMesh.skeletonId > -1) {
  15626. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15627. if (parsedMesh.numBoneInfluencers) {
  15628. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15629. }
  15630. }
  15631. // Physics
  15632. if (parsedMesh.physicsImpostor) {
  15633. if (!scene.isPhysicsEnabled()) {
  15634. scene.enablePhysics();
  15635. }
  15636. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15637. }
  15638. // Animations
  15639. if (parsedMesh.animations) {
  15640. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15641. var parsedAnimation = parsedMesh.animations[animationIndex];
  15642. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15643. }
  15644. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15645. }
  15646. if (parsedMesh.autoAnimate) {
  15647. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15648. }
  15649. // Layer Mask
  15650. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15651. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15652. }
  15653. else {
  15654. mesh.layerMask = 0x0FFFFFFF;
  15655. }
  15656. // Instances
  15657. if (parsedMesh.instances) {
  15658. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15659. var parsedInstance = parsedMesh.instances[index];
  15660. var instance = mesh.createInstance(parsedInstance.name);
  15661. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15662. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15663. if (parsedInstance.rotationQuaternion) {
  15664. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15665. }
  15666. else if (parsedInstance.rotation) {
  15667. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15668. }
  15669. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15670. instance.checkCollisions = mesh.checkCollisions;
  15671. if (parsedMesh.animations) {
  15672. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15673. parsedAnimation = parsedMesh.animations[animationIndex];
  15674. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15675. }
  15676. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  15677. }
  15678. }
  15679. }
  15680. return mesh;
  15681. };
  15682. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15683. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15684. pathArray: pathArray,
  15685. closeArray: closeArray,
  15686. closePath: closePath,
  15687. offset: offset,
  15688. updatable: updatable,
  15689. sideOrientation: sideOrientation,
  15690. instance: instance
  15691. }, scene);
  15692. };
  15693. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15694. var options = {
  15695. radius: radius,
  15696. tessellation: tessellation,
  15697. sideOrientation: sideOrientation,
  15698. updatable: updatable
  15699. };
  15700. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15701. };
  15702. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15703. var options = {
  15704. size: size,
  15705. sideOrientation: sideOrientation,
  15706. updatable: updatable
  15707. };
  15708. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15709. };
  15710. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15711. var options = {
  15712. segments: segments,
  15713. diameterX: diameter,
  15714. diameterY: diameter,
  15715. diameterZ: diameter,
  15716. sideOrientation: sideOrientation,
  15717. updatable: updatable
  15718. };
  15719. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15720. };
  15721. // Cylinder and cone
  15722. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15723. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15724. if (scene !== undefined) {
  15725. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15726. updatable = scene;
  15727. }
  15728. scene = subdivisions;
  15729. subdivisions = 1;
  15730. }
  15731. var options = {
  15732. height: height,
  15733. diameterTop: diameterTop,
  15734. diameterBottom: diameterBottom,
  15735. tessellation: tessellation,
  15736. subdivisions: subdivisions,
  15737. sideOrientation: sideOrientation,
  15738. updatable: updatable
  15739. };
  15740. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15741. };
  15742. // Torus (Code from SharpDX.org)
  15743. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15744. var options = {
  15745. diameter: diameter,
  15746. thickness: thickness,
  15747. tessellation: tessellation,
  15748. sideOrientation: sideOrientation,
  15749. updatable: updatable
  15750. };
  15751. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15752. };
  15753. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15754. var options = {
  15755. radius: radius,
  15756. tube: tube,
  15757. radialSegments: radialSegments,
  15758. tubularSegments: tubularSegments,
  15759. p: p,
  15760. q: q,
  15761. sideOrientation: sideOrientation,
  15762. updatable: updatable
  15763. };
  15764. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15765. };
  15766. // Lines
  15767. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15768. var options = {
  15769. points: points,
  15770. updatable: updatable,
  15771. instance: instance
  15772. };
  15773. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15774. };
  15775. // Dashed Lines
  15776. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15777. var options = {
  15778. points: points,
  15779. dashSize: dashSize,
  15780. gapSize: gapSize,
  15781. dashNb: dashNb,
  15782. updatable: updatable
  15783. };
  15784. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15785. };
  15786. // Extrusion
  15787. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15788. var options = {
  15789. shape: shape,
  15790. path: path,
  15791. scale: scale,
  15792. rotation: rotation,
  15793. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15794. sideOrientation: sideOrientation,
  15795. instance: instance,
  15796. updatable: updatable
  15797. };
  15798. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15799. };
  15800. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15801. var options = {
  15802. shape: shape,
  15803. path: path,
  15804. scaleFunction: scaleFunction,
  15805. rotationFunction: rotationFunction,
  15806. ribbonCloseArray: ribbonCloseArray,
  15807. ribbonClosePath: ribbonClosePath,
  15808. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15809. sideOrientation: sideOrientation,
  15810. instance: instance,
  15811. updatable: updatable
  15812. };
  15813. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15814. };
  15815. // Lathe
  15816. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15817. var options = {
  15818. shape: shape,
  15819. radius: radius,
  15820. tessellation: tessellation,
  15821. sideOrientation: sideOrientation,
  15822. updatable: updatable
  15823. };
  15824. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15825. };
  15826. // Plane & ground
  15827. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15828. var options = {
  15829. size: size,
  15830. width: size,
  15831. height: size,
  15832. sideOrientation: sideOrientation,
  15833. updatable: updatable
  15834. };
  15835. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15836. };
  15837. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15838. var options = {
  15839. width: width,
  15840. height: height,
  15841. subdivisions: subdivisions,
  15842. updatable: updatable
  15843. };
  15844. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15845. };
  15846. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15847. var options = {
  15848. xmin: xmin,
  15849. zmin: zmin,
  15850. xmax: xmax,
  15851. zmax: zmax,
  15852. subdivisions: subdivisions,
  15853. precision: precision,
  15854. updatable: updatable
  15855. };
  15856. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15857. };
  15858. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15859. var options = {
  15860. width: width,
  15861. height: height,
  15862. subdivisions: subdivisions,
  15863. minHeight: minHeight,
  15864. maxHeight: maxHeight,
  15865. updatable: updatable,
  15866. onReady: onReady
  15867. };
  15868. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15869. };
  15870. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15871. var options = {
  15872. path: path,
  15873. radius: radius,
  15874. tessellation: tessellation,
  15875. radiusFunction: radiusFunction,
  15876. arc: 1,
  15877. cap: cap,
  15878. updatable: updatable,
  15879. sideOrientation: sideOrientation,
  15880. instance: instance
  15881. };
  15882. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15883. };
  15884. Mesh.CreatePolyhedron = function (name, options, scene) {
  15885. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15886. };
  15887. Mesh.CreateIcoSphere = function (name, options, scene) {
  15888. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15889. };
  15890. // Decals
  15891. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15892. var options = {
  15893. position: position,
  15894. normal: normal,
  15895. size: size,
  15896. angle: angle
  15897. };
  15898. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15899. };
  15900. // Skeletons
  15901. /**
  15902. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15903. */
  15904. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15905. var source;
  15906. if (!this._sourcePositions) {
  15907. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15908. this._sourcePositions = new Float32Array(source);
  15909. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15910. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15911. }
  15912. }
  15913. return this._sourcePositions;
  15914. };
  15915. /**
  15916. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15917. */
  15918. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15919. var source;
  15920. if (!this._sourceNormals) {
  15921. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15922. this._sourceNormals = new Float32Array(source);
  15923. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15924. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15925. }
  15926. }
  15927. return this._sourceNormals;
  15928. };
  15929. /**
  15930. * Update the vertex buffers by applying transformation from the bones
  15931. * @param {skeleton} skeleton to apply
  15932. */
  15933. Mesh.prototype.applySkeleton = function (skeleton) {
  15934. if (!this.geometry) {
  15935. return;
  15936. }
  15937. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  15938. return;
  15939. }
  15940. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  15941. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15942. return this;
  15943. }
  15944. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15945. return this;
  15946. }
  15947. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15948. return this;
  15949. }
  15950. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15951. return this;
  15952. }
  15953. if (!this._sourcePositions) {
  15954. this.setPositionsForCPUSkinning();
  15955. }
  15956. if (!this._sourceNormals) {
  15957. this.setNormalsForCPUSkinning();
  15958. }
  15959. // positionsData checks for not being Float32Array will only pass at most once
  15960. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15961. if (!(positionsData instanceof Float32Array)) {
  15962. positionsData = new Float32Array(positionsData);
  15963. }
  15964. // normalsData checks for not being Float32Array will only pass at most once
  15965. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15966. if (!(normalsData instanceof Float32Array)) {
  15967. normalsData = new Float32Array(normalsData);
  15968. }
  15969. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15970. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15971. var needExtras = this.numBoneInfluencers > 4;
  15972. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15973. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15974. var skeletonMatrices = skeleton.getTransformMatrices();
  15975. var tempVector3 = BABYLON.Vector3.Zero();
  15976. var finalMatrix = new BABYLON.Matrix();
  15977. var tempMatrix = new BABYLON.Matrix();
  15978. var matWeightIdx = 0;
  15979. var inf;
  15980. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15981. var weight;
  15982. for (inf = 0; inf < 4; inf++) {
  15983. weight = matricesWeightsData[matWeightIdx + inf];
  15984. if (weight > 0) {
  15985. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15986. finalMatrix.addToSelf(tempMatrix);
  15987. }
  15988. else
  15989. break;
  15990. }
  15991. if (needExtras) {
  15992. for (inf = 0; inf < 4; inf++) {
  15993. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15994. if (weight > 0) {
  15995. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15996. finalMatrix.addToSelf(tempMatrix);
  15997. }
  15998. else
  15999. break;
  16000. }
  16001. }
  16002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16003. tempVector3.toArray(positionsData, index);
  16004. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16005. tempVector3.toArray(normalsData, index);
  16006. finalMatrix.reset();
  16007. }
  16008. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16009. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16010. return this;
  16011. };
  16012. // Tools
  16013. Mesh.MinMax = function (meshes) {
  16014. var minVector = null;
  16015. var maxVector = null;
  16016. for (var i in meshes) {
  16017. var mesh = meshes[i];
  16018. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16019. if (!minVector) {
  16020. minVector = boundingBox.minimumWorld;
  16021. maxVector = boundingBox.maximumWorld;
  16022. continue;
  16023. }
  16024. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16025. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16026. }
  16027. return {
  16028. min: minVector,
  16029. max: maxVector
  16030. };
  16031. };
  16032. Mesh.Center = function (meshesOrMinMaxVector) {
  16033. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16034. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16035. };
  16036. /**
  16037. * Merge the array of meshes into a single mesh for performance reasons.
  16038. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16039. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16040. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16041. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16042. */
  16043. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16044. if (disposeSource === void 0) { disposeSource = true; }
  16045. var index;
  16046. if (!allow32BitsIndices) {
  16047. var totalVertices = 0;
  16048. // Counting vertices
  16049. for (index = 0; index < meshes.length; index++) {
  16050. if (meshes[index]) {
  16051. totalVertices += meshes[index].getTotalVertices();
  16052. if (totalVertices > 65536) {
  16053. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16054. return null;
  16055. }
  16056. }
  16057. }
  16058. }
  16059. // Merge
  16060. var vertexData;
  16061. var otherVertexData;
  16062. var source;
  16063. for (index = 0; index < meshes.length; index++) {
  16064. if (meshes[index]) {
  16065. meshes[index].computeWorldMatrix(true);
  16066. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16067. otherVertexData.transform(meshes[index].getWorldMatrix());
  16068. if (vertexData) {
  16069. vertexData.merge(otherVertexData);
  16070. }
  16071. else {
  16072. vertexData = otherVertexData;
  16073. source = meshes[index];
  16074. }
  16075. }
  16076. }
  16077. if (!meshSubclass) {
  16078. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16079. }
  16080. vertexData.applyToMesh(meshSubclass);
  16081. // Setting properties
  16082. meshSubclass.material = source.material;
  16083. meshSubclass.checkCollisions = source.checkCollisions;
  16084. // Cleaning
  16085. if (disposeSource) {
  16086. for (index = 0; index < meshes.length; index++) {
  16087. if (meshes[index]) {
  16088. meshes[index].dispose();
  16089. }
  16090. }
  16091. }
  16092. return meshSubclass;
  16093. };
  16094. // Consts
  16095. Mesh._FRONTSIDE = 0;
  16096. Mesh._BACKSIDE = 1;
  16097. Mesh._DOUBLESIDE = 2;
  16098. Mesh._DEFAULTSIDE = 0;
  16099. Mesh._NO_CAP = 0;
  16100. Mesh._CAP_START = 1;
  16101. Mesh._CAP_END = 2;
  16102. Mesh._CAP_ALL = 3;
  16103. return Mesh;
  16104. })(BABYLON.AbstractMesh);
  16105. BABYLON.Mesh = Mesh;
  16106. })(BABYLON || (BABYLON = {}));
  16107. var BABYLON;
  16108. (function (BABYLON) {
  16109. var SubMesh = (function () {
  16110. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16111. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16112. this.materialIndex = materialIndex;
  16113. this.verticesStart = verticesStart;
  16114. this.verticesCount = verticesCount;
  16115. this.indexStart = indexStart;
  16116. this.indexCount = indexCount;
  16117. this._renderId = 0;
  16118. this._mesh = mesh;
  16119. this._renderingMesh = renderingMesh || mesh;
  16120. mesh.subMeshes.push(this);
  16121. this._trianglePlanes = [];
  16122. this._id = mesh.subMeshes.length - 1;
  16123. if (createBoundingBox) {
  16124. this.refreshBoundingInfo();
  16125. mesh.computeWorldMatrix(true);
  16126. }
  16127. }
  16128. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16129. get: function () {
  16130. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. SubMesh.prototype.getBoundingInfo = function () {
  16136. if (this.IsGlobal) {
  16137. return this._mesh.getBoundingInfo();
  16138. }
  16139. return this._boundingInfo;
  16140. };
  16141. SubMesh.prototype.getMesh = function () {
  16142. return this._mesh;
  16143. };
  16144. SubMesh.prototype.getRenderingMesh = function () {
  16145. return this._renderingMesh;
  16146. };
  16147. SubMesh.prototype.getMaterial = function () {
  16148. var rootMaterial = this._renderingMesh.material;
  16149. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16150. var multiMaterial = rootMaterial;
  16151. return multiMaterial.getSubMaterial(this.materialIndex);
  16152. }
  16153. if (!rootMaterial) {
  16154. return this._mesh.getScene().defaultMaterial;
  16155. }
  16156. return rootMaterial;
  16157. };
  16158. // Methods
  16159. SubMesh.prototype.refreshBoundingInfo = function () {
  16160. if (this.IsGlobal) {
  16161. return;
  16162. }
  16163. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16164. if (!data) {
  16165. this._boundingInfo = this._mesh._boundingInfo;
  16166. return;
  16167. }
  16168. var indices = this._renderingMesh.getIndices();
  16169. var extend;
  16170. //is this the only submesh?
  16171. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16172. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16173. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16174. }
  16175. else {
  16176. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16177. }
  16178. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16179. };
  16180. SubMesh.prototype._checkCollision = function (collider) {
  16181. return this.getBoundingInfo()._checkCollision(collider);
  16182. };
  16183. SubMesh.prototype.updateBoundingInfo = function (world) {
  16184. if (!this.getBoundingInfo()) {
  16185. this.refreshBoundingInfo();
  16186. }
  16187. this.getBoundingInfo()._update(world);
  16188. };
  16189. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16190. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16191. };
  16192. SubMesh.prototype.render = function (enableAlphaMode) {
  16193. this._renderingMesh.render(this, enableAlphaMode);
  16194. };
  16195. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16196. if (!this._linesIndexBuffer) {
  16197. var linesIndices = [];
  16198. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16199. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16200. }
  16201. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16202. this.linesIndexCount = linesIndices.length;
  16203. }
  16204. return this._linesIndexBuffer;
  16205. };
  16206. SubMesh.prototype.canIntersects = function (ray) {
  16207. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16208. };
  16209. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16210. var intersectInfo = null;
  16211. // Triangles test
  16212. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16213. var p0 = positions[indices[index]];
  16214. var p1 = positions[indices[index + 1]];
  16215. var p2 = positions[indices[index + 2]];
  16216. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16217. if (currentIntersectInfo) {
  16218. if (currentIntersectInfo.distance < 0) {
  16219. continue;
  16220. }
  16221. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16222. intersectInfo = currentIntersectInfo;
  16223. intersectInfo.faceId = index / 3;
  16224. if (fastCheck) {
  16225. break;
  16226. }
  16227. }
  16228. }
  16229. }
  16230. return intersectInfo;
  16231. };
  16232. // Clone
  16233. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16234. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16235. if (!this.IsGlobal) {
  16236. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16237. }
  16238. return result;
  16239. };
  16240. // Dispose
  16241. SubMesh.prototype.dispose = function () {
  16242. if (this._linesIndexBuffer) {
  16243. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16244. this._linesIndexBuffer = null;
  16245. }
  16246. // Remove from mesh
  16247. var index = this._mesh.subMeshes.indexOf(this);
  16248. this._mesh.subMeshes.splice(index, 1);
  16249. };
  16250. // Statics
  16251. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16252. var minVertexIndex = Number.MAX_VALUE;
  16253. var maxVertexIndex = -Number.MAX_VALUE;
  16254. renderingMesh = renderingMesh || mesh;
  16255. var indices = renderingMesh.getIndices();
  16256. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16257. var vertexIndex = indices[index];
  16258. if (vertexIndex < minVertexIndex)
  16259. minVertexIndex = vertexIndex;
  16260. if (vertexIndex > maxVertexIndex)
  16261. maxVertexIndex = vertexIndex;
  16262. }
  16263. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16264. };
  16265. return SubMesh;
  16266. })();
  16267. BABYLON.SubMesh = SubMesh;
  16268. })(BABYLON || (BABYLON = {}));
  16269. var BABYLON;
  16270. (function (BABYLON) {
  16271. var MeshBuilder = (function () {
  16272. function MeshBuilder() {
  16273. }
  16274. MeshBuilder.CreateBox = function (name, options, scene) {
  16275. var box = new BABYLON.Mesh(name, scene);
  16276. var vertexData = BABYLON.VertexData.CreateBox(options);
  16277. vertexData.applyToMesh(box, options.updatable);
  16278. return box;
  16279. };
  16280. MeshBuilder.CreateSphere = function (name, options, scene) {
  16281. var sphere = new BABYLON.Mesh(name, scene);
  16282. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16283. vertexData.applyToMesh(sphere, options.updatable);
  16284. return sphere;
  16285. };
  16286. MeshBuilder.CreateDisc = function (name, options, scene) {
  16287. var disc = new BABYLON.Mesh(name, scene);
  16288. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16289. vertexData.applyToMesh(disc, options.updatable);
  16290. return disc;
  16291. };
  16292. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16293. var sphere = new BABYLON.Mesh(name, scene);
  16294. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16295. vertexData.applyToMesh(sphere, options.updatable);
  16296. return sphere;
  16297. };
  16298. ;
  16299. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16300. var pathArray = options.pathArray;
  16301. var closeArray = options.closeArray;
  16302. var closePath = options.closePath;
  16303. var offset = options.offset;
  16304. var sideOrientation = options.sideOrientation;
  16305. var instance = options.instance;
  16306. var updatable = options.updatable;
  16307. if (instance) {
  16308. // positionFunction : ribbon case
  16309. // only pathArray and sideOrientation parameters are taken into account for positions update
  16310. var positionFunction = function (positions) {
  16311. var minlg = pathArray[0].length;
  16312. var i = 0;
  16313. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16314. for (var si = 1; si <= ns; si++) {
  16315. for (var p = 0; p < pathArray.length; p++) {
  16316. var path = pathArray[p];
  16317. var l = path.length;
  16318. minlg = (minlg < l) ? minlg : l;
  16319. var j = 0;
  16320. while (j < minlg) {
  16321. positions[i] = path[j].x;
  16322. positions[i + 1] = path[j].y;
  16323. positions[i + 2] = path[j].z;
  16324. j++;
  16325. i += 3;
  16326. }
  16327. if (instance._closePath) {
  16328. positions[i] = path[0].x;
  16329. positions[i + 1] = path[0].y;
  16330. positions[i + 2] = path[0].z;
  16331. i += 3;
  16332. }
  16333. }
  16334. }
  16335. };
  16336. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16337. positionFunction(positions);
  16338. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16339. if (!(instance.areNormalsFrozen)) {
  16340. var indices = instance.getIndices();
  16341. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16342. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16343. if (instance._closePath) {
  16344. var indexFirst = 0;
  16345. var indexLast = 0;
  16346. for (var p = 0; p < pathArray.length; p++) {
  16347. indexFirst = instance._idx[p] * 3;
  16348. if (p + 1 < pathArray.length) {
  16349. indexLast = (instance._idx[p + 1] - 1) * 3;
  16350. }
  16351. else {
  16352. indexLast = normals.length - 3;
  16353. }
  16354. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16355. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16356. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16357. normals[indexLast] = normals[indexFirst];
  16358. normals[indexLast + 1] = normals[indexFirst + 1];
  16359. normals[indexLast + 2] = normals[indexFirst + 2];
  16360. }
  16361. }
  16362. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16363. }
  16364. return instance;
  16365. }
  16366. else {
  16367. var ribbon = new BABYLON.Mesh(name, scene);
  16368. ribbon.sideOrientation = sideOrientation;
  16369. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16370. if (closePath) {
  16371. ribbon._idx = vertexData._idx;
  16372. }
  16373. ribbon._closePath = closePath;
  16374. ribbon._closeArray = closeArray;
  16375. vertexData.applyToMesh(ribbon, updatable);
  16376. return ribbon;
  16377. }
  16378. };
  16379. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16380. var cylinder = new BABYLON.Mesh(name, scene);
  16381. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16382. vertexData.applyToMesh(cylinder, options.updatable);
  16383. return cylinder;
  16384. };
  16385. MeshBuilder.CreateTorus = function (name, options, scene) {
  16386. var torus = new BABYLON.Mesh(name, scene);
  16387. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16388. vertexData.applyToMesh(torus, options.updatable);
  16389. return torus;
  16390. };
  16391. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16392. var torusKnot = new BABYLON.Mesh(name, scene);
  16393. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16394. vertexData.applyToMesh(torusKnot, options.updatable);
  16395. return torusKnot;
  16396. };
  16397. MeshBuilder.CreateLines = function (name, options, scene) {
  16398. var instance = options.instance;
  16399. var points = options.points;
  16400. if (instance) {
  16401. var positionFunction = function (positions) {
  16402. var i = 0;
  16403. for (var p = 0; p < points.length; p++) {
  16404. positions[i] = points[p].x;
  16405. positions[i + 1] = points[p].y;
  16406. positions[i + 2] = points[p].z;
  16407. i += 3;
  16408. }
  16409. };
  16410. instance.updateMeshPositions(positionFunction, false);
  16411. return instance;
  16412. }
  16413. // lines creation
  16414. var lines = new BABYLON.LinesMesh(name, scene);
  16415. var vertexData = BABYLON.VertexData.CreateLines(options);
  16416. vertexData.applyToMesh(lines, options.updatable);
  16417. return lines;
  16418. };
  16419. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16420. var points = options.points;
  16421. var instance = options.instance;
  16422. var gapSize = options.gapSize;
  16423. var dashNb = options.dashNb;
  16424. var dashSize = options.dashSize;
  16425. if (instance) {
  16426. var positionFunction = function (positions) {
  16427. var curvect = BABYLON.Vector3.Zero();
  16428. var nbSeg = positions.length / 6;
  16429. var lg = 0;
  16430. var nb = 0;
  16431. var shft = 0;
  16432. var dashshft = 0;
  16433. var curshft = 0;
  16434. var p = 0;
  16435. var i = 0;
  16436. var j = 0;
  16437. for (i = 0; i < points.length - 1; i++) {
  16438. points[i + 1].subtractToRef(points[i], curvect);
  16439. lg += curvect.length();
  16440. }
  16441. shft = lg / nbSeg;
  16442. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16443. for (i = 0; i < points.length - 1; i++) {
  16444. points[i + 1].subtractToRef(points[i], curvect);
  16445. nb = Math.floor(curvect.length() / shft);
  16446. curvect.normalize();
  16447. j = 0;
  16448. while (j < nb && p < positions.length) {
  16449. curshft = shft * j;
  16450. positions[p] = points[i].x + curshft * curvect.x;
  16451. positions[p + 1] = points[i].y + curshft * curvect.y;
  16452. positions[p + 2] = points[i].z + curshft * curvect.z;
  16453. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16454. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16455. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16456. p += 6;
  16457. j++;
  16458. }
  16459. }
  16460. while (p < positions.length) {
  16461. positions[p] = points[i].x;
  16462. positions[p + 1] = points[i].y;
  16463. positions[p + 2] = points[i].z;
  16464. p += 3;
  16465. }
  16466. };
  16467. instance.updateMeshPositions(positionFunction, false);
  16468. return instance;
  16469. }
  16470. // dashed lines creation
  16471. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16472. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16473. vertexData.applyToMesh(dashedLines, options.updatable);
  16474. dashedLines.dashSize = dashSize;
  16475. dashedLines.gapSize = gapSize;
  16476. return dashedLines;
  16477. };
  16478. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16479. var path = options.path;
  16480. var shape = options.shape;
  16481. var scale = options.scale || 1;
  16482. var rotation = options.rotation || 0;
  16483. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16484. var updatable = options.updatable;
  16485. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16486. var instance = options.instance;
  16487. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16488. };
  16489. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16490. var path = options.path;
  16491. var shape = options.shape;
  16492. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16493. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16494. var ribbonCloseArray = options.ribbonCloseArray || false;
  16495. var ribbonClosePath = options.ribbonClosePath || false;
  16496. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16497. var updatable = options.updatable;
  16498. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16499. var instance = options.instance;
  16500. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16501. };
  16502. MeshBuilder.CreateLathe = function (name, options, scene) {
  16503. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16504. var closed = (options.closed === undefined) ? true : options.closed;
  16505. var shape = options.shape;
  16506. var radius = options.radius || 1;
  16507. var tessellation = options.tessellation || 64;
  16508. var updatable = options.updatable;
  16509. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16510. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16511. var pi2 = Math.PI * 2;
  16512. var paths = new Array();
  16513. var i = 0;
  16514. var p = 0;
  16515. var step = pi2 / tessellation * arc;
  16516. var rotated;
  16517. var path = new Array();
  16518. ;
  16519. for (i = 0; i <= tessellation; i++) {
  16520. var path = [];
  16521. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16522. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16523. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16524. }
  16525. for (p = 0; p < shape.length; p++) {
  16526. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16527. path.push(rotated);
  16528. }
  16529. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16530. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  16531. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16532. }
  16533. paths.push(path);
  16534. }
  16535. // lathe ribbon
  16536. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16537. return lathe;
  16538. };
  16539. MeshBuilder.CreatePlane = function (name, options, scene) {
  16540. var plane = new BABYLON.Mesh(name, scene);
  16541. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16542. vertexData.applyToMesh(plane, options.updatable);
  16543. if (options.sourcePlane) {
  16544. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16545. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16546. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16547. plane.rotate(vectorProduct, product);
  16548. }
  16549. return plane;
  16550. };
  16551. MeshBuilder.CreateGround = function (name, options, scene) {
  16552. var ground = new BABYLON.GroundMesh(name, scene);
  16553. ground._setReady(false);
  16554. ground._subdivisions = options.subdivisions || 1;
  16555. ground._width = options.width || 1;
  16556. ground._height = options.height || 1;
  16557. ground._maxX = ground._width / 2;
  16558. ground._maxZ = ground._height / 2;
  16559. ground._minX = -ground._maxX;
  16560. ground._minZ = -ground._maxZ;
  16561. var vertexData = BABYLON.VertexData.CreateGround(options);
  16562. vertexData.applyToMesh(ground, options.updatable);
  16563. ground._setReady(true);
  16564. return ground;
  16565. };
  16566. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16567. var tiledGround = new BABYLON.Mesh(name, scene);
  16568. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16569. vertexData.applyToMesh(tiledGround, options.updatable);
  16570. return tiledGround;
  16571. };
  16572. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16573. var width = options.width || 10;
  16574. var height = options.height || 10;
  16575. var subdivisions = options.subdivisions || 1;
  16576. var minHeight = options.minHeight;
  16577. var maxHeight = options.maxHeight || 10;
  16578. var updatable = options.updatable;
  16579. var onReady = options.onReady;
  16580. var ground = new BABYLON.GroundMesh(name, scene);
  16581. ground._subdivisions = subdivisions;
  16582. ground._width = width;
  16583. ground._height = height;
  16584. ground._maxX = ground._width / 2;
  16585. ground._maxZ = ground._height / 2;
  16586. ground._minX = -ground._maxX;
  16587. ground._minZ = -ground._maxZ;
  16588. ground._setReady(false);
  16589. var onload = function (img) {
  16590. // Getting height map data
  16591. var canvas = document.createElement("canvas");
  16592. var context = canvas.getContext("2d");
  16593. var bufferWidth = img.width;
  16594. var bufferHeight = img.height;
  16595. canvas.width = bufferWidth;
  16596. canvas.height = bufferHeight;
  16597. context.drawImage(img, 0, 0);
  16598. // Create VertexData from map data
  16599. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16600. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16601. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16602. width: width, height: height,
  16603. subdivisions: subdivisions,
  16604. minHeight: minHeight, maxHeight: maxHeight,
  16605. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16606. });
  16607. vertexData.applyToMesh(ground, updatable);
  16608. ground._setReady(true);
  16609. //execute ready callback, if set
  16610. if (onReady) {
  16611. onReady(ground);
  16612. }
  16613. };
  16614. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16615. return ground;
  16616. };
  16617. MeshBuilder.CreateTube = function (name, options, scene) {
  16618. var path = options.path;
  16619. var radius = options.radius || 1;
  16620. var tessellation = options.tessellation || 64;
  16621. var radiusFunction = options.radiusFunction;
  16622. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16623. var updatable = options.updatable;
  16624. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16625. var instance = options.instance;
  16626. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16627. // tube geometry
  16628. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16629. var tangents = path3D.getTangents();
  16630. var normals = path3D.getNormals();
  16631. var distances = path3D.getDistances();
  16632. var pi2 = Math.PI * 2;
  16633. var step = pi2 / tessellation * arc;
  16634. var returnRadius = function () { return radius; };
  16635. var radiusFunctionFinal = radiusFunction || returnRadius;
  16636. var circlePath;
  16637. var rad;
  16638. var normal;
  16639. var rotated;
  16640. var rotationMatrix = BABYLON.Matrix.Zero();
  16641. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16642. for (var i = 0; i < path.length; i++) {
  16643. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16644. circlePath = Array(); // current circle array
  16645. normal = normals[i]; // current normal
  16646. for (var t = 0; t < tessellation; t++) {
  16647. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16648. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16649. circlePath.push(rotated);
  16650. }
  16651. circlePaths[index] = circlePath;
  16652. index++;
  16653. }
  16654. // cap
  16655. var capPath = function (nbPoints, pathIndex) {
  16656. var pointCap = Array();
  16657. for (var i = 0; i < nbPoints; i++) {
  16658. pointCap.push(path[pathIndex]);
  16659. }
  16660. return pointCap;
  16661. };
  16662. switch (cap) {
  16663. case BABYLON.Mesh.NO_CAP:
  16664. break;
  16665. case BABYLON.Mesh.CAP_START:
  16666. circlePaths[0] = capPath(tessellation, 0);
  16667. circlePaths[1] = circlePaths[2].slice(0);
  16668. break;
  16669. case BABYLON.Mesh.CAP_END:
  16670. circlePaths[index] = circlePaths[index - 1].slice(0);
  16671. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16672. break;
  16673. case BABYLON.Mesh.CAP_ALL:
  16674. circlePaths[0] = capPath(tessellation, 0);
  16675. circlePaths[1] = circlePaths[2].slice(0);
  16676. circlePaths[index] = circlePaths[index - 1].slice(0);
  16677. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16678. break;
  16679. default:
  16680. break;
  16681. }
  16682. return circlePaths;
  16683. };
  16684. var path3D;
  16685. var pathArray;
  16686. if (instance) {
  16687. var arc = options.arc || instance.arc;
  16688. path3D = (instance.path3D).update(path);
  16689. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16690. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16691. instance.path3D = path3D;
  16692. instance.pathArray = pathArray;
  16693. instance.arc = arc;
  16694. return instance;
  16695. }
  16696. // tube creation
  16697. path3D = new BABYLON.Path3D(path);
  16698. var newPathArray = new Array();
  16699. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16700. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16701. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16702. tube.pathArray = pathArray;
  16703. tube.path3D = path3D;
  16704. tube.tessellation = tessellation;
  16705. tube.cap = cap;
  16706. tube.arc = options.arc;
  16707. return tube;
  16708. };
  16709. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16710. var polyhedron = new BABYLON.Mesh(name, scene);
  16711. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16712. vertexData.applyToMesh(polyhedron, options.updatable);
  16713. return polyhedron;
  16714. };
  16715. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16716. var indices = sourceMesh.getIndices();
  16717. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16718. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16719. var position = options.position || BABYLON.Vector3.Zero();
  16720. var normal = options.normal || BABYLON.Vector3.Up();
  16721. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16722. var angle = options.angle || 0;
  16723. // Getting correct rotation
  16724. if (!normal) {
  16725. var target = new BABYLON.Vector3(0, 0, 1);
  16726. var camera = sourceMesh.getScene().activeCamera;
  16727. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16728. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16729. }
  16730. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16731. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16732. var pitch = Math.atan2(normal.y, len);
  16733. // Matrix
  16734. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16735. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16736. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16737. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16738. var vertexData = new BABYLON.VertexData();
  16739. vertexData.indices = [];
  16740. vertexData.positions = [];
  16741. vertexData.normals = [];
  16742. vertexData.uvs = [];
  16743. var currentVertexDataIndex = 0;
  16744. var extractDecalVector3 = function (indexId) {
  16745. var vertexId = indices[indexId];
  16746. var result = new BABYLON.PositionNormalVertex();
  16747. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16748. // Send vector to decal local world
  16749. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16750. // Get normal
  16751. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16752. return result;
  16753. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16754. var clip = function (vertices, axis) {
  16755. if (vertices.length === 0) {
  16756. return vertices;
  16757. }
  16758. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16759. var clipVertices = function (v0, v1) {
  16760. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16761. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16762. };
  16763. var result = new Array();
  16764. for (var index = 0; index < vertices.length; index += 3) {
  16765. var v1Out;
  16766. var v2Out;
  16767. var v3Out;
  16768. var total = 0;
  16769. var nV1, nV2, nV3, nV4;
  16770. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16771. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16772. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16773. v1Out = d1 > 0;
  16774. v2Out = d2 > 0;
  16775. v3Out = d3 > 0;
  16776. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16777. switch (total) {
  16778. case 0:
  16779. result.push(vertices[index]);
  16780. result.push(vertices[index + 1]);
  16781. result.push(vertices[index + 2]);
  16782. break;
  16783. case 1:
  16784. if (v1Out) {
  16785. nV1 = vertices[index + 1];
  16786. nV2 = vertices[index + 2];
  16787. nV3 = clipVertices(vertices[index], nV1);
  16788. nV4 = clipVertices(vertices[index], nV2);
  16789. }
  16790. if (v2Out) {
  16791. nV1 = vertices[index];
  16792. nV2 = vertices[index + 2];
  16793. nV3 = clipVertices(vertices[index + 1], nV1);
  16794. nV4 = clipVertices(vertices[index + 1], nV2);
  16795. result.push(nV3);
  16796. result.push(nV2.clone());
  16797. result.push(nV1.clone());
  16798. result.push(nV2.clone());
  16799. result.push(nV3.clone());
  16800. result.push(nV4);
  16801. break;
  16802. }
  16803. if (v3Out) {
  16804. nV1 = vertices[index];
  16805. nV2 = vertices[index + 1];
  16806. nV3 = clipVertices(vertices[index + 2], nV1);
  16807. nV4 = clipVertices(vertices[index + 2], nV2);
  16808. }
  16809. result.push(nV1.clone());
  16810. result.push(nV2.clone());
  16811. result.push(nV3);
  16812. result.push(nV4);
  16813. result.push(nV3.clone());
  16814. result.push(nV2.clone());
  16815. break;
  16816. case 2:
  16817. if (!v1Out) {
  16818. nV1 = vertices[index].clone();
  16819. nV2 = clipVertices(nV1, vertices[index + 1]);
  16820. nV3 = clipVertices(nV1, vertices[index + 2]);
  16821. result.push(nV1);
  16822. result.push(nV2);
  16823. result.push(nV3);
  16824. }
  16825. if (!v2Out) {
  16826. nV1 = vertices[index + 1].clone();
  16827. nV2 = clipVertices(nV1, vertices[index + 2]);
  16828. nV3 = clipVertices(nV1, vertices[index]);
  16829. result.push(nV1);
  16830. result.push(nV2);
  16831. result.push(nV3);
  16832. }
  16833. if (!v3Out) {
  16834. nV1 = vertices[index + 2].clone();
  16835. nV2 = clipVertices(nV1, vertices[index]);
  16836. nV3 = clipVertices(nV1, vertices[index + 1]);
  16837. result.push(nV1);
  16838. result.push(nV2);
  16839. result.push(nV3);
  16840. }
  16841. break;
  16842. case 3:
  16843. break;
  16844. }
  16845. }
  16846. return result;
  16847. };
  16848. for (var index = 0; index < indices.length; index += 3) {
  16849. var faceVertices = new Array();
  16850. faceVertices.push(extractDecalVector3(index));
  16851. faceVertices.push(extractDecalVector3(index + 1));
  16852. faceVertices.push(extractDecalVector3(index + 2));
  16853. // Clip
  16854. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16855. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16856. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16857. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16858. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16859. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16860. if (faceVertices.length === 0) {
  16861. continue;
  16862. }
  16863. // Add UVs and get back to world
  16864. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16865. var vertex = faceVertices[vIndex];
  16866. //TODO check for Int32Array
  16867. vertexData.indices.push(currentVertexDataIndex);
  16868. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16869. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16870. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16871. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16872. currentVertexDataIndex++;
  16873. }
  16874. }
  16875. // Return mesh
  16876. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16877. vertexData.applyToMesh(decal);
  16878. decal.position = position.clone();
  16879. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16880. return decal;
  16881. };
  16882. // Privates
  16883. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16884. // extrusion geometry
  16885. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16886. var tangents = path3D.getTangents();
  16887. var normals = path3D.getNormals();
  16888. var binormals = path3D.getBinormals();
  16889. var distances = path3D.getDistances();
  16890. var angle = 0;
  16891. var returnScale = function () { return scale; };
  16892. var returnRotation = function () { return rotation; };
  16893. var rotate = custom ? rotateFunction : returnRotation;
  16894. var scl = custom ? scaleFunction : returnScale;
  16895. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16896. var rotationMatrix = BABYLON.Matrix.Zero();
  16897. for (var i = 0; i < curve.length; i++) {
  16898. var shapePath = new Array();
  16899. var angleStep = rotate(i, distances[i]);
  16900. var scaleRatio = scl(i, distances[i]);
  16901. for (var p = 0; p < shape.length; p++) {
  16902. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16903. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16904. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16905. shapePath.push(rotated);
  16906. }
  16907. shapePaths[index] = shapePath;
  16908. angle += angleStep;
  16909. index++;
  16910. }
  16911. // cap
  16912. var capPath = function (shapePath) {
  16913. var pointCap = Array();
  16914. var barycenter = BABYLON.Vector3.Zero();
  16915. var i;
  16916. for (i = 0; i < shapePath.length; i++) {
  16917. barycenter.addInPlace(shapePath[i]);
  16918. }
  16919. barycenter.scaleInPlace(1 / shapePath.length);
  16920. for (i = 0; i < shapePath.length; i++) {
  16921. pointCap.push(barycenter);
  16922. }
  16923. return pointCap;
  16924. };
  16925. switch (cap) {
  16926. case BABYLON.Mesh.NO_CAP:
  16927. break;
  16928. case BABYLON.Mesh.CAP_START:
  16929. shapePaths[0] = capPath(shapePaths[2]);
  16930. shapePaths[1] = shapePaths[2].slice(0);
  16931. break;
  16932. case BABYLON.Mesh.CAP_END:
  16933. shapePaths[index] = shapePaths[index - 1];
  16934. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16935. break;
  16936. case BABYLON.Mesh.CAP_ALL:
  16937. shapePaths[0] = capPath(shapePaths[2]);
  16938. shapePaths[1] = shapePaths[2].slice(0);
  16939. shapePaths[index] = shapePaths[index - 1];
  16940. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16941. break;
  16942. default:
  16943. break;
  16944. }
  16945. return shapePaths;
  16946. };
  16947. var path3D;
  16948. var pathArray;
  16949. if (instance) {
  16950. path3D = (instance.path3D).update(curve);
  16951. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16952. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16953. return instance;
  16954. }
  16955. // extruded shape creation
  16956. path3D = new BABYLON.Path3D(curve);
  16957. var newShapePaths = new Array();
  16958. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16959. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16960. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16961. extrudedGeneric.pathArray = pathArray;
  16962. extrudedGeneric.path3D = path3D;
  16963. extrudedGeneric.cap = cap;
  16964. return extrudedGeneric;
  16965. };
  16966. return MeshBuilder;
  16967. })();
  16968. BABYLON.MeshBuilder = MeshBuilder;
  16969. })(BABYLON || (BABYLON = {}));
  16970. var BABYLON;
  16971. (function (BABYLON) {
  16972. var BaseTexture = (function () {
  16973. function BaseTexture(scene) {
  16974. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16975. this.hasAlpha = false;
  16976. this.getAlphaFromRGB = false;
  16977. this.level = 1;
  16978. this.isCube = false;
  16979. this.isRenderTarget = false;
  16980. this.animations = new Array();
  16981. this.coordinatesIndex = 0;
  16982. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16983. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16984. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16985. this.anisotropicFilteringLevel = 4;
  16986. this._scene = scene;
  16987. this._scene.textures.push(this);
  16988. }
  16989. BaseTexture.prototype.getScene = function () {
  16990. return this._scene;
  16991. };
  16992. BaseTexture.prototype.getTextureMatrix = function () {
  16993. return null;
  16994. };
  16995. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16996. return null;
  16997. };
  16998. BaseTexture.prototype.getInternalTexture = function () {
  16999. return this._texture;
  17000. };
  17001. BaseTexture.prototype.isReady = function () {
  17002. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17003. return true;
  17004. }
  17005. if (this._texture) {
  17006. return this._texture.isReady;
  17007. }
  17008. return false;
  17009. };
  17010. BaseTexture.prototype.getSize = function () {
  17011. if (this._texture._width) {
  17012. return { width: this._texture._width, height: this._texture._height };
  17013. }
  17014. if (this._texture._size) {
  17015. return { width: this._texture._size, height: this._texture._size };
  17016. }
  17017. return { width: 0, height: 0 };
  17018. };
  17019. BaseTexture.prototype.getBaseSize = function () {
  17020. if (!this.isReady())
  17021. return { width: 0, height: 0 };
  17022. if (this._texture._size) {
  17023. return { width: this._texture._size, height: this._texture._size };
  17024. }
  17025. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17026. };
  17027. BaseTexture.prototype.scale = function (ratio) {
  17028. };
  17029. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17030. get: function () {
  17031. return false;
  17032. },
  17033. enumerable: true,
  17034. configurable: true
  17035. });
  17036. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17037. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17038. for (var index = 0; index < texturesCache.length; index++) {
  17039. var texturesCacheEntry = texturesCache[index];
  17040. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17041. texturesCache.splice(index, 1);
  17042. return;
  17043. }
  17044. }
  17045. };
  17046. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17047. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17048. for (var index = 0; index < texturesCache.length; index++) {
  17049. var texturesCacheEntry = texturesCache[index];
  17050. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17051. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17052. texturesCacheEntry.references++;
  17053. return texturesCacheEntry;
  17054. }
  17055. }
  17056. }
  17057. return null;
  17058. };
  17059. BaseTexture.prototype.delayLoad = function () {
  17060. };
  17061. BaseTexture.prototype.clone = function () {
  17062. return null;
  17063. };
  17064. BaseTexture.prototype.releaseInternalTexture = function () {
  17065. if (this._texture) {
  17066. this._scene.getEngine().releaseInternalTexture(this._texture);
  17067. delete this._texture;
  17068. }
  17069. };
  17070. BaseTexture.prototype.dispose = function () {
  17071. // Animations
  17072. this.getScene().stopAnimation(this);
  17073. // Remove from scene
  17074. var index = this._scene.textures.indexOf(this);
  17075. if (index >= 0) {
  17076. this._scene.textures.splice(index, 1);
  17077. }
  17078. if (this._texture === undefined) {
  17079. return;
  17080. }
  17081. // Release
  17082. this.releaseInternalTexture();
  17083. // Callback
  17084. if (this.onDispose) {
  17085. this.onDispose();
  17086. }
  17087. };
  17088. BaseTexture.prototype.serialize = function () {
  17089. var serializationObject = {};
  17090. if (!this.name) {
  17091. return null;
  17092. }
  17093. serializationObject.name = this.name;
  17094. serializationObject.hasAlpha = this.hasAlpha;
  17095. serializationObject.level = this.level;
  17096. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17097. serializationObject.coordinatesMode = this.coordinatesMode;
  17098. serializationObject.wrapU = this.wrapU;
  17099. serializationObject.wrapV = this.wrapV;
  17100. // Animations
  17101. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17102. return serializationObject;
  17103. };
  17104. return BaseTexture;
  17105. })();
  17106. BABYLON.BaseTexture = BaseTexture;
  17107. })(BABYLON || (BABYLON = {}));
  17108. var BABYLON;
  17109. (function (BABYLON) {
  17110. var Texture = (function (_super) {
  17111. __extends(Texture, _super);
  17112. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17113. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17114. if (onLoad === void 0) { onLoad = null; }
  17115. if (onError === void 0) { onError = null; }
  17116. if (buffer === void 0) { buffer = null; }
  17117. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17118. _super.call(this, scene);
  17119. this.uOffset = 0;
  17120. this.vOffset = 0;
  17121. this.uScale = 1.0;
  17122. this.vScale = 1.0;
  17123. this.uAng = 0;
  17124. this.vAng = 0;
  17125. this.wAng = 0;
  17126. this.name = url;
  17127. this.url = url;
  17128. this._noMipmap = noMipmap;
  17129. this._invertY = invertY;
  17130. this._samplingMode = samplingMode;
  17131. this._buffer = buffer;
  17132. this._deleteBuffer = deleteBuffer;
  17133. if (!url) {
  17134. return;
  17135. }
  17136. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17137. if (!this._texture) {
  17138. if (!scene.useDelayedTextureLoading) {
  17139. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17140. if (deleteBuffer) {
  17141. delete this._buffer;
  17142. }
  17143. }
  17144. else {
  17145. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17146. }
  17147. }
  17148. else {
  17149. BABYLON.Tools.SetImmediate(function () {
  17150. if (onLoad) {
  17151. onLoad();
  17152. }
  17153. });
  17154. }
  17155. }
  17156. Texture.prototype.delayLoad = function () {
  17157. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17158. return;
  17159. }
  17160. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17161. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17162. if (!this._texture) {
  17163. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17164. if (this._deleteBuffer) {
  17165. delete this._buffer;
  17166. }
  17167. }
  17168. };
  17169. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17170. if (!this._texture) {
  17171. return;
  17172. }
  17173. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17174. };
  17175. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17176. x *= this.uScale;
  17177. y *= this.vScale;
  17178. x -= 0.5 * this.uScale;
  17179. y -= 0.5 * this.vScale;
  17180. z -= 0.5;
  17181. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17182. t.x += 0.5 * this.uScale + this.uOffset;
  17183. t.y += 0.5 * this.vScale + this.vOffset;
  17184. t.z += 0.5;
  17185. };
  17186. Texture.prototype.getTextureMatrix = function () {
  17187. if (this.uOffset === this._cachedUOffset &&
  17188. this.vOffset === this._cachedVOffset &&
  17189. this.uScale === this._cachedUScale &&
  17190. this.vScale === this._cachedVScale &&
  17191. this.uAng === this._cachedUAng &&
  17192. this.vAng === this._cachedVAng &&
  17193. this.wAng === this._cachedWAng) {
  17194. return this._cachedTextureMatrix;
  17195. }
  17196. this._cachedUOffset = this.uOffset;
  17197. this._cachedVOffset = this.vOffset;
  17198. this._cachedUScale = this.uScale;
  17199. this._cachedVScale = this.vScale;
  17200. this._cachedUAng = this.uAng;
  17201. this._cachedVAng = this.vAng;
  17202. this._cachedWAng = this.wAng;
  17203. if (!this._cachedTextureMatrix) {
  17204. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17205. this._rowGenerationMatrix = new BABYLON.Matrix();
  17206. this._t0 = BABYLON.Vector3.Zero();
  17207. this._t1 = BABYLON.Vector3.Zero();
  17208. this._t2 = BABYLON.Vector3.Zero();
  17209. }
  17210. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17211. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17212. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17213. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17214. this._t1.subtractInPlace(this._t0);
  17215. this._t2.subtractInPlace(this._t0);
  17216. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17217. this._cachedTextureMatrix.m[0] = this._t1.x;
  17218. this._cachedTextureMatrix.m[1] = this._t1.y;
  17219. this._cachedTextureMatrix.m[2] = this._t1.z;
  17220. this._cachedTextureMatrix.m[4] = this._t2.x;
  17221. this._cachedTextureMatrix.m[5] = this._t2.y;
  17222. this._cachedTextureMatrix.m[6] = this._t2.z;
  17223. this._cachedTextureMatrix.m[8] = this._t0.x;
  17224. this._cachedTextureMatrix.m[9] = this._t0.y;
  17225. this._cachedTextureMatrix.m[10] = this._t0.z;
  17226. return this._cachedTextureMatrix;
  17227. };
  17228. Texture.prototype.getReflectionTextureMatrix = function () {
  17229. if (this.uOffset === this._cachedUOffset &&
  17230. this.vOffset === this._cachedVOffset &&
  17231. this.uScale === this._cachedUScale &&
  17232. this.vScale === this._cachedVScale &&
  17233. this.coordinatesMode === this._cachedCoordinatesMode) {
  17234. return this._cachedTextureMatrix;
  17235. }
  17236. if (!this._cachedTextureMatrix) {
  17237. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17238. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17239. }
  17240. this._cachedCoordinatesMode = this.coordinatesMode;
  17241. switch (this.coordinatesMode) {
  17242. case Texture.PLANAR_MODE:
  17243. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17244. this._cachedTextureMatrix[0] = this.uScale;
  17245. this._cachedTextureMatrix[5] = this.vScale;
  17246. this._cachedTextureMatrix[12] = this.uOffset;
  17247. this._cachedTextureMatrix[13] = this.vOffset;
  17248. break;
  17249. case Texture.PROJECTION_MODE:
  17250. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17251. this._projectionModeMatrix.m[0] = 0.5;
  17252. this._projectionModeMatrix.m[5] = -0.5;
  17253. this._projectionModeMatrix.m[10] = 0.0;
  17254. this._projectionModeMatrix.m[12] = 0.5;
  17255. this._projectionModeMatrix.m[13] = 0.5;
  17256. this._projectionModeMatrix.m[14] = 1.0;
  17257. this._projectionModeMatrix.m[15] = 1.0;
  17258. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17259. break;
  17260. default:
  17261. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17262. break;
  17263. }
  17264. return this._cachedTextureMatrix;
  17265. };
  17266. Texture.prototype.clone = function () {
  17267. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17268. // Base texture
  17269. newTexture.hasAlpha = this.hasAlpha;
  17270. newTexture.level = this.level;
  17271. newTexture.wrapU = this.wrapU;
  17272. newTexture.wrapV = this.wrapV;
  17273. newTexture.coordinatesIndex = this.coordinatesIndex;
  17274. newTexture.coordinatesMode = this.coordinatesMode;
  17275. // Texture
  17276. newTexture.uOffset = this.uOffset;
  17277. newTexture.vOffset = this.vOffset;
  17278. newTexture.uScale = this.uScale;
  17279. newTexture.vScale = this.vScale;
  17280. newTexture.uAng = this.uAng;
  17281. newTexture.vAng = this.vAng;
  17282. newTexture.wAng = this.wAng;
  17283. return newTexture;
  17284. };
  17285. Texture.prototype.serialize = function () {
  17286. if (!this.name) {
  17287. return null;
  17288. }
  17289. var serializationObject = _super.prototype.serialize.call(this);
  17290. serializationObject.uOffset = this.uOffset;
  17291. serializationObject.vOffset = this.vOffset;
  17292. serializationObject.uScale = this.uScale;
  17293. serializationObject.vScale = this.vScale;
  17294. serializationObject.uAng = this.uAng;
  17295. serializationObject.vAng = this.vAng;
  17296. serializationObject.wAng = this.wAng;
  17297. return serializationObject;
  17298. };
  17299. // Statics
  17300. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17301. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17302. if (onLoad === void 0) { onLoad = null; }
  17303. if (onError === void 0) { onError = null; }
  17304. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17305. };
  17306. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17307. if (parsedTexture.isCube) {
  17308. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17309. }
  17310. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17311. return null;
  17312. }
  17313. var texture;
  17314. if (parsedTexture.mirrorPlane) {
  17315. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17316. texture._waitingRenderList = parsedTexture.renderList;
  17317. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17318. }
  17319. else if (parsedTexture.isRenderTarget) {
  17320. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17321. texture._waitingRenderList = parsedTexture.renderList;
  17322. }
  17323. else {
  17324. if (parsedTexture.base64String) {
  17325. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17326. }
  17327. else {
  17328. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17329. }
  17330. }
  17331. texture.name = parsedTexture.name;
  17332. texture.hasAlpha = parsedTexture.hasAlpha;
  17333. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17334. texture.level = parsedTexture.level;
  17335. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17336. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17337. texture.uOffset = parsedTexture.uOffset;
  17338. texture.vOffset = parsedTexture.vOffset;
  17339. texture.uScale = parsedTexture.uScale;
  17340. texture.vScale = parsedTexture.vScale;
  17341. texture.uAng = parsedTexture.uAng;
  17342. texture.vAng = parsedTexture.vAng;
  17343. texture.wAng = parsedTexture.wAng;
  17344. texture.wrapU = parsedTexture.wrapU;
  17345. texture.wrapV = parsedTexture.wrapV;
  17346. // Animations
  17347. if (parsedTexture.animations) {
  17348. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17349. var parsedAnimation = parsedTexture.animations[animationIndex];
  17350. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17351. }
  17352. }
  17353. return texture;
  17354. };
  17355. // Constants
  17356. Texture.NEAREST_SAMPLINGMODE = 1;
  17357. Texture.BILINEAR_SAMPLINGMODE = 2;
  17358. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17359. Texture.EXPLICIT_MODE = 0;
  17360. Texture.SPHERICAL_MODE = 1;
  17361. Texture.PLANAR_MODE = 2;
  17362. Texture.CUBIC_MODE = 3;
  17363. Texture.PROJECTION_MODE = 4;
  17364. Texture.SKYBOX_MODE = 5;
  17365. Texture.INVCUBIC_MODE = 6;
  17366. Texture.EQUIRECTANGULAR_MODE = 7;
  17367. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17368. Texture.CLAMP_ADDRESSMODE = 0;
  17369. Texture.WRAP_ADDRESSMODE = 1;
  17370. Texture.MIRROR_ADDRESSMODE = 2;
  17371. return Texture;
  17372. })(BABYLON.BaseTexture);
  17373. BABYLON.Texture = Texture;
  17374. })(BABYLON || (BABYLON = {}));
  17375. var BABYLON;
  17376. (function (BABYLON) {
  17377. var CubeTexture = (function (_super) {
  17378. __extends(CubeTexture, _super);
  17379. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17380. _super.call(this, scene);
  17381. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17382. this.name = rootUrl;
  17383. this.url = rootUrl;
  17384. this._noMipmap = noMipmap;
  17385. this.hasAlpha = false;
  17386. if (!rootUrl) {
  17387. return;
  17388. }
  17389. this._texture = this._getFromCache(rootUrl, noMipmap);
  17390. if (!extensions) {
  17391. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17392. }
  17393. this._extensions = extensions;
  17394. if (!this._texture) {
  17395. if (!scene.useDelayedTextureLoading) {
  17396. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17397. }
  17398. else {
  17399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17400. }
  17401. }
  17402. this.isCube = true;
  17403. this._textureMatrix = BABYLON.Matrix.Identity();
  17404. }
  17405. CubeTexture.prototype.clone = function () {
  17406. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17407. // Base texture
  17408. newTexture.level = this.level;
  17409. newTexture.wrapU = this.wrapU;
  17410. newTexture.wrapV = this.wrapV;
  17411. newTexture.coordinatesIndex = this.coordinatesIndex;
  17412. newTexture.coordinatesMode = this.coordinatesMode;
  17413. return newTexture;
  17414. };
  17415. // Methods
  17416. CubeTexture.prototype.delayLoad = function () {
  17417. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17418. return;
  17419. }
  17420. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17421. this._texture = this._getFromCache(this.url, this._noMipmap);
  17422. if (!this._texture) {
  17423. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17424. }
  17425. };
  17426. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17427. return this._textureMatrix;
  17428. };
  17429. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17430. var texture = null;
  17431. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17432. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17433. texture.name = parsedTexture.name;
  17434. texture.hasAlpha = parsedTexture.hasAlpha;
  17435. texture.level = parsedTexture.level;
  17436. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17437. }
  17438. return texture;
  17439. };
  17440. CubeTexture.prototype.serialize = function () {
  17441. if (!this.name) {
  17442. return null;
  17443. }
  17444. var serializationObject = {};
  17445. serializationObject.name = this.name;
  17446. serializationObject.hasAlpha = this.hasAlpha;
  17447. serializationObject.isCube = true;
  17448. serializationObject.level = this.level;
  17449. serializationObject.coordinatesMode = this.coordinatesMode;
  17450. return serializationObject;
  17451. };
  17452. return CubeTexture;
  17453. })(BABYLON.BaseTexture);
  17454. BABYLON.CubeTexture = CubeTexture;
  17455. })(BABYLON || (BABYLON = {}));
  17456. var BABYLON;
  17457. (function (BABYLON) {
  17458. var RenderTargetTexture = (function (_super) {
  17459. __extends(RenderTargetTexture, _super);
  17460. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17461. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17462. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17463. if (isCube === void 0) { isCube = false; }
  17464. _super.call(this, null, scene, !generateMipMaps);
  17465. this.isCube = isCube;
  17466. this.renderList = new Array();
  17467. this.renderParticles = true;
  17468. this.renderSprites = false;
  17469. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17470. this._currentRefreshId = -1;
  17471. this._refreshRate = 1;
  17472. this.name = name;
  17473. this.isRenderTarget = true;
  17474. this._size = size;
  17475. this._generateMipMaps = generateMipMaps;
  17476. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17477. if (isCube) {
  17478. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17479. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17480. this._textureMatrix = BABYLON.Matrix.Identity();
  17481. }
  17482. else {
  17483. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17484. }
  17485. // Rendering groups
  17486. this._renderingManager = new BABYLON.RenderingManager(scene);
  17487. }
  17488. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17489. get: function () {
  17490. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17491. },
  17492. enumerable: true,
  17493. configurable: true
  17494. });
  17495. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17496. get: function () {
  17497. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17503. get: function () {
  17504. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17505. },
  17506. enumerable: true,
  17507. configurable: true
  17508. });
  17509. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17510. this._currentRefreshId = -1;
  17511. };
  17512. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17513. get: function () {
  17514. return this._refreshRate;
  17515. },
  17516. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17517. set: function (value) {
  17518. this._refreshRate = value;
  17519. this.resetRefreshCounter();
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. RenderTargetTexture.prototype._shouldRender = function () {
  17525. if (this._currentRefreshId === -1) {
  17526. this._currentRefreshId = 1;
  17527. return true;
  17528. }
  17529. if (this.refreshRate === this._currentRefreshId) {
  17530. this._currentRefreshId = 1;
  17531. return true;
  17532. }
  17533. this._currentRefreshId++;
  17534. return false;
  17535. };
  17536. RenderTargetTexture.prototype.isReady = function () {
  17537. if (!this.getScene().renderTargetsEnabled) {
  17538. return false;
  17539. }
  17540. return _super.prototype.isReady.call(this);
  17541. };
  17542. RenderTargetTexture.prototype.getRenderSize = function () {
  17543. return this._size;
  17544. };
  17545. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17546. get: function () {
  17547. return true;
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. RenderTargetTexture.prototype.scale = function (ratio) {
  17553. var newSize = this._size * ratio;
  17554. this.resize(newSize, this._generateMipMaps);
  17555. };
  17556. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17557. if (this.isCube) {
  17558. return this._textureMatrix;
  17559. }
  17560. return _super.prototype.getReflectionTextureMatrix.call(this);
  17561. };
  17562. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17563. this.releaseInternalTexture();
  17564. if (this.isCube) {
  17565. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17566. }
  17567. else {
  17568. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17569. }
  17570. };
  17571. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17572. var scene = this.getScene();
  17573. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17574. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17575. }
  17576. if (this._waitingRenderList) {
  17577. this.renderList = [];
  17578. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17579. var id = this._waitingRenderList[index];
  17580. this.renderList.push(scene.getMeshByID(id));
  17581. }
  17582. delete this._waitingRenderList;
  17583. }
  17584. if (this.renderList && this.renderList.length === 0) {
  17585. return;
  17586. }
  17587. // Prepare renderingManager
  17588. this._renderingManager.reset();
  17589. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17590. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17591. var mesh = currentRenderList[meshIndex];
  17592. if (mesh) {
  17593. if (!mesh.isReady()) {
  17594. // Reset _currentRefreshId
  17595. this.resetRefreshCounter();
  17596. continue;
  17597. }
  17598. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17599. mesh._activate(scene.getRenderId());
  17600. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17601. var subMesh = mesh.subMeshes[subIndex];
  17602. scene._activeIndices += subMesh.indexCount;
  17603. this._renderingManager.dispatch(subMesh);
  17604. }
  17605. }
  17606. }
  17607. }
  17608. if (this.isCube) {
  17609. for (var face = 0; face < 6; face++) {
  17610. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17611. scene.incrementRenderId();
  17612. }
  17613. }
  17614. else {
  17615. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17616. }
  17617. if (this.onAfterUnbind) {
  17618. this.onAfterUnbind();
  17619. }
  17620. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17621. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17622. }
  17623. scene.resetCachedMaterial();
  17624. };
  17625. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17626. var scene = this.getScene();
  17627. var engine = scene.getEngine();
  17628. // Bind
  17629. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17630. if (this.isCube) {
  17631. engine.bindFramebuffer(this._texture, faceIndex);
  17632. }
  17633. else {
  17634. engine.bindFramebuffer(this._texture);
  17635. }
  17636. }
  17637. if (this.onBeforeRender) {
  17638. this.onBeforeRender(faceIndex);
  17639. }
  17640. // Clear
  17641. if (this.onClear) {
  17642. this.onClear(engine);
  17643. }
  17644. else {
  17645. engine.clear(scene.clearColor, true, true);
  17646. }
  17647. if (!this._doNotChangeAspectRatio) {
  17648. scene.updateTransformMatrix(true);
  17649. }
  17650. // Render
  17651. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17652. if (useCameraPostProcess) {
  17653. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17654. }
  17655. if (!this._doNotChangeAspectRatio) {
  17656. scene.updateTransformMatrix(true);
  17657. }
  17658. if (this.onAfterRender) {
  17659. this.onAfterRender(faceIndex);
  17660. }
  17661. // Dump ?
  17662. if (dumpForDebug) {
  17663. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17664. }
  17665. // Unbind
  17666. if (!this.isCube || faceIndex === 5) {
  17667. if (this.isCube) {
  17668. if (faceIndex === 5) {
  17669. engine.generateMipMapsForCubemap(this._texture);
  17670. }
  17671. }
  17672. engine.unBindFramebuffer(this._texture, this.isCube);
  17673. }
  17674. };
  17675. RenderTargetTexture.prototype.clone = function () {
  17676. var textureSize = this.getSize();
  17677. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17678. // Base texture
  17679. newTexture.hasAlpha = this.hasAlpha;
  17680. newTexture.level = this.level;
  17681. // RenderTarget Texture
  17682. newTexture.coordinatesMode = this.coordinatesMode;
  17683. newTexture.renderList = this.renderList.slice(0);
  17684. return newTexture;
  17685. };
  17686. RenderTargetTexture.prototype.serialize = function () {
  17687. if (!this.name) {
  17688. return null;
  17689. }
  17690. var serializationObject = _super.prototype.serialize.call(this);
  17691. serializationObject.renderTargetSize = this.getRenderSize();
  17692. serializationObject.renderList = [];
  17693. for (var index = 0; index < this.renderList.length; index++) {
  17694. serializationObject.renderList.push(this.renderList[index].id);
  17695. }
  17696. return serializationObject;
  17697. };
  17698. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17699. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17700. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17701. return RenderTargetTexture;
  17702. })(BABYLON.Texture);
  17703. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17704. })(BABYLON || (BABYLON = {}));
  17705. var BABYLON;
  17706. (function (BABYLON) {
  17707. var ProceduralTexture = (function (_super) {
  17708. __extends(ProceduralTexture, _super);
  17709. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17710. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17711. _super.call(this, null, scene, !generateMipMaps);
  17712. this.isEnabled = true;
  17713. this._currentRefreshId = -1;
  17714. this._refreshRate = 1;
  17715. this._vertexDeclaration = [2];
  17716. this._vertexStrideSize = 2 * 4;
  17717. this._uniforms = new Array();
  17718. this._samplers = new Array();
  17719. this._textures = new Array();
  17720. this._floats = new Array();
  17721. this._floatsArrays = {};
  17722. this._colors3 = new Array();
  17723. this._colors4 = new Array();
  17724. this._vectors2 = new Array();
  17725. this._vectors3 = new Array();
  17726. this._matrices = new Array();
  17727. this._fallbackTextureUsed = false;
  17728. scene._proceduralTextures.push(this);
  17729. this.name = name;
  17730. this.isRenderTarget = true;
  17731. this._size = size;
  17732. this._generateMipMaps = generateMipMaps;
  17733. this.setFragment(fragment);
  17734. this._fallbackTexture = fallbackTexture;
  17735. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17736. // VBO
  17737. var vertices = [];
  17738. vertices.push(1, 1);
  17739. vertices.push(-1, 1);
  17740. vertices.push(-1, -1);
  17741. vertices.push(1, -1);
  17742. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17743. // Indices
  17744. var indices = [];
  17745. indices.push(0);
  17746. indices.push(1);
  17747. indices.push(2);
  17748. indices.push(0);
  17749. indices.push(2);
  17750. indices.push(3);
  17751. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17752. }
  17753. ProceduralTexture.prototype.reset = function () {
  17754. if (this._effect === undefined) {
  17755. return;
  17756. }
  17757. var engine = this.getScene().getEngine();
  17758. engine._releaseEffect(this._effect);
  17759. };
  17760. ProceduralTexture.prototype.isReady = function () {
  17761. var _this = this;
  17762. var engine = this.getScene().getEngine();
  17763. var shaders;
  17764. if (!this._fragment) {
  17765. return false;
  17766. }
  17767. if (this._fallbackTextureUsed) {
  17768. return true;
  17769. }
  17770. if (this._fragment.fragmentElement !== undefined) {
  17771. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17772. }
  17773. else {
  17774. shaders = { vertex: "procedural", fragment: this._fragment };
  17775. }
  17776. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17777. _this.releaseInternalTexture();
  17778. if (_this._fallbackTexture) {
  17779. _this._texture = _this._fallbackTexture._texture;
  17780. _this._texture.references++;
  17781. }
  17782. _this._fallbackTextureUsed = true;
  17783. });
  17784. return this._effect.isReady();
  17785. };
  17786. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17787. this._currentRefreshId = -1;
  17788. };
  17789. ProceduralTexture.prototype.setFragment = function (fragment) {
  17790. this._fragment = fragment;
  17791. };
  17792. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17793. get: function () {
  17794. return this._refreshRate;
  17795. },
  17796. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17797. set: function (value) {
  17798. this._refreshRate = value;
  17799. this.resetRefreshCounter();
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. ProceduralTexture.prototype._shouldRender = function () {
  17805. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17806. return false;
  17807. }
  17808. if (this._fallbackTextureUsed) {
  17809. return false;
  17810. }
  17811. if (this._currentRefreshId === -1) {
  17812. this._currentRefreshId = 1;
  17813. return true;
  17814. }
  17815. if (this.refreshRate === this._currentRefreshId) {
  17816. this._currentRefreshId = 1;
  17817. return true;
  17818. }
  17819. this._currentRefreshId++;
  17820. return false;
  17821. };
  17822. ProceduralTexture.prototype.getRenderSize = function () {
  17823. return this._size;
  17824. };
  17825. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17826. if (this._fallbackTextureUsed) {
  17827. return;
  17828. }
  17829. this.releaseInternalTexture();
  17830. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17831. };
  17832. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17833. if (this._uniforms.indexOf(uniformName) === -1) {
  17834. this._uniforms.push(uniformName);
  17835. }
  17836. };
  17837. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17838. if (this._samplers.indexOf(name) === -1) {
  17839. this._samplers.push(name);
  17840. }
  17841. this._textures[name] = texture;
  17842. return this;
  17843. };
  17844. ProceduralTexture.prototype.setFloat = function (name, value) {
  17845. this._checkUniform(name);
  17846. this._floats[name] = value;
  17847. return this;
  17848. };
  17849. ProceduralTexture.prototype.setFloats = function (name, value) {
  17850. this._checkUniform(name);
  17851. this._floatsArrays[name] = value;
  17852. return this;
  17853. };
  17854. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17855. this._checkUniform(name);
  17856. this._colors3[name] = value;
  17857. return this;
  17858. };
  17859. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17860. this._checkUniform(name);
  17861. this._colors4[name] = value;
  17862. return this;
  17863. };
  17864. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17865. this._checkUniform(name);
  17866. this._vectors2[name] = value;
  17867. return this;
  17868. };
  17869. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17870. this._checkUniform(name);
  17871. this._vectors3[name] = value;
  17872. return this;
  17873. };
  17874. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17875. this._checkUniform(name);
  17876. this._matrices[name] = value;
  17877. return this;
  17878. };
  17879. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17880. var scene = this.getScene();
  17881. var engine = scene.getEngine();
  17882. engine.bindFramebuffer(this._texture);
  17883. // Clear
  17884. engine.clear(scene.clearColor, true, true);
  17885. // Render
  17886. engine.enableEffect(this._effect);
  17887. engine.setState(false);
  17888. // Texture
  17889. for (var name in this._textures) {
  17890. this._effect.setTexture(name, this._textures[name]);
  17891. }
  17892. // Float
  17893. for (name in this._floats) {
  17894. this._effect.setFloat(name, this._floats[name]);
  17895. }
  17896. // Floats
  17897. for (name in this._floatsArrays) {
  17898. this._effect.setArray(name, this._floatsArrays[name]);
  17899. }
  17900. // Color3
  17901. for (name in this._colors3) {
  17902. this._effect.setColor3(name, this._colors3[name]);
  17903. }
  17904. // Color4
  17905. for (name in this._colors4) {
  17906. var color = this._colors4[name];
  17907. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17908. }
  17909. // Vector2
  17910. for (name in this._vectors2) {
  17911. this._effect.setVector2(name, this._vectors2[name]);
  17912. }
  17913. // Vector3
  17914. for (name in this._vectors3) {
  17915. this._effect.setVector3(name, this._vectors3[name]);
  17916. }
  17917. // Matrix
  17918. for (name in this._matrices) {
  17919. this._effect.setMatrix(name, this._matrices[name]);
  17920. }
  17921. // VBOs
  17922. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17923. // Draw order
  17924. engine.draw(true, 0, 6);
  17925. // Unbind
  17926. engine.unBindFramebuffer(this._texture);
  17927. };
  17928. ProceduralTexture.prototype.clone = function () {
  17929. var textureSize = this.getSize();
  17930. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17931. // Base texture
  17932. newTexture.hasAlpha = this.hasAlpha;
  17933. newTexture.level = this.level;
  17934. // RenderTarget Texture
  17935. newTexture.coordinatesMode = this.coordinatesMode;
  17936. return newTexture;
  17937. };
  17938. ProceduralTexture.prototype.dispose = function () {
  17939. var index = this.getScene()._proceduralTextures.indexOf(this);
  17940. if (index >= 0) {
  17941. this.getScene()._proceduralTextures.splice(index, 1);
  17942. }
  17943. _super.prototype.dispose.call(this);
  17944. };
  17945. return ProceduralTexture;
  17946. })(BABYLON.Texture);
  17947. BABYLON.ProceduralTexture = ProceduralTexture;
  17948. })(BABYLON || (BABYLON = {}));
  17949. var BABYLON;
  17950. (function (BABYLON) {
  17951. var MirrorTexture = (function (_super) {
  17952. __extends(MirrorTexture, _super);
  17953. function MirrorTexture(name, size, scene, generateMipMaps) {
  17954. var _this = this;
  17955. _super.call(this, name, size, scene, generateMipMaps, true);
  17956. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17957. this._transformMatrix = BABYLON.Matrix.Zero();
  17958. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17959. this.onBeforeRender = function () {
  17960. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17961. _this._savedViewMatrix = scene.getViewMatrix();
  17962. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17963. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17964. scene.clipPlane = _this.mirrorPlane;
  17965. scene.getEngine().cullBackFaces = false;
  17966. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17967. };
  17968. this.onAfterRender = function () {
  17969. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17970. scene.getEngine().cullBackFaces = true;
  17971. scene._mirroredCameraPosition = null;
  17972. delete scene.clipPlane;
  17973. };
  17974. }
  17975. MirrorTexture.prototype.clone = function () {
  17976. var textureSize = this.getSize();
  17977. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17978. // Base texture
  17979. newTexture.hasAlpha = this.hasAlpha;
  17980. newTexture.level = this.level;
  17981. // Mirror Texture
  17982. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17983. newTexture.renderList = this.renderList.slice(0);
  17984. return newTexture;
  17985. };
  17986. MirrorTexture.prototype.serialize = function () {
  17987. if (!this.name) {
  17988. return null;
  17989. }
  17990. var serializationObject = _super.prototype.serialize.call(this);
  17991. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17992. return serializationObject;
  17993. };
  17994. return MirrorTexture;
  17995. })(BABYLON.RenderTargetTexture);
  17996. BABYLON.MirrorTexture = MirrorTexture;
  17997. })(BABYLON || (BABYLON = {}));
  17998. var BABYLON;
  17999. (function (BABYLON) {
  18000. var DynamicTexture = (function (_super) {
  18001. __extends(DynamicTexture, _super);
  18002. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18004. _super.call(this, null, scene, !generateMipMaps);
  18005. this.name = name;
  18006. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18007. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18008. this._generateMipMaps = generateMipMaps;
  18009. if (options.getContext) {
  18010. this._canvas = options;
  18011. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18012. }
  18013. else {
  18014. this._canvas = document.createElement("canvas");
  18015. if (options.width) {
  18016. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18017. }
  18018. else {
  18019. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18020. }
  18021. }
  18022. var textureSize = this.getSize();
  18023. this._canvas.width = textureSize.width;
  18024. this._canvas.height = textureSize.height;
  18025. this._context = this._canvas.getContext("2d");
  18026. }
  18027. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18028. get: function () {
  18029. return true;
  18030. },
  18031. enumerable: true,
  18032. configurable: true
  18033. });
  18034. DynamicTexture.prototype.scale = function (ratio) {
  18035. var textureSize = this.getSize();
  18036. textureSize.width *= ratio;
  18037. textureSize.height *= ratio;
  18038. this._canvas.width = textureSize.width;
  18039. this._canvas.height = textureSize.height;
  18040. this.releaseInternalTexture();
  18041. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18042. };
  18043. DynamicTexture.prototype.getContext = function () {
  18044. return this._context;
  18045. };
  18046. DynamicTexture.prototype.clear = function () {
  18047. var size = this.getSize();
  18048. this._context.fillRect(0, 0, size.width, size.height);
  18049. };
  18050. DynamicTexture.prototype.update = function (invertY) {
  18051. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18052. };
  18053. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18054. if (update === void 0) { update = true; }
  18055. var size = this.getSize();
  18056. if (clearColor) {
  18057. this._context.fillStyle = clearColor;
  18058. this._context.fillRect(0, 0, size.width, size.height);
  18059. }
  18060. this._context.font = font;
  18061. if (x === null) {
  18062. var textSize = this._context.measureText(text);
  18063. x = (size.width - textSize.width) / 2;
  18064. }
  18065. this._context.fillStyle = color;
  18066. this._context.fillText(text, x, y);
  18067. if (update) {
  18068. this.update(invertY);
  18069. }
  18070. };
  18071. DynamicTexture.prototype.clone = function () {
  18072. var textureSize = this.getSize();
  18073. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18074. // Base texture
  18075. newTexture.hasAlpha = this.hasAlpha;
  18076. newTexture.level = this.level;
  18077. // Dynamic Texture
  18078. newTexture.wrapU = this.wrapU;
  18079. newTexture.wrapV = this.wrapV;
  18080. return newTexture;
  18081. };
  18082. return DynamicTexture;
  18083. })(BABYLON.Texture);
  18084. BABYLON.DynamicTexture = DynamicTexture;
  18085. })(BABYLON || (BABYLON = {}));
  18086. var BABYLON;
  18087. (function (BABYLON) {
  18088. var VideoTexture = (function (_super) {
  18089. __extends(VideoTexture, _super);
  18090. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18091. var _this = this;
  18092. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18093. if (invertY === void 0) { invertY = false; }
  18094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18095. _super.call(this, null, scene, !generateMipMaps, invertY);
  18096. this._autoLaunch = true;
  18097. this.name = name;
  18098. this.video = document.createElement("video");
  18099. this.video.autoplay = false;
  18100. this.video.loop = true;
  18101. this.video.addEventListener("canplaythrough", function () {
  18102. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18103. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18104. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18105. }
  18106. else {
  18107. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18108. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18109. generateMipMaps = false;
  18110. }
  18111. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18112. _this._texture.isReady = true;
  18113. });
  18114. urls.forEach(function (url) {
  18115. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18116. var source = document.createElement("source");
  18117. source.src = url;
  18118. _this.video.appendChild(source);
  18119. });
  18120. this._lastUpdate = BABYLON.Tools.Now;
  18121. }
  18122. VideoTexture.prototype.update = function () {
  18123. if (this._autoLaunch) {
  18124. this._autoLaunch = false;
  18125. this.video.play();
  18126. }
  18127. var now = BABYLON.Tools.Now;
  18128. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18129. return false;
  18130. }
  18131. this._lastUpdate = now;
  18132. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18133. return true;
  18134. };
  18135. return VideoTexture;
  18136. })(BABYLON.Texture);
  18137. BABYLON.VideoTexture = VideoTexture;
  18138. })(BABYLON || (BABYLON = {}));
  18139. var BABYLON;
  18140. (function (BABYLON) {
  18141. var CustomProceduralTexture = (function (_super) {
  18142. __extends(CustomProceduralTexture, _super);
  18143. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18144. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18145. this._animate = true;
  18146. this._time = 0;
  18147. this._texturePath = texturePath;
  18148. //Try to load json
  18149. this.loadJson(texturePath);
  18150. this.refreshRate = 1;
  18151. }
  18152. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18153. var _this = this;
  18154. var that = this;
  18155. function noConfigFile() {
  18156. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18157. try {
  18158. that.setFragment(that._texturePath);
  18159. }
  18160. catch (ex) {
  18161. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18162. }
  18163. }
  18164. var configFileUrl = jsonUrl + "/config.json";
  18165. var xhr = new XMLHttpRequest();
  18166. xhr.open("GET", configFileUrl, true);
  18167. xhr.addEventListener("load", function () {
  18168. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18169. try {
  18170. _this._config = JSON.parse(xhr.response);
  18171. _this.updateShaderUniforms();
  18172. _this.updateTextures();
  18173. _this.setFragment(_this._texturePath + "/custom");
  18174. _this._animate = _this._config.animate;
  18175. _this.refreshRate = _this._config.refreshrate;
  18176. }
  18177. catch (ex) {
  18178. noConfigFile();
  18179. }
  18180. }
  18181. else {
  18182. noConfigFile();
  18183. }
  18184. }, false);
  18185. xhr.addEventListener("error", function () {
  18186. noConfigFile();
  18187. }, false);
  18188. try {
  18189. xhr.send();
  18190. }
  18191. catch (ex) {
  18192. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18193. }
  18194. };
  18195. CustomProceduralTexture.prototype.isReady = function () {
  18196. if (!_super.prototype.isReady.call(this)) {
  18197. return false;
  18198. }
  18199. for (var name in this._textures) {
  18200. var texture = this._textures[name];
  18201. if (!texture.isReady()) {
  18202. return false;
  18203. }
  18204. }
  18205. return true;
  18206. };
  18207. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18208. if (this._animate) {
  18209. this._time += this.getScene().getAnimationRatio() * 0.03;
  18210. this.updateShaderUniforms();
  18211. }
  18212. _super.prototype.render.call(this, useCameraPostProcess);
  18213. };
  18214. CustomProceduralTexture.prototype.updateTextures = function () {
  18215. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18216. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18217. }
  18218. };
  18219. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18220. if (this._config) {
  18221. for (var j = 0; j < this._config.uniforms.length; j++) {
  18222. var uniform = this._config.uniforms[j];
  18223. switch (uniform.type) {
  18224. case "float":
  18225. this.setFloat(uniform.name, uniform.value);
  18226. break;
  18227. case "color3":
  18228. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18229. break;
  18230. case "color4":
  18231. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18232. break;
  18233. case "vector2":
  18234. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18235. break;
  18236. case "vector3":
  18237. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18238. break;
  18239. }
  18240. }
  18241. }
  18242. this.setFloat("time", this._time);
  18243. };
  18244. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18245. get: function () {
  18246. return this._animate;
  18247. },
  18248. set: function (value) {
  18249. this._animate = value;
  18250. },
  18251. enumerable: true,
  18252. configurable: true
  18253. });
  18254. return CustomProceduralTexture;
  18255. })(BABYLON.ProceduralTexture);
  18256. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18257. })(BABYLON || (BABYLON = {}));
  18258. var BABYLON;
  18259. (function (BABYLON) {
  18260. var EffectFallbacks = (function () {
  18261. function EffectFallbacks() {
  18262. this._defines = {};
  18263. this._currentRank = 32;
  18264. this._maxRank = -1;
  18265. }
  18266. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18267. if (!this._defines[rank]) {
  18268. if (rank < this._currentRank) {
  18269. this._currentRank = rank;
  18270. }
  18271. if (rank > this._maxRank) {
  18272. this._maxRank = rank;
  18273. }
  18274. this._defines[rank] = new Array();
  18275. }
  18276. this._defines[rank].push(define);
  18277. };
  18278. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18279. this._meshRank = rank;
  18280. this._mesh = mesh;
  18281. if (rank > this._maxRank) {
  18282. this._maxRank = rank;
  18283. }
  18284. };
  18285. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18286. get: function () {
  18287. return this._currentRank <= this._maxRank;
  18288. },
  18289. enumerable: true,
  18290. configurable: true
  18291. });
  18292. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18293. var currentFallbacks = this._defines[this._currentRank];
  18294. for (var index = 0; index < currentFallbacks.length; index++) {
  18295. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18296. }
  18297. if (this._mesh && this._currentRank === this._meshRank) {
  18298. this._mesh.computeBonesUsingShaders = false;
  18299. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18300. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18301. }
  18302. this._currentRank++;
  18303. return currentDefines;
  18304. };
  18305. return EffectFallbacks;
  18306. })();
  18307. BABYLON.EffectFallbacks = EffectFallbacks;
  18308. var Effect = (function () {
  18309. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18310. var _this = this;
  18311. this._isReady = false;
  18312. this._compilationError = "";
  18313. this._valueCache = [];
  18314. this._engine = engine;
  18315. this.name = baseName;
  18316. this.defines = defines;
  18317. this._uniformsNames = uniformsNames.concat(samplers);
  18318. this._samplers = samplers;
  18319. this._attributesNames = attributesNames;
  18320. this.onError = onError;
  18321. this.onCompiled = onCompiled;
  18322. var vertexSource;
  18323. var fragmentSource;
  18324. if (baseName.vertexElement) {
  18325. vertexSource = document.getElementById(baseName.vertexElement);
  18326. if (!vertexSource) {
  18327. vertexSource = baseName.vertexElement;
  18328. }
  18329. }
  18330. else {
  18331. vertexSource = baseName.vertex || baseName;
  18332. }
  18333. if (baseName.fragmentElement) {
  18334. fragmentSource = document.getElementById(baseName.fragmentElement);
  18335. if (!fragmentSource) {
  18336. fragmentSource = baseName.fragmentElement;
  18337. }
  18338. }
  18339. else {
  18340. fragmentSource = baseName.fragment || baseName;
  18341. }
  18342. this._loadVertexShader(vertexSource, function (vertexCode) {
  18343. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18344. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18345. });
  18346. });
  18347. }
  18348. // Properties
  18349. Effect.prototype.isReady = function () {
  18350. return this._isReady;
  18351. };
  18352. Effect.prototype.getProgram = function () {
  18353. return this._program;
  18354. };
  18355. Effect.prototype.getAttributesNames = function () {
  18356. return this._attributesNames;
  18357. };
  18358. Effect.prototype.getAttributeLocation = function (index) {
  18359. return this._attributes[index];
  18360. };
  18361. Effect.prototype.getAttributeLocationByName = function (name) {
  18362. var index = this._attributesNames.indexOf(name);
  18363. return this._attributes[index];
  18364. };
  18365. Effect.prototype.getAttributesCount = function () {
  18366. return this._attributes.length;
  18367. };
  18368. Effect.prototype.getUniformIndex = function (uniformName) {
  18369. return this._uniformsNames.indexOf(uniformName);
  18370. };
  18371. Effect.prototype.getUniform = function (uniformName) {
  18372. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18373. };
  18374. Effect.prototype.getSamplers = function () {
  18375. return this._samplers;
  18376. };
  18377. Effect.prototype.getCompilationError = function () {
  18378. return this._compilationError;
  18379. };
  18380. // Methods
  18381. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18382. // DOM element ?
  18383. if (vertex instanceof HTMLElement) {
  18384. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18385. callback(vertexCode);
  18386. return;
  18387. }
  18388. // Is in local store ?
  18389. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18390. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18391. return;
  18392. }
  18393. var vertexShaderUrl;
  18394. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18395. vertexShaderUrl = vertex;
  18396. }
  18397. else {
  18398. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18399. }
  18400. // Vertex shader
  18401. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18402. };
  18403. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18404. // DOM element ?
  18405. if (fragment instanceof HTMLElement) {
  18406. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18407. callback(fragmentCode);
  18408. return;
  18409. }
  18410. // Is in local store ?
  18411. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18412. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18413. return;
  18414. }
  18415. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18416. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18417. return;
  18418. }
  18419. var fragmentShaderUrl;
  18420. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18421. fragmentShaderUrl = fragment;
  18422. }
  18423. else {
  18424. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18425. }
  18426. // Fragment shader
  18427. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18428. };
  18429. Effect.prototype._dumpShadersName = function () {
  18430. if (this.name.vertexElement) {
  18431. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18432. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18433. }
  18434. else if (this.name.vertex) {
  18435. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18436. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18437. }
  18438. else {
  18439. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18440. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18441. }
  18442. };
  18443. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18444. try {
  18445. var engine = this._engine;
  18446. if (!engine.getCaps().highPrecisionShaderSupported) {
  18447. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18448. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18449. }
  18450. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18451. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18452. this._attributes = engine.getAttributes(this._program, attributesNames);
  18453. for (var index = 0; index < this._samplers.length; index++) {
  18454. var sampler = this.getUniform(this._samplers[index]);
  18455. if (sampler == null) {
  18456. this._samplers.splice(index, 1);
  18457. index--;
  18458. }
  18459. }
  18460. engine.bindSamplers(this);
  18461. this._isReady = true;
  18462. if (this.onCompiled) {
  18463. this.onCompiled(this);
  18464. }
  18465. }
  18466. catch (e) {
  18467. // Is it a problem with precision?
  18468. if (e.message.indexOf("highp") !== -1) {
  18469. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18470. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18471. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18472. return;
  18473. }
  18474. // Let's go through fallbacks then
  18475. if (fallbacks && fallbacks.isMoreFallbacks) {
  18476. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18477. this._dumpShadersName();
  18478. defines = fallbacks.reduce(defines);
  18479. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18480. }
  18481. else {
  18482. BABYLON.Tools.Error("Unable to compile effect: ");
  18483. this._dumpShadersName();
  18484. BABYLON.Tools.Error("Defines: " + defines);
  18485. BABYLON.Tools.Error("Error: " + e.message);
  18486. this._compilationError = e.message;
  18487. if (this.onError) {
  18488. this.onError(this, this._compilationError);
  18489. }
  18490. }
  18491. }
  18492. };
  18493. Object.defineProperty(Effect.prototype, "isSupported", {
  18494. get: function () {
  18495. return this._compilationError === "";
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. Effect.prototype._bindTexture = function (channel, texture) {
  18501. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18502. };
  18503. Effect.prototype.setTexture = function (channel, texture) {
  18504. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18505. };
  18506. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18507. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18508. };
  18509. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18510. if (!this._valueCache[uniformName]) {
  18511. this._valueCache[uniformName] = new BABYLON.Matrix();
  18512. }
  18513. for (var index = 0; index < 16; index++) {
  18514. this._valueCache[uniformName].m[index] = matrix.m[index];
  18515. }
  18516. };
  18517. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18518. if (!this._valueCache[uniformName]) {
  18519. this._valueCache[uniformName] = [x, y];
  18520. return;
  18521. }
  18522. this._valueCache[uniformName][0] = x;
  18523. this._valueCache[uniformName][1] = y;
  18524. };
  18525. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18526. if (!this._valueCache[uniformName]) {
  18527. this._valueCache[uniformName] = [x, y, z];
  18528. return;
  18529. }
  18530. this._valueCache[uniformName][0] = x;
  18531. this._valueCache[uniformName][1] = y;
  18532. this._valueCache[uniformName][2] = z;
  18533. };
  18534. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18535. if (!this._valueCache[uniformName]) {
  18536. this._valueCache[uniformName] = [x, y, z, w];
  18537. return;
  18538. }
  18539. this._valueCache[uniformName][0] = x;
  18540. this._valueCache[uniformName][1] = y;
  18541. this._valueCache[uniformName][2] = z;
  18542. this._valueCache[uniformName][3] = w;
  18543. };
  18544. Effect.prototype.setArray = function (uniformName, array) {
  18545. this._engine.setArray(this.getUniform(uniformName), array);
  18546. return this;
  18547. };
  18548. Effect.prototype.setArray2 = function (uniformName, array) {
  18549. this._engine.setArray2(this.getUniform(uniformName), array);
  18550. return this;
  18551. };
  18552. Effect.prototype.setArray3 = function (uniformName, array) {
  18553. this._engine.setArray3(this.getUniform(uniformName), array);
  18554. return this;
  18555. };
  18556. Effect.prototype.setArray4 = function (uniformName, array) {
  18557. this._engine.setArray4(this.getUniform(uniformName), array);
  18558. return this;
  18559. };
  18560. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18561. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18562. return this;
  18563. };
  18564. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18565. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18566. // return this;
  18567. // this._cacheMatrix(uniformName, matrix);
  18568. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18569. return this;
  18570. };
  18571. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18572. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18573. return this;
  18574. };
  18575. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18576. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18577. return this;
  18578. };
  18579. Effect.prototype.setFloat = function (uniformName, value) {
  18580. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18581. return this;
  18582. this._valueCache[uniformName] = value;
  18583. this._engine.setFloat(this.getUniform(uniformName), value);
  18584. return this;
  18585. };
  18586. Effect.prototype.setBool = function (uniformName, bool) {
  18587. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18588. return this;
  18589. this._valueCache[uniformName] = bool;
  18590. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18591. return this;
  18592. };
  18593. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18594. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18595. return this;
  18596. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18597. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18598. return this;
  18599. };
  18600. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18601. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18602. return this;
  18603. this._cacheFloat2(uniformName, x, y);
  18604. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18605. return this;
  18606. };
  18607. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18608. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18609. return this;
  18610. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18611. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18612. return this;
  18613. };
  18614. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18615. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18616. return this;
  18617. this._cacheFloat3(uniformName, x, y, z);
  18618. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18619. return this;
  18620. };
  18621. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18622. 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)
  18623. return this;
  18624. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18625. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18626. return this;
  18627. };
  18628. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18629. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18630. return this;
  18631. this._cacheFloat4(uniformName, x, y, z, w);
  18632. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18633. return this;
  18634. };
  18635. Effect.prototype.setColor3 = function (uniformName, color3) {
  18636. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18637. return this;
  18638. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18639. this._engine.setColor3(this.getUniform(uniformName), color3);
  18640. return this;
  18641. };
  18642. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18643. 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)
  18644. return this;
  18645. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18646. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18647. return this;
  18648. };
  18649. // Statics
  18650. Effect.ShadersStore = {};
  18651. return Effect;
  18652. })();
  18653. BABYLON.Effect = Effect;
  18654. })(BABYLON || (BABYLON = {}));
  18655. var BABYLON;
  18656. (function (BABYLON) {
  18657. var MaterialDefines = (function () {
  18658. function MaterialDefines() {
  18659. }
  18660. MaterialDefines.prototype.isEqual = function (other) {
  18661. for (var index = 0; index < this._keys.length; index++) {
  18662. var prop = this._keys[index];
  18663. if (this[prop] !== other[prop]) {
  18664. return false;
  18665. }
  18666. }
  18667. return true;
  18668. };
  18669. MaterialDefines.prototype.cloneTo = function (other) {
  18670. for (var index = 0; index < this._keys.length; index++) {
  18671. var prop = this._keys[index];
  18672. other[prop] = this[prop];
  18673. }
  18674. };
  18675. MaterialDefines.prototype.reset = function () {
  18676. for (var index = 0; index < this._keys.length; index++) {
  18677. var prop = this._keys[index];
  18678. if (typeof (this[prop]) === "number") {
  18679. this[prop] = 0;
  18680. }
  18681. else {
  18682. this[prop] = false;
  18683. }
  18684. }
  18685. };
  18686. MaterialDefines.prototype.toString = function () {
  18687. var result = "";
  18688. for (var index = 0; index < this._keys.length; index++) {
  18689. var prop = this._keys[index];
  18690. if (typeof (this[prop]) === "number") {
  18691. result += "#define " + prop + " " + this[prop] + "\n";
  18692. }
  18693. else if (this[prop]) {
  18694. result += "#define " + prop + "\n";
  18695. }
  18696. }
  18697. return result;
  18698. };
  18699. return MaterialDefines;
  18700. })();
  18701. BABYLON.MaterialDefines = MaterialDefines;
  18702. var Material = (function () {
  18703. function Material(name, scene, doNotAdd) {
  18704. this.name = name;
  18705. this.checkReadyOnEveryCall = false;
  18706. this.checkReadyOnlyOnce = false;
  18707. this.state = "";
  18708. this.alpha = 1.0;
  18709. this.backFaceCulling = true;
  18710. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18711. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18712. this.disableDepthWrite = false;
  18713. this.fogEnabled = true;
  18714. this._wasPreviouslyReady = false;
  18715. this._fillMode = Material.TriangleFillMode;
  18716. this.pointSize = 1.0;
  18717. this.zOffset = 0;
  18718. this.id = name;
  18719. this._scene = scene;
  18720. if (!doNotAdd) {
  18721. scene.materials.push(this);
  18722. }
  18723. }
  18724. Object.defineProperty(Material, "TriangleFillMode", {
  18725. get: function () {
  18726. return Material._TriangleFillMode;
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(Material, "WireFrameFillMode", {
  18732. get: function () {
  18733. return Material._WireFrameFillMode;
  18734. },
  18735. enumerable: true,
  18736. configurable: true
  18737. });
  18738. Object.defineProperty(Material, "PointFillMode", {
  18739. get: function () {
  18740. return Material._PointFillMode;
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18746. get: function () {
  18747. return Material._ClockWiseSideOrientation;
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18753. get: function () {
  18754. return Material._CounterClockWiseSideOrientation;
  18755. },
  18756. enumerable: true,
  18757. configurable: true
  18758. });
  18759. Object.defineProperty(Material.prototype, "wireframe", {
  18760. get: function () {
  18761. return this._fillMode === Material.WireFrameFillMode;
  18762. },
  18763. set: function (value) {
  18764. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18765. },
  18766. enumerable: true,
  18767. configurable: true
  18768. });
  18769. Object.defineProperty(Material.prototype, "pointsCloud", {
  18770. get: function () {
  18771. return this._fillMode === Material.PointFillMode;
  18772. },
  18773. set: function (value) {
  18774. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(Material.prototype, "fillMode", {
  18780. get: function () {
  18781. return this._fillMode;
  18782. },
  18783. set: function (value) {
  18784. this._fillMode = value;
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. Object.defineProperty(Material.prototype, "isFrozen", {
  18790. get: function () {
  18791. return this.checkReadyOnlyOnce;
  18792. },
  18793. enumerable: true,
  18794. configurable: true
  18795. });
  18796. Material.prototype.freeze = function () {
  18797. this.checkReadyOnlyOnce = true;
  18798. };
  18799. Material.prototype.unfreeze = function () {
  18800. this.checkReadyOnlyOnce = false;
  18801. };
  18802. Material.prototype.isReady = function (mesh, useInstances) {
  18803. return true;
  18804. };
  18805. Material.prototype.getEffect = function () {
  18806. return this._effect;
  18807. };
  18808. Material.prototype.getScene = function () {
  18809. return this._scene;
  18810. };
  18811. Material.prototype.needAlphaBlending = function () {
  18812. return (this.alpha < 1.0);
  18813. };
  18814. Material.prototype.needAlphaTesting = function () {
  18815. return false;
  18816. };
  18817. Material.prototype.getAlphaTestTexture = function () {
  18818. return null;
  18819. };
  18820. Material.prototype.trackCreation = function (onCompiled, onError) {
  18821. };
  18822. Material.prototype.markDirty = function () {
  18823. this._wasPreviouslyReady = false;
  18824. };
  18825. Material.prototype._preBind = function () {
  18826. var engine = this._scene.getEngine();
  18827. engine.enableEffect(this._effect);
  18828. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18829. };
  18830. Material.prototype.bind = function (world, mesh) {
  18831. this._scene._cachedMaterial = this;
  18832. if (this.onBind) {
  18833. this.onBind(this, mesh);
  18834. }
  18835. if (this.disableDepthWrite) {
  18836. var engine = this._scene.getEngine();
  18837. this._cachedDepthWriteState = engine.getDepthWrite();
  18838. engine.setDepthWrite(false);
  18839. }
  18840. };
  18841. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18842. };
  18843. Material.prototype.unbind = function () {
  18844. if (this.disableDepthWrite) {
  18845. var engine = this._scene.getEngine();
  18846. engine.setDepthWrite(this._cachedDepthWriteState);
  18847. }
  18848. };
  18849. Material.prototype.clone = function (name) {
  18850. return null;
  18851. };
  18852. Material.prototype.getBindedMeshes = function () {
  18853. var result = new Array();
  18854. for (var index = 0; index < this._scene.meshes.length; index++) {
  18855. var mesh = this._scene.meshes[index];
  18856. if (mesh.material === this) {
  18857. result.push(mesh);
  18858. }
  18859. }
  18860. return result;
  18861. };
  18862. Material.prototype.dispose = function (forceDisposeEffect) {
  18863. // Animations
  18864. this.getScene().stopAnimation(this);
  18865. // Remove from scene
  18866. var index = this._scene.materials.indexOf(this);
  18867. if (index >= 0) {
  18868. this._scene.materials.splice(index, 1);
  18869. }
  18870. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18871. if (forceDisposeEffect && this._effect) {
  18872. this._scene.getEngine()._releaseEffect(this._effect);
  18873. this._effect = null;
  18874. }
  18875. // Remove from meshes
  18876. for (index = 0; index < this._scene.meshes.length; index++) {
  18877. var mesh = this._scene.meshes[index];
  18878. if (mesh.material === this) {
  18879. mesh.material = null;
  18880. }
  18881. }
  18882. // Callback
  18883. if (this.onDispose) {
  18884. this.onDispose();
  18885. }
  18886. };
  18887. Material.prototype.copyTo = function (other) {
  18888. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18889. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18890. other.alpha = this.alpha;
  18891. other.fillMode = this.fillMode;
  18892. other.backFaceCulling = this.backFaceCulling;
  18893. other.fogEnabled = this.fogEnabled;
  18894. other.wireframe = this.wireframe;
  18895. other.zOffset = this.zOffset;
  18896. other.alphaMode = this.alphaMode;
  18897. other.sideOrientation = this.sideOrientation;
  18898. other.disableDepthWrite = this.disableDepthWrite;
  18899. other.pointSize = this.pointSize;
  18900. other.pointsCloud = this.pointsCloud;
  18901. };
  18902. Material.prototype.serialize = function () {
  18903. var serializationObject = {};
  18904. serializationObject.name = this.name;
  18905. serializationObject.alpha = this.alpha;
  18906. serializationObject.id = this.id;
  18907. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18908. serializationObject.backFaceCulling = this.backFaceCulling;
  18909. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18910. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18911. return serializationObject;
  18912. };
  18913. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18914. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18915. multiMaterial.id = parsedMultiMaterial.id;
  18916. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18917. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18918. var subMatId = parsedMultiMaterial.materials[matIndex];
  18919. if (subMatId) {
  18920. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18921. }
  18922. else {
  18923. multiMaterial.subMaterials.push(null);
  18924. }
  18925. }
  18926. return multiMaterial;
  18927. };
  18928. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18929. if (!parsedMaterial.customType) {
  18930. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18931. }
  18932. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18933. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18934. ;
  18935. };
  18936. Material._TriangleFillMode = 0;
  18937. Material._WireFrameFillMode = 1;
  18938. Material._PointFillMode = 2;
  18939. Material._ClockWiseSideOrientation = 0;
  18940. Material._CounterClockWiseSideOrientation = 1;
  18941. return Material;
  18942. })();
  18943. BABYLON.Material = Material;
  18944. })(BABYLON || (BABYLON = {}));
  18945. var BABYLON;
  18946. (function (BABYLON) {
  18947. var maxSimultaneousLights = 4;
  18948. var FresnelParameters = (function () {
  18949. function FresnelParameters() {
  18950. this.isEnabled = true;
  18951. this.leftColor = BABYLON.Color3.White();
  18952. this.rightColor = BABYLON.Color3.Black();
  18953. this.bias = 0;
  18954. this.power = 1;
  18955. }
  18956. FresnelParameters.prototype.clone = function () {
  18957. var newFresnelParameters = new FresnelParameters();
  18958. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18959. return new FresnelParameters;
  18960. };
  18961. FresnelParameters.prototype.serialize = function () {
  18962. var serializationObject = {};
  18963. serializationObject.isEnabled = this.isEnabled;
  18964. serializationObject.leftColor = this.leftColor;
  18965. serializationObject.rightColor = this.rightColor;
  18966. serializationObject.bias = this.bias;
  18967. serializationObject.power = this.power;
  18968. return serializationObject;
  18969. };
  18970. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18971. var fresnelParameters = new FresnelParameters();
  18972. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18973. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18974. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18975. fresnelParameters.bias = parsedFresnelParameters.bias;
  18976. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18977. return fresnelParameters;
  18978. };
  18979. return FresnelParameters;
  18980. })();
  18981. BABYLON.FresnelParameters = FresnelParameters;
  18982. var StandardMaterialDefines = (function (_super) {
  18983. __extends(StandardMaterialDefines, _super);
  18984. function StandardMaterialDefines() {
  18985. _super.call(this);
  18986. this.DIFFUSE = false;
  18987. this.AMBIENT = false;
  18988. this.OPACITY = false;
  18989. this.OPACITYRGB = false;
  18990. this.REFLECTION = false;
  18991. this.EMISSIVE = false;
  18992. this.SPECULAR = false;
  18993. this.BUMP = false;
  18994. this.SPECULAROVERALPHA = false;
  18995. this.CLIPPLANE = false;
  18996. this.ALPHATEST = false;
  18997. this.ALPHAFROMDIFFUSE = false;
  18998. this.POINTSIZE = false;
  18999. this.FOG = false;
  19000. this.LIGHT0 = false;
  19001. this.LIGHT1 = false;
  19002. this.LIGHT2 = false;
  19003. this.LIGHT3 = false;
  19004. this.SPOTLIGHT0 = false;
  19005. this.SPOTLIGHT1 = false;
  19006. this.SPOTLIGHT2 = false;
  19007. this.SPOTLIGHT3 = false;
  19008. this.HEMILIGHT0 = false;
  19009. this.HEMILIGHT1 = false;
  19010. this.HEMILIGHT2 = false;
  19011. this.HEMILIGHT3 = false;
  19012. this.POINTLIGHT0 = false;
  19013. this.POINTLIGHT1 = false;
  19014. this.POINTLIGHT2 = false;
  19015. this.POINTLIGHT3 = false;
  19016. this.DIRLIGHT0 = false;
  19017. this.DIRLIGHT1 = false;
  19018. this.DIRLIGHT2 = false;
  19019. this.DIRLIGHT3 = false;
  19020. this.SPECULARTERM = false;
  19021. this.SHADOW0 = false;
  19022. this.SHADOW1 = false;
  19023. this.SHADOW2 = false;
  19024. this.SHADOW3 = false;
  19025. this.SHADOWS = false;
  19026. this.SHADOWVSM0 = false;
  19027. this.SHADOWVSM1 = false;
  19028. this.SHADOWVSM2 = false;
  19029. this.SHADOWVSM3 = false;
  19030. this.SHADOWPCF0 = false;
  19031. this.SHADOWPCF1 = false;
  19032. this.SHADOWPCF2 = false;
  19033. this.SHADOWPCF3 = false;
  19034. this.DIFFUSEFRESNEL = false;
  19035. this.OPACITYFRESNEL = false;
  19036. this.REFLECTIONFRESNEL = false;
  19037. this.EMISSIVEFRESNEL = false;
  19038. this.FRESNEL = false;
  19039. this.NORMAL = false;
  19040. this.UV1 = false;
  19041. this.UV2 = false;
  19042. this.VERTEXCOLOR = false;
  19043. this.VERTEXALPHA = false;
  19044. this.NUM_BONE_INFLUENCERS = 0;
  19045. this.BonesPerMesh = 0;
  19046. this.INSTANCES = false;
  19047. this.GLOSSINESS = false;
  19048. this.ROUGHNESS = false;
  19049. this.EMISSIVEASILLUMINATION = false;
  19050. this.LINKEMISSIVEWITHDIFFUSE = false;
  19051. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19052. this.LIGHTMAP = false;
  19053. this.USELIGHTMAPASSHADOWMAP = false;
  19054. this.REFLECTIONMAP_3D = false;
  19055. this.REFLECTIONMAP_SPHERICAL = false;
  19056. this.REFLECTIONMAP_PLANAR = false;
  19057. this.REFLECTIONMAP_CUBIC = false;
  19058. this.REFLECTIONMAP_PROJECTION = false;
  19059. this.REFLECTIONMAP_SKYBOX = false;
  19060. this.REFLECTIONMAP_EXPLICIT = false;
  19061. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19062. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19063. this.INVERTCUBICMAP = false;
  19064. this.LOGARITHMICDEPTH = false;
  19065. this._keys = Object.keys(this);
  19066. }
  19067. return StandardMaterialDefines;
  19068. })(BABYLON.MaterialDefines);
  19069. var StandardMaterial = (function (_super) {
  19070. __extends(StandardMaterial, _super);
  19071. function StandardMaterial(name, scene) {
  19072. var _this = this;
  19073. _super.call(this, name, scene);
  19074. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19075. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19076. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19077. this.specularPower = 64;
  19078. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19079. this.useAlphaFromDiffuseTexture = false;
  19080. this.useEmissiveAsIllumination = false;
  19081. this.linkEmissiveWithDiffuse = false;
  19082. this.useReflectionFresnelFromSpecular = false;
  19083. this.useSpecularOverAlpha = false;
  19084. this.disableLighting = false;
  19085. this.roughness = 0;
  19086. this.useLightmapAsShadowmap = false;
  19087. this.useGlossinessFromSpecularMapAlpha = false;
  19088. this._renderTargets = new BABYLON.SmartArray(16);
  19089. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19090. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19091. this._defines = new StandardMaterialDefines();
  19092. this._cachedDefines = new StandardMaterialDefines();
  19093. this._cachedDefines.BonesPerMesh = -1;
  19094. this.getRenderTargetTextures = function () {
  19095. _this._renderTargets.reset();
  19096. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19097. _this._renderTargets.push(_this.reflectionTexture);
  19098. }
  19099. return _this._renderTargets;
  19100. };
  19101. }
  19102. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19103. get: function () {
  19104. return this._useLogarithmicDepth;
  19105. },
  19106. set: function (value) {
  19107. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19108. },
  19109. enumerable: true,
  19110. configurable: true
  19111. });
  19112. StandardMaterial.prototype.needAlphaBlending = function () {
  19113. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19114. };
  19115. StandardMaterial.prototype.needAlphaTesting = function () {
  19116. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19117. };
  19118. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19119. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19120. };
  19121. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19122. return this.diffuseTexture;
  19123. };
  19124. // Methods
  19125. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19126. if (!mesh) {
  19127. return true;
  19128. }
  19129. if (this._defines.INSTANCES !== useInstances) {
  19130. return false;
  19131. }
  19132. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19133. return true;
  19134. }
  19135. return false;
  19136. };
  19137. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19138. var lightIndex = 0;
  19139. var needNormals = false;
  19140. for (var index = 0; index < scene.lights.length; index++) {
  19141. var light = scene.lights[index];
  19142. if (!light.isEnabled()) {
  19143. continue;
  19144. }
  19145. // Excluded check
  19146. if (light._excludedMeshesIds.length > 0) {
  19147. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19148. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19149. if (excludedMesh) {
  19150. light.excludedMeshes.push(excludedMesh);
  19151. }
  19152. }
  19153. light._excludedMeshesIds = [];
  19154. }
  19155. // Included check
  19156. if (light._includedOnlyMeshesIds.length > 0) {
  19157. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19158. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19159. if (includedOnlyMesh) {
  19160. light.includedOnlyMeshes.push(includedOnlyMesh);
  19161. }
  19162. }
  19163. light._includedOnlyMeshesIds = [];
  19164. }
  19165. if (!light.canAffectMesh(mesh)) {
  19166. continue;
  19167. }
  19168. needNormals = true;
  19169. defines["LIGHT" + lightIndex] = true;
  19170. var type;
  19171. if (light instanceof BABYLON.SpotLight) {
  19172. type = "SPOTLIGHT" + lightIndex;
  19173. }
  19174. else if (light instanceof BABYLON.HemisphericLight) {
  19175. type = "HEMILIGHT" + lightIndex;
  19176. }
  19177. else if (light instanceof BABYLON.PointLight) {
  19178. type = "POINTLIGHT" + lightIndex;
  19179. }
  19180. else {
  19181. type = "DIRLIGHT" + lightIndex;
  19182. }
  19183. defines[type] = true;
  19184. // Specular
  19185. if (!light.specular.equalsFloats(0, 0, 0)) {
  19186. defines["SPECULARTERM"] = true;
  19187. }
  19188. // Shadows
  19189. if (scene.shadowsEnabled) {
  19190. var shadowGenerator = light.getShadowGenerator();
  19191. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19192. defines["SHADOW" + lightIndex] = true;
  19193. defines["SHADOWS"] = true;
  19194. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19195. defines["SHADOWVSM" + lightIndex] = true;
  19196. }
  19197. if (shadowGenerator.usePoissonSampling) {
  19198. defines["SHADOWPCF" + lightIndex] = true;
  19199. }
  19200. }
  19201. }
  19202. lightIndex++;
  19203. if (lightIndex === maxSimultaneousLights)
  19204. break;
  19205. }
  19206. return needNormals;
  19207. };
  19208. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19209. var lightIndex = 0;
  19210. var depthValuesAlreadySet = false;
  19211. for (var index = 0; index < scene.lights.length; index++) {
  19212. var light = scene.lights[index];
  19213. if (!light.isEnabled()) {
  19214. continue;
  19215. }
  19216. if (!light.canAffectMesh(mesh)) {
  19217. continue;
  19218. }
  19219. if (light instanceof BABYLON.PointLight) {
  19220. // Point Light
  19221. light.transferToEffect(effect, "vLightData" + lightIndex);
  19222. }
  19223. else if (light instanceof BABYLON.DirectionalLight) {
  19224. // Directional Light
  19225. light.transferToEffect(effect, "vLightData" + lightIndex);
  19226. }
  19227. else if (light instanceof BABYLON.SpotLight) {
  19228. // Spot Light
  19229. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19230. }
  19231. else if (light instanceof BABYLON.HemisphericLight) {
  19232. // Hemispheric Light
  19233. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19234. }
  19235. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19236. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19237. if (defines["SPECULARTERM"]) {
  19238. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19239. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19240. }
  19241. // Shadows
  19242. if (scene.shadowsEnabled) {
  19243. var shadowGenerator = light.getShadowGenerator();
  19244. if (mesh.receiveShadows && shadowGenerator) {
  19245. if (!light.needCube()) {
  19246. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19247. }
  19248. else {
  19249. if (!depthValuesAlreadySet) {
  19250. depthValuesAlreadySet = true;
  19251. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19252. }
  19253. }
  19254. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19255. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19256. }
  19257. }
  19258. lightIndex++;
  19259. if (lightIndex === maxSimultaneousLights)
  19260. break;
  19261. }
  19262. };
  19263. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19264. if (this.isFrozen) {
  19265. if (this._wasPreviouslyReady) {
  19266. return true;
  19267. }
  19268. }
  19269. var scene = this.getScene();
  19270. if (!this.checkReadyOnEveryCall) {
  19271. if (this._renderId === scene.getRenderId()) {
  19272. if (this._checkCache(scene, mesh, useInstances)) {
  19273. return true;
  19274. }
  19275. }
  19276. }
  19277. var engine = scene.getEngine();
  19278. var needNormals = false;
  19279. var needUVs = false;
  19280. this._defines.reset();
  19281. // Textures
  19282. if (scene.texturesEnabled) {
  19283. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19284. if (!this.diffuseTexture.isReady()) {
  19285. return false;
  19286. }
  19287. else {
  19288. needUVs = true;
  19289. this._defines.DIFFUSE = true;
  19290. }
  19291. }
  19292. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19293. if (!this.ambientTexture.isReady()) {
  19294. return false;
  19295. }
  19296. else {
  19297. needUVs = true;
  19298. this._defines.AMBIENT = true;
  19299. }
  19300. }
  19301. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19302. if (!this.opacityTexture.isReady()) {
  19303. return false;
  19304. }
  19305. else {
  19306. needUVs = true;
  19307. this._defines.OPACITY = true;
  19308. if (this.opacityTexture.getAlphaFromRGB) {
  19309. this._defines.OPACITYRGB = true;
  19310. }
  19311. }
  19312. }
  19313. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19314. if (!this.reflectionTexture.isReady()) {
  19315. return false;
  19316. }
  19317. else {
  19318. needNormals = true;
  19319. this._defines.REFLECTION = true;
  19320. if (this.roughness > 0) {
  19321. this._defines.ROUGHNESS = true;
  19322. }
  19323. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19324. this._defines.INVERTCUBICMAP = true;
  19325. }
  19326. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19327. switch (this.reflectionTexture.coordinatesMode) {
  19328. case BABYLON.Texture.CUBIC_MODE:
  19329. case BABYLON.Texture.INVCUBIC_MODE:
  19330. this._defines.REFLECTIONMAP_CUBIC = true;
  19331. break;
  19332. case BABYLON.Texture.EXPLICIT_MODE:
  19333. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19334. break;
  19335. case BABYLON.Texture.PLANAR_MODE:
  19336. this._defines.REFLECTIONMAP_PLANAR = true;
  19337. break;
  19338. case BABYLON.Texture.PROJECTION_MODE:
  19339. this._defines.REFLECTIONMAP_PROJECTION = true;
  19340. break;
  19341. case BABYLON.Texture.SKYBOX_MODE:
  19342. this._defines.REFLECTIONMAP_SKYBOX = true;
  19343. break;
  19344. case BABYLON.Texture.SPHERICAL_MODE:
  19345. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19346. break;
  19347. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19348. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19349. break;
  19350. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19351. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19352. break;
  19353. }
  19354. }
  19355. }
  19356. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19357. if (!this.emissiveTexture.isReady()) {
  19358. return false;
  19359. }
  19360. else {
  19361. needUVs = true;
  19362. this._defines.EMISSIVE = true;
  19363. }
  19364. }
  19365. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19366. if (!this.lightmapTexture.isReady()) {
  19367. return false;
  19368. }
  19369. else {
  19370. needUVs = true;
  19371. this._defines.LIGHTMAP = true;
  19372. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19373. }
  19374. }
  19375. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19376. if (!this.specularTexture.isReady()) {
  19377. return false;
  19378. }
  19379. else {
  19380. needUVs = true;
  19381. this._defines.SPECULAR = true;
  19382. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19383. }
  19384. }
  19385. }
  19386. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19387. if (!this.bumpTexture.isReady()) {
  19388. return false;
  19389. }
  19390. else {
  19391. needUVs = true;
  19392. this._defines.BUMP = true;
  19393. }
  19394. }
  19395. // Effect
  19396. if (scene.clipPlane) {
  19397. this._defines.CLIPPLANE = true;
  19398. }
  19399. if (engine.getAlphaTesting()) {
  19400. this._defines.ALPHATEST = true;
  19401. }
  19402. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19403. this._defines.ALPHAFROMDIFFUSE = true;
  19404. }
  19405. if (this.useEmissiveAsIllumination) {
  19406. this._defines.EMISSIVEASILLUMINATION = true;
  19407. }
  19408. if (this.linkEmissiveWithDiffuse) {
  19409. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19410. }
  19411. if (this.useReflectionFresnelFromSpecular) {
  19412. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19413. }
  19414. if (this.useLogarithmicDepth) {
  19415. this._defines.LOGARITHMICDEPTH = true;
  19416. }
  19417. // Point size
  19418. if (this.pointsCloud || scene.forcePointsCloud) {
  19419. this._defines.POINTSIZE = true;
  19420. }
  19421. // Fog
  19422. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19423. this._defines.FOG = true;
  19424. }
  19425. if (scene.lightsEnabled && !this.disableLighting) {
  19426. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19427. }
  19428. if (StandardMaterial.FresnelEnabled) {
  19429. // Fresnel
  19430. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19431. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19432. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19433. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19434. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19435. this._defines.DIFFUSEFRESNEL = true;
  19436. }
  19437. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19438. this._defines.OPACITYFRESNEL = true;
  19439. }
  19440. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19441. this._defines.REFLECTIONFRESNEL = true;
  19442. }
  19443. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19444. this._defines.EMISSIVEFRESNEL = true;
  19445. }
  19446. needNormals = true;
  19447. this._defines.FRESNEL = true;
  19448. }
  19449. }
  19450. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19451. this._defines.SPECULAROVERALPHA = true;
  19452. }
  19453. // Attribs
  19454. if (mesh) {
  19455. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19456. this._defines.NORMAL = true;
  19457. }
  19458. if (needUVs) {
  19459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19460. this._defines.UV1 = true;
  19461. }
  19462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19463. this._defines.UV2 = true;
  19464. }
  19465. }
  19466. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19467. this._defines.VERTEXCOLOR = true;
  19468. if (mesh.hasVertexAlpha) {
  19469. this._defines.VERTEXALPHA = true;
  19470. }
  19471. }
  19472. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19473. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19474. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19475. }
  19476. // Instances
  19477. if (useInstances) {
  19478. this._defines.INSTANCES = true;
  19479. }
  19480. }
  19481. // Get correct effect
  19482. if (!this._defines.isEqual(this._cachedDefines)) {
  19483. this._defines.cloneTo(this._cachedDefines);
  19484. scene.resetCachedMaterial();
  19485. // Fallbacks
  19486. var fallbacks = new BABYLON.EffectFallbacks();
  19487. if (this._defines.REFLECTION) {
  19488. fallbacks.addFallback(0, "REFLECTION");
  19489. }
  19490. if (this._defines.SPECULAR) {
  19491. fallbacks.addFallback(0, "SPECULAR");
  19492. }
  19493. if (this._defines.BUMP) {
  19494. fallbacks.addFallback(0, "BUMP");
  19495. }
  19496. if (this._defines.SPECULAROVERALPHA) {
  19497. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19498. }
  19499. if (this._defines.FOG) {
  19500. fallbacks.addFallback(1, "FOG");
  19501. }
  19502. if (this._defines.POINTSIZE) {
  19503. fallbacks.addFallback(0, "POINTSIZE");
  19504. }
  19505. if (this._defines.LOGARITHMICDEPTH) {
  19506. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19507. }
  19508. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19509. if (!this._defines["LIGHT" + lightIndex]) {
  19510. continue;
  19511. }
  19512. if (lightIndex > 0) {
  19513. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19514. }
  19515. if (this._defines["SHADOW" + lightIndex]) {
  19516. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19517. }
  19518. if (this._defines["SHADOWPCF" + lightIndex]) {
  19519. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19520. }
  19521. if (this._defines["SHADOWVSM" + lightIndex]) {
  19522. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19523. }
  19524. }
  19525. if (this._defines.SPECULARTERM) {
  19526. fallbacks.addFallback(0, "SPECULARTERM");
  19527. }
  19528. if (this._defines.DIFFUSEFRESNEL) {
  19529. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19530. }
  19531. if (this._defines.OPACITYFRESNEL) {
  19532. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19533. }
  19534. if (this._defines.REFLECTIONFRESNEL) {
  19535. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19536. }
  19537. if (this._defines.EMISSIVEFRESNEL) {
  19538. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19539. }
  19540. if (this._defines.FRESNEL) {
  19541. fallbacks.addFallback(4, "FRESNEL");
  19542. }
  19543. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19544. fallbacks.addCPUSkinningFallback(0, mesh);
  19545. }
  19546. //Attributes
  19547. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19548. if (this._defines.NORMAL) {
  19549. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19550. }
  19551. if (this._defines.UV1) {
  19552. attribs.push(BABYLON.VertexBuffer.UVKind);
  19553. }
  19554. if (this._defines.UV2) {
  19555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19556. }
  19557. if (this._defines.VERTEXCOLOR) {
  19558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19559. }
  19560. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19563. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19566. }
  19567. }
  19568. if (this._defines.INSTANCES) {
  19569. attribs.push("world0");
  19570. attribs.push("world1");
  19571. attribs.push("world2");
  19572. attribs.push("world3");
  19573. }
  19574. // Legacy browser patch
  19575. var shaderName = "default";
  19576. if (!scene.getEngine().getCaps().standardDerivatives) {
  19577. shaderName = "legacydefault";
  19578. }
  19579. var join = this._defines.toString();
  19580. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19581. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19582. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19583. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19584. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19585. "vFogInfos", "vFogColor", "pointSize",
  19586. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19587. "mBones",
  19588. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19589. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19590. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19591. "logarithmicDepthConstant"
  19592. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19593. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19594. ], join, fallbacks, this.onCompiled, this.onError);
  19595. }
  19596. if (!this._effect.isReady()) {
  19597. return false;
  19598. }
  19599. this._renderId = scene.getRenderId();
  19600. this._wasPreviouslyReady = true;
  19601. if (mesh) {
  19602. if (!mesh._materialDefines) {
  19603. mesh._materialDefines = new StandardMaterialDefines();
  19604. }
  19605. this._defines.cloneTo(mesh._materialDefines);
  19606. }
  19607. return true;
  19608. };
  19609. StandardMaterial.prototype.unbind = function () {
  19610. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19611. this._effect.setTexture("reflection2DSampler", null);
  19612. }
  19613. _super.prototype.unbind.call(this);
  19614. };
  19615. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19616. this._effect.setMatrix("world", world);
  19617. };
  19618. StandardMaterial.prototype.bind = function (world, mesh) {
  19619. var scene = this.getScene();
  19620. // Matrices
  19621. this.bindOnlyWorldMatrix(world);
  19622. // Bones
  19623. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19624. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19625. }
  19626. if (scene.getCachedMaterial() !== this) {
  19627. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19628. if (StandardMaterial.FresnelEnabled) {
  19629. // Fresnel
  19630. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19631. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19632. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19633. }
  19634. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19635. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19636. }
  19637. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19638. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19639. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19640. }
  19641. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19642. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19643. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19644. }
  19645. }
  19646. // Textures
  19647. if (scene.texturesEnabled) {
  19648. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19649. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19650. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19651. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19652. }
  19653. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19654. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19655. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19656. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19657. }
  19658. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19659. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19660. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19661. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19662. }
  19663. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19664. if (this.reflectionTexture.isCube) {
  19665. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19666. }
  19667. else {
  19668. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19669. }
  19670. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19671. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19672. }
  19673. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19674. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19675. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19676. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19677. }
  19678. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19679. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19680. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19681. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19682. }
  19683. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19684. this._effect.setTexture("specularSampler", this.specularTexture);
  19685. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19686. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19687. }
  19688. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19689. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19690. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19691. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19692. }
  19693. }
  19694. // Clip plane
  19695. if (scene.clipPlane) {
  19696. var clipPlane = scene.clipPlane;
  19697. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19698. }
  19699. // Point size
  19700. if (this.pointsCloud) {
  19701. this._effect.setFloat("pointSize", this.pointSize);
  19702. }
  19703. // Colors
  19704. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19705. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19706. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19707. if (this._defines.SPECULARTERM) {
  19708. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19709. }
  19710. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19711. }
  19712. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  19713. // Diffuse
  19714. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19715. // Lights
  19716. if (scene.lightsEnabled && !this.disableLighting) {
  19717. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19718. }
  19719. // View
  19720. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19721. this._effect.setMatrix("view", scene.getViewMatrix());
  19722. }
  19723. // Fog
  19724. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19725. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19726. this._effect.setColor3("vFogColor", scene.fogColor);
  19727. }
  19728. // Log. depth
  19729. if (this._defines.LOGARITHMICDEPTH) {
  19730. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19731. }
  19732. }
  19733. _super.prototype.bind.call(this, world, mesh);
  19734. };
  19735. StandardMaterial.prototype.getAnimatables = function () {
  19736. var results = [];
  19737. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19738. results.push(this.diffuseTexture);
  19739. }
  19740. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19741. results.push(this.ambientTexture);
  19742. }
  19743. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19744. results.push(this.opacityTexture);
  19745. }
  19746. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19747. results.push(this.reflectionTexture);
  19748. }
  19749. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19750. results.push(this.emissiveTexture);
  19751. }
  19752. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19753. results.push(this.specularTexture);
  19754. }
  19755. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19756. results.push(this.bumpTexture);
  19757. }
  19758. return results;
  19759. };
  19760. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19761. if (this.diffuseTexture) {
  19762. this.diffuseTexture.dispose();
  19763. }
  19764. if (this.ambientTexture) {
  19765. this.ambientTexture.dispose();
  19766. }
  19767. if (this.opacityTexture) {
  19768. this.opacityTexture.dispose();
  19769. }
  19770. if (this.reflectionTexture) {
  19771. this.reflectionTexture.dispose();
  19772. }
  19773. if (this.emissiveTexture) {
  19774. this.emissiveTexture.dispose();
  19775. }
  19776. if (this.specularTexture) {
  19777. this.specularTexture.dispose();
  19778. }
  19779. if (this.bumpTexture) {
  19780. this.bumpTexture.dispose();
  19781. }
  19782. _super.prototype.dispose.call(this, forceDisposeEffect);
  19783. };
  19784. StandardMaterial.prototype.clone = function (name) {
  19785. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19786. // Base material
  19787. this.copyTo(newStandardMaterial);
  19788. // Standard material
  19789. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19790. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19791. }
  19792. if (this.ambientTexture && this.ambientTexture.clone) {
  19793. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19794. }
  19795. if (this.opacityTexture && this.opacityTexture.clone) {
  19796. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19797. }
  19798. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19799. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19800. }
  19801. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19802. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19803. }
  19804. if (this.specularTexture && this.specularTexture.clone) {
  19805. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19806. }
  19807. if (this.bumpTexture && this.bumpTexture.clone) {
  19808. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19809. }
  19810. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19811. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19812. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19813. }
  19814. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19815. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19816. newStandardMaterial.specularColor = this.specularColor.clone();
  19817. newStandardMaterial.specularPower = this.specularPower;
  19818. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19819. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19820. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19821. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19822. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19823. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19824. newStandardMaterial.roughness = this.roughness;
  19825. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19826. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19827. }
  19828. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19829. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19830. }
  19831. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19832. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19833. }
  19834. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19835. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19836. }
  19837. return newStandardMaterial;
  19838. };
  19839. StandardMaterial.prototype.serialize = function () {
  19840. var serializationObject = _super.prototype.serialize.call(this);
  19841. serializationObject.ambient = this.ambientColor.asArray();
  19842. serializationObject.diffuse = this.diffuseColor.asArray();
  19843. serializationObject.specular = this.specularColor.asArray();
  19844. serializationObject.specularPower = this.specularPower;
  19845. serializationObject.emissive = this.emissiveColor.asArray();
  19846. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19847. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19848. if (this.diffuseTexture) {
  19849. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19850. }
  19851. if (this.diffuseFresnelParameters) {
  19852. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19853. }
  19854. if (this.ambientTexture) {
  19855. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19856. }
  19857. if (this.opacityTexture) {
  19858. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19859. }
  19860. if (this.opacityFresnelParameters) {
  19861. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19862. }
  19863. if (this.reflectionTexture) {
  19864. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19865. }
  19866. if (this.reflectionFresnelParameters) {
  19867. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19868. }
  19869. if (this.emissiveTexture) {
  19870. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19871. }
  19872. if (this.lightmapTexture) {
  19873. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19874. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19875. }
  19876. if (this.emissiveFresnelParameters) {
  19877. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19878. }
  19879. if (this.specularTexture) {
  19880. serializationObject.specularTexture = this.specularTexture.serialize();
  19881. }
  19882. if (this.bumpTexture) {
  19883. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19884. }
  19885. return serializationObject;
  19886. };
  19887. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19888. var material = new StandardMaterial(source.name, scene);
  19889. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19890. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19891. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19892. material.specularPower = source.specularPower;
  19893. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19894. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19895. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19896. material.alpha = source.alpha;
  19897. material.id = source.id;
  19898. if (source.disableDepthWrite) {
  19899. material.disableDepthWrite = source.disableDepthWrite;
  19900. }
  19901. BABYLON.Tags.AddTagsTo(material, source.tags);
  19902. material.backFaceCulling = source.backFaceCulling;
  19903. material.wireframe = source.wireframe;
  19904. if (source.diffuseTexture) {
  19905. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19906. }
  19907. if (source.diffuseFresnelParameters) {
  19908. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19909. }
  19910. if (source.ambientTexture) {
  19911. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19912. }
  19913. if (source.opacityTexture) {
  19914. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19915. }
  19916. if (source.opacityFresnelParameters) {
  19917. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19918. }
  19919. if (source.reflectionTexture) {
  19920. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19921. }
  19922. if (source.reflectionFresnelParameters) {
  19923. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19924. }
  19925. if (source.emissiveTexture) {
  19926. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19927. }
  19928. if (source.lightmapTexture) {
  19929. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19930. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19931. }
  19932. if (source.emissiveFresnelParameters) {
  19933. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19934. }
  19935. if (source.specularTexture) {
  19936. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19937. }
  19938. if (source.bumpTexture) {
  19939. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19940. }
  19941. if (source.checkReadyOnlyOnce) {
  19942. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19943. }
  19944. return material;
  19945. };
  19946. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19947. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19948. // Statics
  19949. // Flags used to enable or disable a type of texture for all Standard Materials
  19950. StandardMaterial.DiffuseTextureEnabled = true;
  19951. StandardMaterial.AmbientTextureEnabled = true;
  19952. StandardMaterial.OpacityTextureEnabled = true;
  19953. StandardMaterial.ReflectionTextureEnabled = true;
  19954. StandardMaterial.EmissiveTextureEnabled = true;
  19955. StandardMaterial.SpecularTextureEnabled = true;
  19956. StandardMaterial.BumpTextureEnabled = true;
  19957. StandardMaterial.FresnelEnabled = true;
  19958. StandardMaterial.LightmapEnabled = true;
  19959. return StandardMaterial;
  19960. })(BABYLON.Material);
  19961. BABYLON.StandardMaterial = StandardMaterial;
  19962. })(BABYLON || (BABYLON = {}));
  19963. var BABYLON;
  19964. (function (BABYLON) {
  19965. var MultiMaterial = (function (_super) {
  19966. __extends(MultiMaterial, _super);
  19967. function MultiMaterial(name, scene) {
  19968. _super.call(this, name, scene, true);
  19969. this.subMaterials = new Array();
  19970. scene.multiMaterials.push(this);
  19971. }
  19972. // Properties
  19973. MultiMaterial.prototype.getSubMaterial = function (index) {
  19974. if (index < 0 || index >= this.subMaterials.length) {
  19975. return this.getScene().defaultMaterial;
  19976. }
  19977. return this.subMaterials[index];
  19978. };
  19979. // Methods
  19980. MultiMaterial.prototype.isReady = function (mesh) {
  19981. for (var index = 0; index < this.subMaterials.length; index++) {
  19982. var subMaterial = this.subMaterials[index];
  19983. if (subMaterial) {
  19984. if (!this.subMaterials[index].isReady(mesh)) {
  19985. return false;
  19986. }
  19987. }
  19988. }
  19989. return true;
  19990. };
  19991. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  19992. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19993. for (var index = 0; index < this.subMaterials.length; index++) {
  19994. var subMaterial = null;
  19995. if (cloneChildren) {
  19996. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  19997. }
  19998. else {
  19999. subMaterial = this.subMaterials[index];
  20000. }
  20001. newMultiMaterial.subMaterials.push(subMaterial);
  20002. }
  20003. return newMultiMaterial;
  20004. };
  20005. MultiMaterial.prototype.serialize = function () {
  20006. var serializationObject = {};
  20007. serializationObject.name = this.name;
  20008. serializationObject.id = this.id;
  20009. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20010. serializationObject.materials = [];
  20011. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20012. var subMat = this.subMaterials[matIndex];
  20013. if (subMat) {
  20014. serializationObject.materials.push(subMat.id);
  20015. }
  20016. else {
  20017. serializationObject.materials.push(null);
  20018. }
  20019. }
  20020. return serializationObject;
  20021. };
  20022. return MultiMaterial;
  20023. })(BABYLON.Material);
  20024. BABYLON.MultiMaterial = MultiMaterial;
  20025. })(BABYLON || (BABYLON = {}));
  20026. var BABYLON;
  20027. (function (BABYLON) {
  20028. var SceneLoader = (function () {
  20029. function SceneLoader() {
  20030. }
  20031. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20032. get: function () {
  20033. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20034. },
  20035. set: function (value) {
  20036. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20037. },
  20038. enumerable: true,
  20039. configurable: true
  20040. });
  20041. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20042. get: function () {
  20043. return SceneLoader._ShowLoadingScreen;
  20044. },
  20045. set: function (value) {
  20046. SceneLoader._ShowLoadingScreen = value;
  20047. },
  20048. enumerable: true,
  20049. configurable: true
  20050. });
  20051. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20052. var dotPosition = sceneFilename.lastIndexOf(".");
  20053. var queryStringPosition = sceneFilename.indexOf("?");
  20054. if (queryStringPosition === -1) {
  20055. queryStringPosition = sceneFilename.length;
  20056. }
  20057. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20058. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20059. var plugin = this._registeredPlugins[index];
  20060. if (plugin.extensions.indexOf(extension) !== -1) {
  20061. return plugin;
  20062. }
  20063. }
  20064. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20065. };
  20066. // Public functions
  20067. SceneLoader.RegisterPlugin = function (plugin) {
  20068. plugin.extensions = plugin.extensions.toLowerCase();
  20069. SceneLoader._registeredPlugins.push(plugin);
  20070. };
  20071. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20072. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20073. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20074. return;
  20075. }
  20076. var loadingToken = {};
  20077. scene._addPendingData(loadingToken);
  20078. var manifestChecked = function (success) {
  20079. scene.database = database;
  20080. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20081. var importMeshFromData = function (data) {
  20082. var meshes = [];
  20083. var particleSystems = [];
  20084. var skeletons = [];
  20085. try {
  20086. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20087. if (onerror) {
  20088. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20089. }
  20090. scene._removePendingData(loadingToken);
  20091. return;
  20092. }
  20093. }
  20094. catch (e) {
  20095. if (onerror) {
  20096. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20097. }
  20098. scene._removePendingData(loadingToken);
  20099. return;
  20100. }
  20101. if (onsuccess) {
  20102. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20103. onsuccess(meshes, particleSystems, skeletons);
  20104. scene._removePendingData(loadingToken);
  20105. }
  20106. };
  20107. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20108. // Direct load
  20109. importMeshFromData(sceneFilename.substr(5));
  20110. return;
  20111. }
  20112. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20113. importMeshFromData(data);
  20114. }, progressCallBack, database);
  20115. };
  20116. if (scene.getEngine().enableOfflineSupport) {
  20117. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20118. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20119. }
  20120. else {
  20121. manifestChecked(true);
  20122. }
  20123. };
  20124. /**
  20125. * Load a scene
  20126. * @param rootUrl a string that defines the root url for scene and resources
  20127. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20128. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20129. */
  20130. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20131. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20132. };
  20133. /**
  20134. * Append a scene
  20135. * @param rootUrl a string that defines the root url for scene and resources
  20136. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20137. * @param scene is the instance of BABYLON.Scene to append to
  20138. */
  20139. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20140. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20141. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20142. return;
  20143. }
  20144. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20145. var database;
  20146. var loadingToken = {};
  20147. scene._addPendingData(loadingToken);
  20148. if (SceneLoader.ShowLoadingScreen) {
  20149. scene.getEngine().displayLoadingUI();
  20150. }
  20151. var loadSceneFromData = function (data) {
  20152. scene.database = database;
  20153. if (!plugin.load(scene, data, rootUrl)) {
  20154. if (onerror) {
  20155. onerror(scene);
  20156. }
  20157. scene._removePendingData(loadingToken);
  20158. scene.getEngine().hideLoadingUI();
  20159. return;
  20160. }
  20161. if (onsuccess) {
  20162. onsuccess(scene);
  20163. }
  20164. scene._removePendingData(loadingToken);
  20165. if (SceneLoader.ShowLoadingScreen) {
  20166. scene.executeWhenReady(function () {
  20167. scene.getEngine().hideLoadingUI();
  20168. });
  20169. }
  20170. };
  20171. var manifestChecked = function (success) {
  20172. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20173. };
  20174. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20175. // Direct load
  20176. loadSceneFromData(sceneFilename.substr(5));
  20177. return;
  20178. }
  20179. if (rootUrl.indexOf("file:") === -1) {
  20180. if (scene.getEngine().enableOfflineSupport) {
  20181. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20182. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20183. }
  20184. else {
  20185. manifestChecked(true);
  20186. }
  20187. }
  20188. else {
  20189. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20190. }
  20191. };
  20192. // Flags
  20193. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20194. SceneLoader._ShowLoadingScreen = true;
  20195. // Members
  20196. SceneLoader._registeredPlugins = new Array();
  20197. return SceneLoader;
  20198. })();
  20199. BABYLON.SceneLoader = SceneLoader;
  20200. ;
  20201. })(BABYLON || (BABYLON = {}));
  20202. var BABYLON;
  20203. (function (BABYLON) {
  20204. var Internals;
  20205. (function (Internals) {
  20206. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20207. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20208. var parsedMaterial = parsedData.materials[index];
  20209. if (parsedMaterial.id === id) {
  20210. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20211. }
  20212. }
  20213. return null;
  20214. };
  20215. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20216. names = (names instanceof Array) ? names : [names];
  20217. for (var i in names) {
  20218. if (mesh.name === names[i]) {
  20219. hierarchyIds.push(mesh.id);
  20220. return true;
  20221. }
  20222. }
  20223. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20224. hierarchyIds.push(mesh.id);
  20225. return true;
  20226. }
  20227. return false;
  20228. };
  20229. BABYLON.SceneLoader.RegisterPlugin({
  20230. extensions: ".babylon",
  20231. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20232. var parsedData = JSON.parse(data);
  20233. var loadedSkeletonsIds = [];
  20234. var loadedMaterialsIds = [];
  20235. var hierarchyIds = [];
  20236. var index;
  20237. var cache;
  20238. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20239. var parsedMesh = parsedData.meshes[index];
  20240. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20241. if (meshesNames instanceof Array) {
  20242. // Remove found mesh name from list.
  20243. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20244. }
  20245. //Geometry?
  20246. if (parsedMesh.geometryId) {
  20247. //does the file contain geometries?
  20248. if (parsedData.geometries) {
  20249. //find the correct geometry and add it to the scene
  20250. var found = false;
  20251. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20252. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20253. return;
  20254. }
  20255. else {
  20256. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20257. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20258. switch (geometryType) {
  20259. case "boxes":
  20260. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20261. break;
  20262. case "spheres":
  20263. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20264. break;
  20265. case "cylinders":
  20266. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20267. break;
  20268. case "toruses":
  20269. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20270. break;
  20271. case "grounds":
  20272. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20273. break;
  20274. case "planes":
  20275. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20276. break;
  20277. case "torusKnots":
  20278. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20279. break;
  20280. case "vertexData":
  20281. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20282. break;
  20283. }
  20284. found = true;
  20285. }
  20286. });
  20287. }
  20288. });
  20289. if (!found) {
  20290. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20291. }
  20292. }
  20293. }
  20294. // Material ?
  20295. if (parsedMesh.materialId) {
  20296. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20297. if (!materialFound && parsedData.multiMaterials) {
  20298. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20299. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20300. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20301. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20302. var subMatId = parsedMultiMaterial.materials[matIndex];
  20303. loadedMaterialsIds.push(subMatId);
  20304. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20305. }
  20306. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20307. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20308. materialFound = true;
  20309. break;
  20310. }
  20311. }
  20312. }
  20313. if (!materialFound) {
  20314. loadedMaterialsIds.push(parsedMesh.materialId);
  20315. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20316. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20317. }
  20318. }
  20319. }
  20320. // Skeleton ?
  20321. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20322. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20323. if (!skeletonAlreadyLoaded) {
  20324. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20325. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20326. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20327. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20328. loadedSkeletonsIds.push(parsedSkeleton.id);
  20329. }
  20330. }
  20331. }
  20332. }
  20333. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20334. meshes.push(mesh);
  20335. }
  20336. }
  20337. // Connecting parents
  20338. var currentMesh;
  20339. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20340. currentMesh = scene.meshes[index];
  20341. if (currentMesh._waitingParentId) {
  20342. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20343. currentMesh._waitingParentId = undefined;
  20344. }
  20345. }
  20346. // freeze world matrix application
  20347. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20348. currentMesh = scene.meshes[index];
  20349. if (currentMesh._waitingFreezeWorldMatrix) {
  20350. currentMesh.freezeWorldMatrix();
  20351. currentMesh._waitingFreezeWorldMatrix = undefined;
  20352. }
  20353. }
  20354. // Particles
  20355. if (parsedData.particleSystems) {
  20356. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20357. var parsedParticleSystem = parsedData.particleSystems[index];
  20358. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20359. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20360. }
  20361. }
  20362. }
  20363. return true;
  20364. },
  20365. load: function (scene, data, rootUrl) {
  20366. var parsedData = JSON.parse(data);
  20367. // Scene
  20368. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20369. scene.autoClear = parsedData.autoClear;
  20370. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20371. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20372. if (parsedData.gravity) {
  20373. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20374. }
  20375. // Fog
  20376. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20377. scene.fogMode = parsedData.fogMode;
  20378. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20379. scene.fogStart = parsedData.fogStart;
  20380. scene.fogEnd = parsedData.fogEnd;
  20381. scene.fogDensity = parsedData.fogDensity;
  20382. }
  20383. //Physics
  20384. if (parsedData.physicsEnabled) {
  20385. var physicsPlugin;
  20386. if (parsedData.physicsEngine === "cannon") {
  20387. physicsPlugin = new BABYLON.CannonJSPlugin();
  20388. }
  20389. else if (parsedData.physicsEngine === "oimo") {
  20390. physicsPlugin = new BABYLON.OimoJSPlugin();
  20391. }
  20392. //else - default engine, which is currently oimo
  20393. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20394. scene.enablePhysics(physicsGravity, physicsPlugin);
  20395. }
  20396. //collisions, if defined. otherwise, default is true
  20397. if (parsedData.collisionsEnabled != undefined) {
  20398. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20399. }
  20400. scene.workerCollisions = !!parsedData.workerCollisions;
  20401. var index;
  20402. var cache;
  20403. // Lights
  20404. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20405. var parsedLight = parsedData.lights[index];
  20406. BABYLON.Light.Parse(parsedLight, scene);
  20407. }
  20408. // Materials
  20409. if (parsedData.materials) {
  20410. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20411. var parsedMaterial = parsedData.materials[index];
  20412. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20413. }
  20414. }
  20415. if (parsedData.multiMaterials) {
  20416. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20417. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20418. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20419. }
  20420. }
  20421. // Skeletons
  20422. if (parsedData.skeletons) {
  20423. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20424. var parsedSkeleton = parsedData.skeletons[index];
  20425. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20426. }
  20427. }
  20428. // Geometries
  20429. var geometries = parsedData.geometries;
  20430. if (geometries) {
  20431. // Boxes
  20432. var boxes = geometries.boxes;
  20433. if (boxes) {
  20434. for (index = 0, cache = boxes.length; index < cache; index++) {
  20435. var parsedBox = boxes[index];
  20436. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20437. }
  20438. }
  20439. // Spheres
  20440. var spheres = geometries.spheres;
  20441. if (spheres) {
  20442. for (index = 0, cache = spheres.length; index < cache; index++) {
  20443. var parsedSphere = spheres[index];
  20444. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20445. }
  20446. }
  20447. // Cylinders
  20448. var cylinders = geometries.cylinders;
  20449. if (cylinders) {
  20450. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20451. var parsedCylinder = cylinders[index];
  20452. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20453. }
  20454. }
  20455. // Toruses
  20456. var toruses = geometries.toruses;
  20457. if (toruses) {
  20458. for (index = 0, cache = toruses.length; index < cache; index++) {
  20459. var parsedTorus = toruses[index];
  20460. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20461. }
  20462. }
  20463. // Grounds
  20464. var grounds = geometries.grounds;
  20465. if (grounds) {
  20466. for (index = 0, cache = grounds.length; index < cache; index++) {
  20467. var parsedGround = grounds[index];
  20468. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20469. }
  20470. }
  20471. // Planes
  20472. var planes = geometries.planes;
  20473. if (planes) {
  20474. for (index = 0, cache = planes.length; index < cache; index++) {
  20475. var parsedPlane = planes[index];
  20476. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20477. }
  20478. }
  20479. // TorusKnots
  20480. var torusKnots = geometries.torusKnots;
  20481. if (torusKnots) {
  20482. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20483. var parsedTorusKnot = torusKnots[index];
  20484. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20485. }
  20486. }
  20487. // VertexData
  20488. var vertexData = geometries.vertexData;
  20489. if (vertexData) {
  20490. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20491. var parsedVertexData = vertexData[index];
  20492. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20493. }
  20494. }
  20495. }
  20496. // Meshes
  20497. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20498. var parsedMesh = parsedData.meshes[index];
  20499. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20500. }
  20501. // Cameras
  20502. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20503. var parsedCamera = parsedData.cameras[index];
  20504. BABYLON.Camera.Parse(parsedCamera, scene);
  20505. }
  20506. if (parsedData.activeCameraID) {
  20507. scene.setActiveCameraByID(parsedData.activeCameraID);
  20508. }
  20509. // Browsing all the graph to connect the dots
  20510. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20511. var camera = scene.cameras[index];
  20512. if (camera._waitingParentId) {
  20513. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20514. camera._waitingParentId = undefined;
  20515. }
  20516. }
  20517. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20518. var light = scene.lights[index];
  20519. if (light._waitingParentId) {
  20520. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20521. light._waitingParentId = undefined;
  20522. }
  20523. }
  20524. // Sounds
  20525. var loadedSounds = [];
  20526. var loadedSound;
  20527. if (BABYLON.AudioEngine && parsedData.sounds) {
  20528. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20529. var parsedSound = parsedData.sounds[index];
  20530. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20531. if (!parsedSound.url)
  20532. parsedSound.url = parsedSound.name;
  20533. if (!loadedSounds[parsedSound.url]) {
  20534. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20535. loadedSounds[parsedSound.url] = loadedSound;
  20536. }
  20537. else {
  20538. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20539. }
  20540. }
  20541. else {
  20542. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20543. }
  20544. }
  20545. }
  20546. loadedSounds = [];
  20547. // Connect parents & children and parse actions
  20548. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20549. var mesh = scene.meshes[index];
  20550. if (mesh._waitingParentId) {
  20551. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20552. mesh._waitingParentId = undefined;
  20553. }
  20554. if (mesh._waitingActions) {
  20555. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20556. mesh._waitingActions = undefined;
  20557. }
  20558. }
  20559. // freeze world matrix application
  20560. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20561. var currentMesh = scene.meshes[index];
  20562. if (currentMesh._waitingFreezeWorldMatrix) {
  20563. currentMesh.freezeWorldMatrix();
  20564. currentMesh._waitingFreezeWorldMatrix = undefined;
  20565. }
  20566. }
  20567. // Particles Systems
  20568. if (parsedData.particleSystems) {
  20569. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20570. var parsedParticleSystem = parsedData.particleSystems[index];
  20571. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20572. }
  20573. }
  20574. // Lens flares
  20575. if (parsedData.lensFlareSystems) {
  20576. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20577. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20578. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20579. }
  20580. }
  20581. // Shadows
  20582. if (parsedData.shadowGenerators) {
  20583. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20584. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20585. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20586. }
  20587. }
  20588. // Actions (scene)
  20589. if (parsedData.actions) {
  20590. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20591. }
  20592. // Finish
  20593. return true;
  20594. }
  20595. });
  20596. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20597. })(BABYLON || (BABYLON = {}));
  20598. var BABYLON;
  20599. (function (BABYLON) {
  20600. var SpriteManager = (function () {
  20601. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20603. this.name = name;
  20604. this.cellSize = cellSize;
  20605. this.sprites = new Array();
  20606. this.renderingGroupId = 0;
  20607. this.layerMask = 0x0FFFFFFF;
  20608. this.fogEnabled = true;
  20609. this.isPickable = false;
  20610. this._vertexDeclaration = [4, 4, 4, 4];
  20611. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20612. this._capacity = capacity;
  20613. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20614. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20615. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20616. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20617. this._scene = scene;
  20618. this._scene.spriteManagers.push(this);
  20619. // VBO
  20620. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20621. var indices = [];
  20622. var index = 0;
  20623. for (var count = 0; count < capacity; count++) {
  20624. indices.push(index);
  20625. indices.push(index + 1);
  20626. indices.push(index + 2);
  20627. indices.push(index);
  20628. indices.push(index + 2);
  20629. indices.push(index + 3);
  20630. index += 4;
  20631. }
  20632. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20633. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20634. // Effects
  20635. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20636. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20637. }
  20638. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20639. var arrayOffset = index * 16;
  20640. if (offsetX === 0)
  20641. offsetX = this._epsilon;
  20642. else if (offsetX === 1)
  20643. offsetX = 1 - this._epsilon;
  20644. if (offsetY === 0)
  20645. offsetY = this._epsilon;
  20646. else if (offsetY === 1)
  20647. offsetY = 1 - this._epsilon;
  20648. this._vertices[arrayOffset] = sprite.position.x;
  20649. this._vertices[arrayOffset + 1] = sprite.position.y;
  20650. this._vertices[arrayOffset + 2] = sprite.position.z;
  20651. this._vertices[arrayOffset + 3] = sprite.angle;
  20652. this._vertices[arrayOffset + 4] = sprite.width;
  20653. this._vertices[arrayOffset + 5] = sprite.height;
  20654. this._vertices[arrayOffset + 6] = offsetX;
  20655. this._vertices[arrayOffset + 7] = offsetY;
  20656. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20657. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20658. var offset = (sprite.cellIndex / rowSize) >> 0;
  20659. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20660. this._vertices[arrayOffset + 11] = offset;
  20661. // Color
  20662. this._vertices[arrayOffset + 12] = sprite.color.r;
  20663. this._vertices[arrayOffset + 13] = sprite.color.g;
  20664. this._vertices[arrayOffset + 14] = sprite.color.b;
  20665. this._vertices[arrayOffset + 15] = sprite.color.a;
  20666. };
  20667. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20668. var count = Math.min(this._capacity, this.sprites.length);
  20669. var min = BABYLON.Vector3.Zero();
  20670. var max = BABYLON.Vector3.Zero();
  20671. var distance = Number.MAX_VALUE;
  20672. var currentSprite;
  20673. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20674. var cameraView = camera.getViewMatrix();
  20675. for (var index = 0; index < count; index++) {
  20676. var sprite = this.sprites[index];
  20677. if (!sprite) {
  20678. continue;
  20679. }
  20680. if (predicate) {
  20681. if (!predicate(sprite)) {
  20682. continue;
  20683. }
  20684. }
  20685. else if (!sprite.isPickable) {
  20686. continue;
  20687. }
  20688. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20689. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20690. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20691. if (ray.intersectsBoxMinMax(min, max)) {
  20692. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20693. if (distance > currentDistance) {
  20694. distance = currentDistance;
  20695. currentSprite = sprite;
  20696. if (fastCheck) {
  20697. break;
  20698. }
  20699. }
  20700. }
  20701. }
  20702. if (currentSprite) {
  20703. var result = new BABYLON.PickingInfo();
  20704. result.hit = true;
  20705. result.pickedSprite = currentSprite;
  20706. result.distance = distance;
  20707. return result;
  20708. }
  20709. return null;
  20710. };
  20711. SpriteManager.prototype.render = function () {
  20712. // Check
  20713. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20714. return;
  20715. var engine = this._scene.getEngine();
  20716. var baseSize = this._spriteTexture.getBaseSize();
  20717. // Sprites
  20718. var deltaTime = engine.getDeltaTime();
  20719. var max = Math.min(this._capacity, this.sprites.length);
  20720. var rowSize = baseSize.width / this.cellSize;
  20721. var offset = 0;
  20722. for (var index = 0; index < max; index++) {
  20723. var sprite = this.sprites[index];
  20724. if (!sprite) {
  20725. continue;
  20726. }
  20727. sprite._animate(deltaTime);
  20728. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20729. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20730. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20731. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20732. }
  20733. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20734. // Render
  20735. var effect = this._effectBase;
  20736. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20737. effect = this._effectFog;
  20738. }
  20739. engine.enableEffect(effect);
  20740. var viewMatrix = this._scene.getViewMatrix();
  20741. effect.setTexture("diffuseSampler", this._spriteTexture);
  20742. effect.setMatrix("view", viewMatrix);
  20743. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20744. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20745. // Fog
  20746. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20747. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20748. effect.setColor3("vFogColor", this._scene.fogColor);
  20749. }
  20750. // VBOs
  20751. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20752. // Draw order
  20753. engine.setDepthFunctionToLessOrEqual();
  20754. effect.setBool("alphaTest", true);
  20755. engine.setColorWrite(false);
  20756. engine.draw(true, 0, max * 6);
  20757. engine.setColorWrite(true);
  20758. effect.setBool("alphaTest", false);
  20759. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20760. engine.draw(true, 0, max * 6);
  20761. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20762. };
  20763. SpriteManager.prototype.dispose = function () {
  20764. if (this._vertexBuffer) {
  20765. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20766. this._vertexBuffer = null;
  20767. }
  20768. if (this._indexBuffer) {
  20769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20770. this._indexBuffer = null;
  20771. }
  20772. if (this._spriteTexture) {
  20773. this._spriteTexture.dispose();
  20774. this._spriteTexture = null;
  20775. }
  20776. // Remove from scene
  20777. var index = this._scene.spriteManagers.indexOf(this);
  20778. this._scene.spriteManagers.splice(index, 1);
  20779. // Callback
  20780. if (this.onDispose) {
  20781. this.onDispose();
  20782. }
  20783. };
  20784. return SpriteManager;
  20785. })();
  20786. BABYLON.SpriteManager = SpriteManager;
  20787. })(BABYLON || (BABYLON = {}));
  20788. var BABYLON;
  20789. (function (BABYLON) {
  20790. var Sprite = (function () {
  20791. function Sprite(name, manager) {
  20792. this.name = name;
  20793. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20794. this.width = 1.0;
  20795. this.height = 1.0;
  20796. this.angle = 0;
  20797. this.cellIndex = 0;
  20798. this.invertU = 0;
  20799. this.invertV = 0;
  20800. this.animations = new Array();
  20801. this.isPickable = false;
  20802. this._animationStarted = false;
  20803. this._loopAnimation = false;
  20804. this._fromIndex = 0;
  20805. this._toIndex = 0;
  20806. this._delay = 0;
  20807. this._direction = 1;
  20808. this._frameCount = 0;
  20809. this._time = 0;
  20810. this._manager = manager;
  20811. this._manager.sprites.push(this);
  20812. this.position = BABYLON.Vector3.Zero();
  20813. }
  20814. Object.defineProperty(Sprite.prototype, "size", {
  20815. get: function () {
  20816. return this.width;
  20817. },
  20818. set: function (value) {
  20819. this.width = value;
  20820. this.height = value;
  20821. },
  20822. enumerable: true,
  20823. configurable: true
  20824. });
  20825. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20826. this._fromIndex = from;
  20827. this._toIndex = to;
  20828. this._loopAnimation = loop;
  20829. this._delay = delay;
  20830. this._animationStarted = true;
  20831. this._direction = from < to ? 1 : -1;
  20832. this.cellIndex = from;
  20833. this._time = 0;
  20834. };
  20835. Sprite.prototype.stopAnimation = function () {
  20836. this._animationStarted = false;
  20837. };
  20838. Sprite.prototype._animate = function (deltaTime) {
  20839. if (!this._animationStarted)
  20840. return;
  20841. this._time += deltaTime;
  20842. if (this._time > this._delay) {
  20843. this._time = this._time % this._delay;
  20844. this.cellIndex += this._direction;
  20845. if (this.cellIndex == this._toIndex) {
  20846. if (this._loopAnimation) {
  20847. this.cellIndex = this._fromIndex;
  20848. }
  20849. else {
  20850. this._animationStarted = false;
  20851. if (this.disposeWhenFinishedAnimating) {
  20852. this.dispose();
  20853. }
  20854. }
  20855. }
  20856. }
  20857. };
  20858. Sprite.prototype.dispose = function () {
  20859. for (var i = 0; i < this._manager.sprites.length; i++) {
  20860. if (this._manager.sprites[i] == this) {
  20861. this._manager.sprites.splice(i, 1);
  20862. }
  20863. }
  20864. };
  20865. return Sprite;
  20866. })();
  20867. BABYLON.Sprite = Sprite;
  20868. })(BABYLON || (BABYLON = {}));
  20869. var BABYLON;
  20870. (function (BABYLON) {
  20871. var Layer = (function () {
  20872. function Layer(name, imgUrl, scene, isBackground, color) {
  20873. this.name = name;
  20874. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20875. this._vertexDeclaration = [2];
  20876. this._vertexStrideSize = 2 * 4;
  20877. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20878. this.isBackground = isBackground === undefined ? true : isBackground;
  20879. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20880. this._scene = scene;
  20881. this._scene.layers.push(this);
  20882. // VBO
  20883. var vertices = [];
  20884. vertices.push(1, 1);
  20885. vertices.push(-1, 1);
  20886. vertices.push(-1, -1);
  20887. vertices.push(1, -1);
  20888. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20889. // Indices
  20890. var indices = [];
  20891. indices.push(0);
  20892. indices.push(1);
  20893. indices.push(2);
  20894. indices.push(0);
  20895. indices.push(2);
  20896. indices.push(3);
  20897. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20898. // Effects
  20899. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20900. }
  20901. Layer.prototype.render = function () {
  20902. // Check
  20903. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20904. return;
  20905. var engine = this._scene.getEngine();
  20906. // Render
  20907. engine.enableEffect(this._effect);
  20908. engine.setState(false);
  20909. // Texture
  20910. this._effect.setTexture("textureSampler", this.texture);
  20911. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20912. // Color
  20913. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20914. // VBOs
  20915. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20916. // Draw order
  20917. engine.setAlphaMode(this.alphaBlendingMode);
  20918. engine.draw(true, 0, 6);
  20919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20920. };
  20921. Layer.prototype.dispose = function () {
  20922. if (this._vertexBuffer) {
  20923. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20924. this._vertexBuffer = null;
  20925. }
  20926. if (this._indexBuffer) {
  20927. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20928. this._indexBuffer = null;
  20929. }
  20930. if (this.texture) {
  20931. this.texture.dispose();
  20932. this.texture = null;
  20933. }
  20934. // Remove from scene
  20935. var index = this._scene.layers.indexOf(this);
  20936. this._scene.layers.splice(index, 1);
  20937. // Callback
  20938. if (this.onDispose) {
  20939. this.onDispose();
  20940. }
  20941. };
  20942. return Layer;
  20943. })();
  20944. BABYLON.Layer = Layer;
  20945. })(BABYLON || (BABYLON = {}));
  20946. var BABYLON;
  20947. (function (BABYLON) {
  20948. var Particle = (function () {
  20949. function Particle() {
  20950. this.position = BABYLON.Vector3.Zero();
  20951. this.direction = BABYLON.Vector3.Zero();
  20952. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20953. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20954. this.lifeTime = 1.0;
  20955. this.age = 0;
  20956. this.size = 0;
  20957. this.angle = 0;
  20958. this.angularSpeed = 0;
  20959. }
  20960. Particle.prototype.copyTo = function (other) {
  20961. other.position.copyFrom(this.position);
  20962. other.direction.copyFrom(this.direction);
  20963. other.color.copyFrom(this.color);
  20964. other.colorStep.copyFrom(this.colorStep);
  20965. other.lifeTime = this.lifeTime;
  20966. other.age = this.age;
  20967. other.size = this.size;
  20968. other.angle = this.angle;
  20969. other.angularSpeed = this.angularSpeed;
  20970. };
  20971. return Particle;
  20972. })();
  20973. BABYLON.Particle = Particle;
  20974. })(BABYLON || (BABYLON = {}));
  20975. var BABYLON;
  20976. (function (BABYLON) {
  20977. var randomNumber = function (min, max) {
  20978. if (min === max) {
  20979. return (min);
  20980. }
  20981. var random = Math.random();
  20982. return ((random * (max - min)) + min);
  20983. };
  20984. var ParticleSystem = (function () {
  20985. function ParticleSystem(name, capacity, scene, customEffect) {
  20986. var _this = this;
  20987. this.name = name;
  20988. this.renderingGroupId = 0;
  20989. this.emitter = null;
  20990. this.emitRate = 10;
  20991. this.manualEmitCount = -1;
  20992. this.updateSpeed = 0.01;
  20993. this.targetStopDuration = 0;
  20994. this.disposeOnStop = false;
  20995. this.minEmitPower = 1;
  20996. this.maxEmitPower = 1;
  20997. this.minLifeTime = 1;
  20998. this.maxLifeTime = 1;
  20999. this.minSize = 1;
  21000. this.maxSize = 1;
  21001. this.minAngularSpeed = 0;
  21002. this.maxAngularSpeed = 0;
  21003. this.layerMask = 0x0FFFFFFF;
  21004. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21005. this.forceDepthWrite = false;
  21006. this.gravity = BABYLON.Vector3.Zero();
  21007. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21008. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21009. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21010. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21011. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21012. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21013. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21014. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21015. this.particles = new Array();
  21016. this._vertexDeclaration = [3, 4, 4];
  21017. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21018. this._stockParticles = new Array();
  21019. this._newPartsExcess = 0;
  21020. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21021. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21022. this._scaledDirection = BABYLON.Vector3.Zero();
  21023. this._scaledGravity = BABYLON.Vector3.Zero();
  21024. this._currentRenderId = -1;
  21025. this._started = false;
  21026. this._stopped = false;
  21027. this._actualFrame = 0;
  21028. this.id = name;
  21029. this._capacity = capacity;
  21030. this._scene = scene;
  21031. this._customEffect = customEffect;
  21032. scene.particleSystems.push(this);
  21033. // VBO
  21034. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21035. var indices = [];
  21036. var index = 0;
  21037. for (var count = 0; count < capacity; count++) {
  21038. indices.push(index);
  21039. indices.push(index + 1);
  21040. indices.push(index + 2);
  21041. indices.push(index);
  21042. indices.push(index + 2);
  21043. indices.push(index + 3);
  21044. index += 4;
  21045. }
  21046. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21047. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21048. // Default behaviors
  21049. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21050. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21051. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21052. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21053. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21054. };
  21055. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21056. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21057. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21058. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21059. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21060. };
  21061. this.updateFunction = function (particles) {
  21062. for (var index = 0; index < particles.length; index++) {
  21063. var particle = particles[index];
  21064. particle.age += _this._scaledUpdateSpeed;
  21065. if (particle.age >= particle.lifeTime) {
  21066. _this.recycleParticle(particle);
  21067. index--;
  21068. continue;
  21069. }
  21070. else {
  21071. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21072. particle.color.addInPlace(_this._scaledColorStep);
  21073. if (particle.color.a < 0)
  21074. particle.color.a = 0;
  21075. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21076. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21077. particle.position.addInPlace(_this._scaledDirection);
  21078. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21079. particle.direction.addInPlace(_this._scaledGravity);
  21080. }
  21081. }
  21082. };
  21083. }
  21084. ParticleSystem.prototype.recycleParticle = function (particle) {
  21085. var lastParticle = this.particles.pop();
  21086. if (lastParticle !== particle) {
  21087. lastParticle.copyTo(particle);
  21088. this._stockParticles.push(lastParticle);
  21089. }
  21090. };
  21091. ParticleSystem.prototype.getCapacity = function () {
  21092. return this._capacity;
  21093. };
  21094. ParticleSystem.prototype.isAlive = function () {
  21095. return this._alive;
  21096. };
  21097. ParticleSystem.prototype.isStarted = function () {
  21098. return this._started;
  21099. };
  21100. ParticleSystem.prototype.start = function () {
  21101. this._started = true;
  21102. this._stopped = false;
  21103. this._actualFrame = 0;
  21104. };
  21105. ParticleSystem.prototype.stop = function () {
  21106. this._stopped = true;
  21107. };
  21108. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21109. var offset = index * 11;
  21110. this._vertices[offset] = particle.position.x;
  21111. this._vertices[offset + 1] = particle.position.y;
  21112. this._vertices[offset + 2] = particle.position.z;
  21113. this._vertices[offset + 3] = particle.color.r;
  21114. this._vertices[offset + 4] = particle.color.g;
  21115. this._vertices[offset + 5] = particle.color.b;
  21116. this._vertices[offset + 6] = particle.color.a;
  21117. this._vertices[offset + 7] = particle.angle;
  21118. this._vertices[offset + 8] = particle.size;
  21119. this._vertices[offset + 9] = offsetX;
  21120. this._vertices[offset + 10] = offsetY;
  21121. };
  21122. ParticleSystem.prototype._update = function (newParticles) {
  21123. // Update current
  21124. this._alive = this.particles.length > 0;
  21125. this.updateFunction(this.particles);
  21126. // Add new ones
  21127. var worldMatrix;
  21128. if (this.emitter.position) {
  21129. worldMatrix = this.emitter.getWorldMatrix();
  21130. }
  21131. else {
  21132. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21133. }
  21134. var particle;
  21135. for (var index = 0; index < newParticles; index++) {
  21136. if (this.particles.length === this._capacity) {
  21137. break;
  21138. }
  21139. if (this._stockParticles.length !== 0) {
  21140. particle = this._stockParticles.pop();
  21141. particle.age = 0;
  21142. }
  21143. else {
  21144. particle = new BABYLON.Particle();
  21145. }
  21146. this.particles.push(particle);
  21147. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21148. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21149. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21150. particle.size = randomNumber(this.minSize, this.maxSize);
  21151. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21152. this.startPositionFunction(worldMatrix, particle.position, particle);
  21153. var step = randomNumber(0, 1.0);
  21154. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21155. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21156. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21157. }
  21158. };
  21159. ParticleSystem.prototype._getEffect = function () {
  21160. if (this._customEffect) {
  21161. return this._customEffect;
  21162. }
  21163. ;
  21164. var defines = [];
  21165. if (this._scene.clipPlane) {
  21166. defines.push("#define CLIPPLANE");
  21167. }
  21168. // Effect
  21169. var join = defines.join("\n");
  21170. if (this._cachedDefines !== join) {
  21171. this._cachedDefines = join;
  21172. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21173. }
  21174. return this._effect;
  21175. };
  21176. ParticleSystem.prototype.animate = function () {
  21177. if (!this._started)
  21178. return;
  21179. var effect = this._getEffect();
  21180. // Check
  21181. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21182. return;
  21183. if (this._currentRenderId === this._scene.getRenderId()) {
  21184. return;
  21185. }
  21186. this._currentRenderId = this._scene.getRenderId();
  21187. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21188. // determine the number of particles we need to create
  21189. var newParticles;
  21190. if (this.manualEmitCount > -1) {
  21191. newParticles = this.manualEmitCount;
  21192. this._newPartsExcess = 0;
  21193. this.manualEmitCount = 0;
  21194. }
  21195. else {
  21196. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21197. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21198. }
  21199. if (this._newPartsExcess > 1.0) {
  21200. newParticles += this._newPartsExcess >> 0;
  21201. this._newPartsExcess -= this._newPartsExcess >> 0;
  21202. }
  21203. this._alive = false;
  21204. if (!this._stopped) {
  21205. this._actualFrame += this._scaledUpdateSpeed;
  21206. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21207. this.stop();
  21208. }
  21209. else {
  21210. newParticles = 0;
  21211. }
  21212. this._update(newParticles);
  21213. // Stopped?
  21214. if (this._stopped) {
  21215. if (!this._alive) {
  21216. this._started = false;
  21217. if (this.disposeOnStop) {
  21218. this._scene._toBeDisposed.push(this);
  21219. }
  21220. }
  21221. }
  21222. // Update VBO
  21223. var offset = 0;
  21224. for (var index = 0; index < this.particles.length; index++) {
  21225. var particle = this.particles[index];
  21226. this._appendParticleVertex(offset++, particle, 0, 0);
  21227. this._appendParticleVertex(offset++, particle, 1, 0);
  21228. this._appendParticleVertex(offset++, particle, 1, 1);
  21229. this._appendParticleVertex(offset++, particle, 0, 1);
  21230. }
  21231. var engine = this._scene.getEngine();
  21232. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21233. };
  21234. ParticleSystem.prototype.render = function () {
  21235. var effect = this._getEffect();
  21236. // Check
  21237. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21238. return 0;
  21239. var engine = this._scene.getEngine();
  21240. // Render
  21241. engine.enableEffect(effect);
  21242. engine.setState(false);
  21243. var viewMatrix = this._scene.getViewMatrix();
  21244. effect.setTexture("diffuseSampler", this.particleTexture);
  21245. effect.setMatrix("view", viewMatrix);
  21246. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21247. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21248. if (this._scene.clipPlane) {
  21249. var clipPlane = this._scene.clipPlane;
  21250. var invView = viewMatrix.clone();
  21251. invView.invert();
  21252. effect.setMatrix("invView", invView);
  21253. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21254. }
  21255. // VBOs
  21256. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21257. // Draw order
  21258. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21259. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21260. }
  21261. else {
  21262. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21263. }
  21264. if (this.forceDepthWrite) {
  21265. engine.setDepthWrite(true);
  21266. }
  21267. engine.draw(true, 0, this.particles.length * 6);
  21268. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21269. return this.particles.length;
  21270. };
  21271. ParticleSystem.prototype.dispose = function () {
  21272. if (this._vertexBuffer) {
  21273. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21274. this._vertexBuffer = null;
  21275. }
  21276. if (this._indexBuffer) {
  21277. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21278. this._indexBuffer = null;
  21279. }
  21280. if (this.particleTexture) {
  21281. this.particleTexture.dispose();
  21282. this.particleTexture = null;
  21283. }
  21284. // Remove from scene
  21285. var index = this._scene.particleSystems.indexOf(this);
  21286. this._scene.particleSystems.splice(index, 1);
  21287. // Callback
  21288. if (this.onDispose) {
  21289. this.onDispose();
  21290. }
  21291. };
  21292. // Clone
  21293. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21294. var result = new ParticleSystem(name, this._capacity, this._scene);
  21295. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21296. if (newEmitter === undefined) {
  21297. newEmitter = this.emitter;
  21298. }
  21299. result.emitter = newEmitter;
  21300. if (this.particleTexture) {
  21301. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21302. }
  21303. result.start();
  21304. return result;
  21305. };
  21306. ParticleSystem.prototype.serialize = function () {
  21307. var serializationObject = {};
  21308. serializationObject.name = this.name;
  21309. if (this.emitter.position) {
  21310. serializationObject.emitterId = this.emitter.id;
  21311. }
  21312. else {
  21313. serializationObject.emitter = this.emitter.asArray();
  21314. ;
  21315. }
  21316. serializationObject.capacity = this.getCapacity();
  21317. if (this.particleTexture) {
  21318. serializationObject.textureName = this.particleTexture.name;
  21319. }
  21320. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21321. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21322. serializationObject.minSize = this.minSize;
  21323. serializationObject.maxSize = this.maxSize;
  21324. serializationObject.minEmitPower = this.minEmitPower;
  21325. serializationObject.maxEmitPower = this.maxEmitPower;
  21326. serializationObject.minLifeTime = this.minLifeTime;
  21327. serializationObject.maxLifeTime = this.maxLifeTime;
  21328. serializationObject.emitRate = this.emitRate;
  21329. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21330. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21331. serializationObject.gravity = this.gravity.asArray();
  21332. serializationObject.direction1 = this.direction1.asArray();
  21333. serializationObject.direction2 = this.direction2.asArray();
  21334. serializationObject.color1 = this.color1.asArray();
  21335. serializationObject.color2 = this.color2.asArray();
  21336. serializationObject.colorDead = this.colorDead.asArray();
  21337. serializationObject.updateSpeed = this.updateSpeed;
  21338. serializationObject.targetStopDuration = this.targetStopDuration;
  21339. serializationObject.textureMask = this.textureMask.asArray();
  21340. serializationObject.blendMode = this.blendMode;
  21341. return serializationObject;
  21342. };
  21343. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21344. var name = parsedParticleSystem.name;
  21345. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21346. if (parsedParticleSystem.textureName) {
  21347. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21348. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21349. }
  21350. if (parsedParticleSystem.emitterId) {
  21351. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21352. }
  21353. else {
  21354. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21355. }
  21356. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21357. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21358. particleSystem.minSize = parsedParticleSystem.minSize;
  21359. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21360. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21361. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21362. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21363. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21364. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21365. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21366. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21367. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21368. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21369. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21370. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21371. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21372. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21373. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21374. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21375. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21376. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21377. particleSystem.start();
  21378. return particleSystem;
  21379. };
  21380. // Statics
  21381. ParticleSystem.BLENDMODE_ONEONE = 0;
  21382. ParticleSystem.BLENDMODE_STANDARD = 1;
  21383. return ParticleSystem;
  21384. })();
  21385. BABYLON.ParticleSystem = ParticleSystem;
  21386. })(BABYLON || (BABYLON = {}));
  21387. var BABYLON;
  21388. (function (BABYLON) {
  21389. var AnimationRange = (function () {
  21390. function AnimationRange(name, from, to) {
  21391. this.name = name;
  21392. this.from = from;
  21393. this.to = to;
  21394. }
  21395. return AnimationRange;
  21396. })();
  21397. BABYLON.AnimationRange = AnimationRange;
  21398. /**
  21399. * Composed of a frame, and an action function
  21400. */
  21401. var AnimationEvent = (function () {
  21402. function AnimationEvent(frame, action, onlyOnce) {
  21403. this.frame = frame;
  21404. this.action = action;
  21405. this.onlyOnce = onlyOnce;
  21406. this.isDone = false;
  21407. }
  21408. return AnimationEvent;
  21409. })();
  21410. BABYLON.AnimationEvent = AnimationEvent;
  21411. var Animation = (function () {
  21412. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21413. this.name = name;
  21414. this.targetProperty = targetProperty;
  21415. this.framePerSecond = framePerSecond;
  21416. this.dataType = dataType;
  21417. this.loopMode = loopMode;
  21418. this._offsetsCache = {};
  21419. this._highLimitsCache = {};
  21420. this._stopped = false;
  21421. // The set of event that will be linked to this animation
  21422. this._events = new Array();
  21423. this.allowMatricesInterpolation = false;
  21424. this._ranges = {};
  21425. this.targetPropertyPath = targetProperty.split(".");
  21426. this.dataType = dataType;
  21427. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21428. }
  21429. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21430. var dataType = undefined;
  21431. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21432. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21433. }
  21434. else if (from instanceof BABYLON.Quaternion) {
  21435. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21436. }
  21437. else if (from instanceof BABYLON.Vector3) {
  21438. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21439. }
  21440. else if (from instanceof BABYLON.Vector2) {
  21441. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21442. }
  21443. else if (from instanceof BABYLON.Color3) {
  21444. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21445. }
  21446. if (dataType == undefined) {
  21447. return null;
  21448. }
  21449. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21450. var keys = [];
  21451. keys.push({ frame: 0, value: from });
  21452. keys.push({ frame: totalFrame, value: to });
  21453. animation.setKeys(keys);
  21454. if (easingFunction !== undefined) {
  21455. animation.setEasingFunction(easingFunction);
  21456. }
  21457. return animation;
  21458. };
  21459. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21460. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21461. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21462. };
  21463. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21464. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21465. node.animations.push(animation);
  21466. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21467. };
  21468. // Methods
  21469. /**
  21470. * Add an event to this animation.
  21471. */
  21472. Animation.prototype.addEvent = function (event) {
  21473. this._events.push(event);
  21474. };
  21475. /**
  21476. * Remove all events found at the given frame
  21477. * @param frame
  21478. */
  21479. Animation.prototype.removeEvents = function (frame) {
  21480. for (var index = 0; index < this._events.length; index++) {
  21481. if (this._events[index].frame === frame) {
  21482. this._events.splice(index, 1);
  21483. index--;
  21484. }
  21485. }
  21486. };
  21487. Animation.prototype.createRange = function (name, from, to) {
  21488. // check name not already in use; could happen for bones after serialized
  21489. if (!this._ranges[name]) {
  21490. this._ranges[name] = new AnimationRange(name, from, to);
  21491. }
  21492. };
  21493. Animation.prototype.deleteRange = function (name, deleteFrames) {
  21494. if (deleteFrames === void 0) { deleteFrames = true; }
  21495. if (this._ranges[name]) {
  21496. if (deleteFrames) {
  21497. var from = this._ranges[name].from;
  21498. var to = this._ranges[name].to;
  21499. // this loop MUST go high to low for multiple splices to work
  21500. for (var key = this._keys.length - 1; key >= 0; key--) {
  21501. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  21502. this._keys.splice(key, 1);
  21503. }
  21504. }
  21505. }
  21506. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  21507. }
  21508. };
  21509. Animation.prototype.getRange = function (name) {
  21510. return this._ranges[name];
  21511. };
  21512. Animation.prototype.reset = function () {
  21513. this._offsetsCache = {};
  21514. this._highLimitsCache = {};
  21515. this.currentFrame = 0;
  21516. };
  21517. Animation.prototype.isStopped = function () {
  21518. return this._stopped;
  21519. };
  21520. Animation.prototype.getKeys = function () {
  21521. return this._keys;
  21522. };
  21523. Animation.prototype.getHighestFrame = function () {
  21524. var ret = 0;
  21525. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  21526. if (ret < this._keys[key].frame) {
  21527. ret = this._keys[key].frame;
  21528. }
  21529. }
  21530. return ret;
  21531. };
  21532. Animation.prototype.getEasingFunction = function () {
  21533. return this._easingFunction;
  21534. };
  21535. Animation.prototype.setEasingFunction = function (easingFunction) {
  21536. this._easingFunction = easingFunction;
  21537. };
  21538. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21539. return startValue + (endValue - startValue) * gradient;
  21540. };
  21541. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21542. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21543. };
  21544. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21545. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21546. };
  21547. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21548. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21549. };
  21550. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21551. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21552. };
  21553. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21554. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21555. };
  21556. Animation.prototype.clone = function () {
  21557. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21558. if (this._keys) {
  21559. clone.setKeys(this._keys);
  21560. }
  21561. return clone;
  21562. };
  21563. Animation.prototype.setKeys = function (values) {
  21564. this._keys = values.slice(0);
  21565. this._offsetsCache = {};
  21566. this._highLimitsCache = {};
  21567. };
  21568. Animation.prototype._getKeyValue = function (value) {
  21569. if (typeof value === "function") {
  21570. return value();
  21571. }
  21572. return value;
  21573. };
  21574. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21575. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21576. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21577. }
  21578. this.currentFrame = currentFrame;
  21579. // Try to get a hash to find the right key
  21580. 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));
  21581. if (this._keys[startKey].frame >= currentFrame) {
  21582. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21583. startKey--;
  21584. }
  21585. }
  21586. for (var key = startKey; key < this._keys.length; key++) {
  21587. if (this._keys[key + 1].frame >= currentFrame) {
  21588. var startValue = this._getKeyValue(this._keys[key].value);
  21589. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21590. // gradient : percent of currentFrame between the frame inf and the frame sup
  21591. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21592. // check for easingFunction and correction of gradient
  21593. if (this._easingFunction != null) {
  21594. gradient = this._easingFunction.ease(gradient);
  21595. }
  21596. switch (this.dataType) {
  21597. // Float
  21598. case Animation.ANIMATIONTYPE_FLOAT:
  21599. switch (loopMode) {
  21600. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21601. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21602. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21603. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21604. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21605. }
  21606. break;
  21607. // Quaternion
  21608. case Animation.ANIMATIONTYPE_QUATERNION:
  21609. var quaternion = null;
  21610. switch (loopMode) {
  21611. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21612. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21613. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21614. break;
  21615. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21616. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21617. break;
  21618. }
  21619. return quaternion;
  21620. // Vector3
  21621. case Animation.ANIMATIONTYPE_VECTOR3:
  21622. switch (loopMode) {
  21623. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21624. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21625. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21626. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21627. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21628. }
  21629. // Vector2
  21630. case Animation.ANIMATIONTYPE_VECTOR2:
  21631. switch (loopMode) {
  21632. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21633. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21634. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21635. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21636. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21637. }
  21638. // Color3
  21639. case Animation.ANIMATIONTYPE_COLOR3:
  21640. switch (loopMode) {
  21641. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21642. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21643. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21644. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21645. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21646. }
  21647. // Matrix
  21648. case Animation.ANIMATIONTYPE_MATRIX:
  21649. switch (loopMode) {
  21650. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21651. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21652. if (this.allowMatricesInterpolation) {
  21653. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21654. }
  21655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21656. return startValue;
  21657. }
  21658. default:
  21659. break;
  21660. }
  21661. break;
  21662. }
  21663. }
  21664. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21665. };
  21666. Animation.prototype.setValue = function (currentValue) {
  21667. // Set value
  21668. if (this.targetPropertyPath.length > 1) {
  21669. var property = this._target[this.targetPropertyPath[0]];
  21670. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21671. property = property[this.targetPropertyPath[index]];
  21672. }
  21673. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21674. }
  21675. else {
  21676. this._target[this.targetPropertyPath[0]] = currentValue;
  21677. }
  21678. if (this._target.markAsDirty) {
  21679. this._target.markAsDirty(this.targetProperty);
  21680. }
  21681. };
  21682. Animation.prototype.goToFrame = function (frame) {
  21683. if (frame < this._keys[0].frame) {
  21684. frame = this._keys[0].frame;
  21685. }
  21686. else if (frame > this._keys[this._keys.length - 1].frame) {
  21687. frame = this._keys[this._keys.length - 1].frame;
  21688. }
  21689. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21690. this.setValue(currentValue);
  21691. };
  21692. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21693. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21694. this._stopped = true;
  21695. return false;
  21696. }
  21697. var returnValue = true;
  21698. // Adding a start key at frame 0 if missing
  21699. if (this._keys[0].frame !== 0) {
  21700. var newKey = { frame: 0, value: this._keys[0].value };
  21701. this._keys.splice(0, 0, newKey);
  21702. }
  21703. // Check limits
  21704. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21705. from = this._keys[0].frame;
  21706. }
  21707. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21708. to = this._keys[this._keys.length - 1].frame;
  21709. }
  21710. // Compute ratio
  21711. var range = to - from;
  21712. var offsetValue;
  21713. // ratio represents the frame delta between from and to
  21714. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21715. var highLimitValue = 0;
  21716. if (ratio > range && !loop) {
  21717. returnValue = false;
  21718. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21719. }
  21720. else {
  21721. // Get max value if required
  21722. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21723. var keyOffset = to.toString() + from.toString();
  21724. if (!this._offsetsCache[keyOffset]) {
  21725. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21726. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21727. switch (this.dataType) {
  21728. // Float
  21729. case Animation.ANIMATIONTYPE_FLOAT:
  21730. this._offsetsCache[keyOffset] = toValue - fromValue;
  21731. break;
  21732. // Quaternion
  21733. case Animation.ANIMATIONTYPE_QUATERNION:
  21734. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21735. break;
  21736. // Vector3
  21737. case Animation.ANIMATIONTYPE_VECTOR3:
  21738. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21739. // Vector2
  21740. case Animation.ANIMATIONTYPE_VECTOR2:
  21741. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21742. // Color3
  21743. case Animation.ANIMATIONTYPE_COLOR3:
  21744. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21745. default:
  21746. break;
  21747. }
  21748. this._highLimitsCache[keyOffset] = toValue;
  21749. }
  21750. highLimitValue = this._highLimitsCache[keyOffset];
  21751. offsetValue = this._offsetsCache[keyOffset];
  21752. }
  21753. }
  21754. if (offsetValue === undefined) {
  21755. switch (this.dataType) {
  21756. // Float
  21757. case Animation.ANIMATIONTYPE_FLOAT:
  21758. offsetValue = 0;
  21759. break;
  21760. // Quaternion
  21761. case Animation.ANIMATIONTYPE_QUATERNION:
  21762. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21763. break;
  21764. // Vector3
  21765. case Animation.ANIMATIONTYPE_VECTOR3:
  21766. offsetValue = BABYLON.Vector3.Zero();
  21767. break;
  21768. // Vector2
  21769. case Animation.ANIMATIONTYPE_VECTOR2:
  21770. offsetValue = BABYLON.Vector2.Zero();
  21771. break;
  21772. // Color3
  21773. case Animation.ANIMATIONTYPE_COLOR3:
  21774. offsetValue = BABYLON.Color3.Black();
  21775. }
  21776. }
  21777. // Compute value
  21778. var repeatCount = (ratio / range) >> 0;
  21779. var currentFrame = returnValue ? from + ratio % range : to;
  21780. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21781. // Set value
  21782. this.setValue(currentValue);
  21783. // Check events
  21784. for (var index = 0; index < this._events.length; index++) {
  21785. if (currentFrame >= this._events[index].frame) {
  21786. var event = this._events[index];
  21787. if (!event.isDone) {
  21788. // If event should be done only once, remove it.
  21789. if (event.onlyOnce) {
  21790. this._events.splice(index, 1);
  21791. index--;
  21792. }
  21793. event.isDone = true;
  21794. event.action();
  21795. } // Don't do anything if the event has already be done.
  21796. }
  21797. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21798. // reset event, the animation is looping
  21799. this._events[index].isDone = false;
  21800. }
  21801. }
  21802. if (!returnValue) {
  21803. this._stopped = true;
  21804. }
  21805. return returnValue;
  21806. };
  21807. Animation.prototype.serialize = function () {
  21808. var serializationObject = {};
  21809. serializationObject.name = this.name;
  21810. serializationObject.property = this.targetProperty;
  21811. serializationObject.framePerSecond = this.framePerSecond;
  21812. serializationObject.dataType = this.dataType;
  21813. serializationObject.loopBehavior = this.loopMode;
  21814. var dataType = this.dataType;
  21815. serializationObject.keys = [];
  21816. var keys = this.getKeys();
  21817. for (var index = 0; index < keys.length; index++) {
  21818. var animationKey = keys[index];
  21819. var key = {};
  21820. key.frame = animationKey.frame;
  21821. switch (dataType) {
  21822. case Animation.ANIMATIONTYPE_FLOAT:
  21823. key.values = [animationKey.value];
  21824. break;
  21825. case Animation.ANIMATIONTYPE_QUATERNION:
  21826. case Animation.ANIMATIONTYPE_MATRIX:
  21827. case Animation.ANIMATIONTYPE_VECTOR3:
  21828. case Animation.ANIMATIONTYPE_COLOR3:
  21829. key.values = animationKey.value.asArray();
  21830. break;
  21831. }
  21832. serializationObject.keys.push(key);
  21833. }
  21834. serializationObject.ranges = [];
  21835. for (var name in this._ranges) {
  21836. var range = {};
  21837. range.name = name;
  21838. range.from = this._ranges[name].from;
  21839. range.to = this._ranges[name].to;
  21840. serializationObject.ranges.push(range);
  21841. }
  21842. return serializationObject;
  21843. };
  21844. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21845. get: function () {
  21846. return Animation._ANIMATIONTYPE_FLOAT;
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21852. get: function () {
  21853. return Animation._ANIMATIONTYPE_VECTOR3;
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21859. get: function () {
  21860. return Animation._ANIMATIONTYPE_VECTOR2;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21866. get: function () {
  21867. return Animation._ANIMATIONTYPE_QUATERNION;
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21873. get: function () {
  21874. return Animation._ANIMATIONTYPE_MATRIX;
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21880. get: function () {
  21881. return Animation._ANIMATIONTYPE_COLOR3;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21887. get: function () {
  21888. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21894. get: function () {
  21895. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21901. get: function () {
  21902. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21903. },
  21904. enumerable: true,
  21905. configurable: true
  21906. });
  21907. Animation.Parse = function (parsedAnimation) {
  21908. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21909. var dataType = parsedAnimation.dataType;
  21910. var keys = [];
  21911. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21912. var key = parsedAnimation.keys[index];
  21913. var data;
  21914. switch (dataType) {
  21915. case Animation.ANIMATIONTYPE_FLOAT:
  21916. data = key.values[0];
  21917. break;
  21918. case Animation.ANIMATIONTYPE_QUATERNION:
  21919. data = BABYLON.Quaternion.FromArray(key.values);
  21920. break;
  21921. case Animation.ANIMATIONTYPE_MATRIX:
  21922. data = BABYLON.Matrix.FromArray(key.values);
  21923. break;
  21924. case Animation.ANIMATIONTYPE_COLOR3:
  21925. data = BABYLON.Color3.FromArray(key.values);
  21926. break;
  21927. case Animation.ANIMATIONTYPE_VECTOR3:
  21928. default:
  21929. data = BABYLON.Vector3.FromArray(key.values);
  21930. break;
  21931. }
  21932. keys.push({
  21933. frame: key.frame,
  21934. value: data
  21935. });
  21936. }
  21937. animation.setKeys(keys);
  21938. if (parsedAnimation.ranges) {
  21939. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  21940. data = parsedAnimation.ranges[index];
  21941. animation.createRange(data.name, data.from, data.to);
  21942. }
  21943. }
  21944. return animation;
  21945. };
  21946. Animation.AppendSerializedAnimations = function (source, destination) {
  21947. if (source.animations) {
  21948. destination.animations = [];
  21949. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21950. var animation = source.animations[animationIndex];
  21951. destination.animations.push(animation.serialize());
  21952. }
  21953. }
  21954. };
  21955. // Statics
  21956. Animation._ANIMATIONTYPE_FLOAT = 0;
  21957. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21958. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21959. Animation._ANIMATIONTYPE_MATRIX = 3;
  21960. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21961. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21962. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21963. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21964. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21965. return Animation;
  21966. })();
  21967. BABYLON.Animation = Animation;
  21968. })(BABYLON || (BABYLON = {}));
  21969. var BABYLON;
  21970. (function (BABYLON) {
  21971. var Animatable = (function () {
  21972. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21973. if (fromFrame === void 0) { fromFrame = 0; }
  21974. if (toFrame === void 0) { toFrame = 100; }
  21975. if (loopAnimation === void 0) { loopAnimation = false; }
  21976. if (speedRatio === void 0) { speedRatio = 1.0; }
  21977. this.target = target;
  21978. this.fromFrame = fromFrame;
  21979. this.toFrame = toFrame;
  21980. this.loopAnimation = loopAnimation;
  21981. this.speedRatio = speedRatio;
  21982. this.onAnimationEnd = onAnimationEnd;
  21983. this._animations = new Array();
  21984. this._paused = false;
  21985. this.animationStarted = false;
  21986. if (animations) {
  21987. this.appendAnimations(target, animations);
  21988. }
  21989. this._scene = scene;
  21990. scene._activeAnimatables.push(this);
  21991. }
  21992. // Methods
  21993. Animatable.prototype.getAnimations = function () {
  21994. return this._animations;
  21995. };
  21996. Animatable.prototype.appendAnimations = function (target, animations) {
  21997. for (var index = 0; index < animations.length; index++) {
  21998. var animation = animations[index];
  21999. animation._target = target;
  22000. this._animations.push(animation);
  22001. }
  22002. };
  22003. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22004. var animations = this._animations;
  22005. for (var index = 0; index < animations.length; index++) {
  22006. if (animations[index].targetProperty === property) {
  22007. return animations[index];
  22008. }
  22009. }
  22010. return null;
  22011. };
  22012. Animatable.prototype.reset = function () {
  22013. var animations = this._animations;
  22014. for (var index = 0; index < animations.length; index++) {
  22015. animations[index].reset();
  22016. }
  22017. this._localDelayOffset = null;
  22018. this._pausedDelay = null;
  22019. };
  22020. Animatable.prototype.goToFrame = function (frame) {
  22021. var animations = this._animations;
  22022. for (var index = 0; index < animations.length; index++) {
  22023. animations[index].goToFrame(frame);
  22024. }
  22025. };
  22026. Animatable.prototype.pause = function () {
  22027. if (this._paused) {
  22028. return;
  22029. }
  22030. this._paused = true;
  22031. };
  22032. Animatable.prototype.restart = function () {
  22033. this._paused = false;
  22034. };
  22035. Animatable.prototype.stop = function () {
  22036. var index = this._scene._activeAnimatables.indexOf(this);
  22037. if (index > -1) {
  22038. this._scene._activeAnimatables.splice(index, 1);
  22039. }
  22040. if (this.onAnimationEnd) {
  22041. this.onAnimationEnd();
  22042. }
  22043. };
  22044. Animatable.prototype._animate = function (delay) {
  22045. if (this._paused) {
  22046. this.animationStarted = false;
  22047. if (!this._pausedDelay) {
  22048. this._pausedDelay = delay;
  22049. }
  22050. return true;
  22051. }
  22052. if (!this._localDelayOffset) {
  22053. this._localDelayOffset = delay;
  22054. }
  22055. else if (this._pausedDelay) {
  22056. this._localDelayOffset += delay - this._pausedDelay;
  22057. this._pausedDelay = null;
  22058. }
  22059. // Animating
  22060. var running = false;
  22061. var animations = this._animations;
  22062. var index;
  22063. for (index = 0; index < animations.length; index++) {
  22064. var animation = animations[index];
  22065. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22066. running = running || isRunning;
  22067. }
  22068. this.animationStarted = running;
  22069. if (!running) {
  22070. // Remove from active animatables
  22071. index = this._scene._activeAnimatables.indexOf(this);
  22072. this._scene._activeAnimatables.splice(index, 1);
  22073. }
  22074. if (!running && this.onAnimationEnd) {
  22075. this.onAnimationEnd();
  22076. }
  22077. return running;
  22078. };
  22079. return Animatable;
  22080. })();
  22081. BABYLON.Animatable = Animatable;
  22082. })(BABYLON || (BABYLON = {}));
  22083. var BABYLON;
  22084. (function (BABYLON) {
  22085. var EasingFunction = (function () {
  22086. function EasingFunction() {
  22087. // Properties
  22088. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22089. }
  22090. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22091. get: function () {
  22092. return EasingFunction._EASINGMODE_EASEIN;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22098. get: function () {
  22099. return EasingFunction._EASINGMODE_EASEOUT;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22105. get: function () {
  22106. return EasingFunction._EASINGMODE_EASEINOUT;
  22107. },
  22108. enumerable: true,
  22109. configurable: true
  22110. });
  22111. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22112. var n = Math.min(Math.max(easingMode, 0), 2);
  22113. this._easingMode = n;
  22114. };
  22115. EasingFunction.prototype.getEasingMode = function () {
  22116. return this._easingMode;
  22117. };
  22118. EasingFunction.prototype.easeInCore = function (gradient) {
  22119. throw new Error('You must implement this method');
  22120. };
  22121. EasingFunction.prototype.ease = function (gradient) {
  22122. switch (this._easingMode) {
  22123. case EasingFunction.EASINGMODE_EASEIN:
  22124. return this.easeInCore(gradient);
  22125. case EasingFunction.EASINGMODE_EASEOUT:
  22126. return (1 - this.easeInCore(1 - gradient));
  22127. }
  22128. if (gradient >= 0.5) {
  22129. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22130. }
  22131. return (this.easeInCore(gradient * 2) * 0.5);
  22132. };
  22133. //Statics
  22134. EasingFunction._EASINGMODE_EASEIN = 0;
  22135. EasingFunction._EASINGMODE_EASEOUT = 1;
  22136. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22137. return EasingFunction;
  22138. })();
  22139. BABYLON.EasingFunction = EasingFunction;
  22140. var CircleEase = (function (_super) {
  22141. __extends(CircleEase, _super);
  22142. function CircleEase() {
  22143. _super.apply(this, arguments);
  22144. }
  22145. CircleEase.prototype.easeInCore = function (gradient) {
  22146. gradient = Math.max(0, Math.min(1, gradient));
  22147. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22148. };
  22149. return CircleEase;
  22150. })(EasingFunction);
  22151. BABYLON.CircleEase = CircleEase;
  22152. var BackEase = (function (_super) {
  22153. __extends(BackEase, _super);
  22154. function BackEase(amplitude) {
  22155. if (amplitude === void 0) { amplitude = 1; }
  22156. _super.call(this);
  22157. this.amplitude = amplitude;
  22158. }
  22159. BackEase.prototype.easeInCore = function (gradient) {
  22160. var num = Math.max(0, this.amplitude);
  22161. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22162. };
  22163. return BackEase;
  22164. })(EasingFunction);
  22165. BABYLON.BackEase = BackEase;
  22166. var BounceEase = (function (_super) {
  22167. __extends(BounceEase, _super);
  22168. function BounceEase(bounces, bounciness) {
  22169. if (bounces === void 0) { bounces = 3; }
  22170. if (bounciness === void 0) { bounciness = 2; }
  22171. _super.call(this);
  22172. this.bounces = bounces;
  22173. this.bounciness = bounciness;
  22174. }
  22175. BounceEase.prototype.easeInCore = function (gradient) {
  22176. var y = Math.max(0.0, this.bounces);
  22177. var bounciness = this.bounciness;
  22178. if (bounciness <= 1.0) {
  22179. bounciness = 1.001;
  22180. }
  22181. var num9 = Math.pow(bounciness, y);
  22182. var num5 = 1.0 - bounciness;
  22183. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22184. var num15 = gradient * num4;
  22185. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22186. var num3 = Math.floor(num65);
  22187. var num13 = num3 + 1.0;
  22188. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22189. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22190. var num7 = (num8 + num12) * 0.5;
  22191. var num6 = gradient - num7;
  22192. var num2 = num7 - num8;
  22193. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22194. };
  22195. return BounceEase;
  22196. })(EasingFunction);
  22197. BABYLON.BounceEase = BounceEase;
  22198. var CubicEase = (function (_super) {
  22199. __extends(CubicEase, _super);
  22200. function CubicEase() {
  22201. _super.apply(this, arguments);
  22202. }
  22203. CubicEase.prototype.easeInCore = function (gradient) {
  22204. return (gradient * gradient * gradient);
  22205. };
  22206. return CubicEase;
  22207. })(EasingFunction);
  22208. BABYLON.CubicEase = CubicEase;
  22209. var ElasticEase = (function (_super) {
  22210. __extends(ElasticEase, _super);
  22211. function ElasticEase(oscillations, springiness) {
  22212. if (oscillations === void 0) { oscillations = 3; }
  22213. if (springiness === void 0) { springiness = 3; }
  22214. _super.call(this);
  22215. this.oscillations = oscillations;
  22216. this.springiness = springiness;
  22217. }
  22218. ElasticEase.prototype.easeInCore = function (gradient) {
  22219. var num2;
  22220. var num3 = Math.max(0.0, this.oscillations);
  22221. var num = Math.max(0.0, this.springiness);
  22222. if (num == 0) {
  22223. num2 = gradient;
  22224. }
  22225. else {
  22226. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22227. }
  22228. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22229. };
  22230. return ElasticEase;
  22231. })(EasingFunction);
  22232. BABYLON.ElasticEase = ElasticEase;
  22233. var ExponentialEase = (function (_super) {
  22234. __extends(ExponentialEase, _super);
  22235. function ExponentialEase(exponent) {
  22236. if (exponent === void 0) { exponent = 2; }
  22237. _super.call(this);
  22238. this.exponent = exponent;
  22239. }
  22240. ExponentialEase.prototype.easeInCore = function (gradient) {
  22241. if (this.exponent <= 0) {
  22242. return gradient;
  22243. }
  22244. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22245. };
  22246. return ExponentialEase;
  22247. })(EasingFunction);
  22248. BABYLON.ExponentialEase = ExponentialEase;
  22249. var PowerEase = (function (_super) {
  22250. __extends(PowerEase, _super);
  22251. function PowerEase(power) {
  22252. if (power === void 0) { power = 2; }
  22253. _super.call(this);
  22254. this.power = power;
  22255. }
  22256. PowerEase.prototype.easeInCore = function (gradient) {
  22257. var y = Math.max(0.0, this.power);
  22258. return Math.pow(gradient, y);
  22259. };
  22260. return PowerEase;
  22261. })(EasingFunction);
  22262. BABYLON.PowerEase = PowerEase;
  22263. var QuadraticEase = (function (_super) {
  22264. __extends(QuadraticEase, _super);
  22265. function QuadraticEase() {
  22266. _super.apply(this, arguments);
  22267. }
  22268. QuadraticEase.prototype.easeInCore = function (gradient) {
  22269. return (gradient * gradient);
  22270. };
  22271. return QuadraticEase;
  22272. })(EasingFunction);
  22273. BABYLON.QuadraticEase = QuadraticEase;
  22274. var QuarticEase = (function (_super) {
  22275. __extends(QuarticEase, _super);
  22276. function QuarticEase() {
  22277. _super.apply(this, arguments);
  22278. }
  22279. QuarticEase.prototype.easeInCore = function (gradient) {
  22280. return (gradient * gradient * gradient * gradient);
  22281. };
  22282. return QuarticEase;
  22283. })(EasingFunction);
  22284. BABYLON.QuarticEase = QuarticEase;
  22285. var QuinticEase = (function (_super) {
  22286. __extends(QuinticEase, _super);
  22287. function QuinticEase() {
  22288. _super.apply(this, arguments);
  22289. }
  22290. QuinticEase.prototype.easeInCore = function (gradient) {
  22291. return (gradient * gradient * gradient * gradient * gradient);
  22292. };
  22293. return QuinticEase;
  22294. })(EasingFunction);
  22295. BABYLON.QuinticEase = QuinticEase;
  22296. var SineEase = (function (_super) {
  22297. __extends(SineEase, _super);
  22298. function SineEase() {
  22299. _super.apply(this, arguments);
  22300. }
  22301. SineEase.prototype.easeInCore = function (gradient) {
  22302. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22303. };
  22304. return SineEase;
  22305. })(EasingFunction);
  22306. BABYLON.SineEase = SineEase;
  22307. var BezierCurveEase = (function (_super) {
  22308. __extends(BezierCurveEase, _super);
  22309. function BezierCurveEase(x1, y1, x2, y2) {
  22310. if (x1 === void 0) { x1 = 0; }
  22311. if (y1 === void 0) { y1 = 0; }
  22312. if (x2 === void 0) { x2 = 1; }
  22313. if (y2 === void 0) { y2 = 1; }
  22314. _super.call(this);
  22315. this.x1 = x1;
  22316. this.y1 = y1;
  22317. this.x2 = x2;
  22318. this.y2 = y2;
  22319. }
  22320. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22321. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22322. };
  22323. return BezierCurveEase;
  22324. })(EasingFunction);
  22325. BABYLON.BezierCurveEase = BezierCurveEase;
  22326. })(BABYLON || (BABYLON = {}));
  22327. var BABYLON;
  22328. (function (BABYLON) {
  22329. var Bone = (function (_super) {
  22330. __extends(Bone, _super);
  22331. function Bone(name, skeleton, parentBone, matrix) {
  22332. _super.call(this, name, skeleton.getScene());
  22333. this.name = name;
  22334. this.children = new Array();
  22335. this.animations = new Array();
  22336. this._worldTransform = new BABYLON.Matrix();
  22337. this._absoluteTransform = new BABYLON.Matrix();
  22338. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22339. this._skeleton = skeleton;
  22340. this._matrix = matrix;
  22341. this._baseMatrix = matrix;
  22342. skeleton.bones.push(this);
  22343. if (parentBone) {
  22344. this._parent = parentBone;
  22345. parentBone.children.push(this);
  22346. }
  22347. else {
  22348. this._parent = null;
  22349. }
  22350. this._updateDifferenceMatrix();
  22351. }
  22352. // Members
  22353. Bone.prototype.getParent = function () {
  22354. return this._parent;
  22355. };
  22356. Bone.prototype.getLocalMatrix = function () {
  22357. return this._matrix;
  22358. };
  22359. Bone.prototype.getBaseMatrix = function () {
  22360. return this._baseMatrix;
  22361. };
  22362. Bone.prototype.getWorldMatrix = function () {
  22363. return this._worldTransform;
  22364. };
  22365. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22366. return this._invertedAbsoluteTransform;
  22367. };
  22368. Bone.prototype.getAbsoluteMatrix = function () {
  22369. var matrix = this._matrix.clone();
  22370. var parent = this._parent;
  22371. while (parent) {
  22372. matrix = matrix.multiply(parent.getLocalMatrix());
  22373. parent = parent.getParent();
  22374. }
  22375. return matrix;
  22376. };
  22377. // Methods
  22378. Bone.prototype.updateMatrix = function (matrix) {
  22379. this._matrix = matrix;
  22380. this._skeleton._markAsDirty();
  22381. this._updateDifferenceMatrix();
  22382. };
  22383. Bone.prototype._updateDifferenceMatrix = function () {
  22384. if (this._parent) {
  22385. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22386. }
  22387. else {
  22388. this._absoluteTransform.copyFrom(this._matrix);
  22389. }
  22390. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22391. for (var index = 0; index < this.children.length; index++) {
  22392. this.children[index]._updateDifferenceMatrix();
  22393. }
  22394. };
  22395. Bone.prototype.markAsDirty = function () {
  22396. this._currentRenderId++;
  22397. this._skeleton._markAsDirty();
  22398. };
  22399. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22400. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22401. // all animation may be coming from a library skeleton, so may need to create animation
  22402. if (this.animations.length === 0) {
  22403. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  22404. }
  22405. // get animation info / verify there is such a range from the source bone
  22406. var sourceRange = source.animations[0].getRange(rangeName);
  22407. if (!sourceRange) {
  22408. return false;
  22409. }
  22410. var from = sourceRange.from;
  22411. var to = sourceRange.to;
  22412. var sourceKeys = source.animations[0].getKeys();
  22413. // rescaling prep
  22414. var sourceBoneLength = source.length;
  22415. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  22416. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  22417. var destKeys = this.animations[0].getKeys();
  22418. // loop vars declaration / initialization
  22419. var orig;
  22420. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22421. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  22422. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22423. var mat;
  22424. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  22425. orig = sourceKeys[key];
  22426. if (orig.frame >= from && orig.frame <= to) {
  22427. if (scalingReqd) {
  22428. orig.value.decompose(origScale, origRotation, origTranslation);
  22429. origTranslation.scaleInPlace(ratio);
  22430. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  22431. }
  22432. else {
  22433. mat = orig.value;
  22434. }
  22435. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  22436. }
  22437. }
  22438. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  22439. return true;
  22440. };
  22441. return Bone;
  22442. })(BABYLON.Node);
  22443. BABYLON.Bone = Bone;
  22444. })(BABYLON || (BABYLON = {}));
  22445. var BABYLON;
  22446. (function (BABYLON) {
  22447. var Skeleton = (function () {
  22448. function Skeleton(name, id, scene) {
  22449. this.name = name;
  22450. this.id = id;
  22451. this.bones = new Array();
  22452. this._isDirty = true;
  22453. this._identity = BABYLON.Matrix.Identity();
  22454. this._ranges = {};
  22455. this.bones = [];
  22456. this._scene = scene;
  22457. scene.skeletons.push(this);
  22458. this.prepare();
  22459. //make sure it will recalculate the matrix next time prepare is called.
  22460. this._isDirty = true;
  22461. }
  22462. // Members
  22463. Skeleton.prototype.getTransformMatrices = function () {
  22464. return this._transformMatrices;
  22465. };
  22466. Skeleton.prototype.getScene = function () {
  22467. return this._scene;
  22468. };
  22469. // Methods
  22470. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22471. // check name not already in use
  22472. if (!this._ranges[name]) {
  22473. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  22474. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22475. if (this.bones[i].animations[0]) {
  22476. this.bones[i].animations[0].createRange(name, from, to);
  22477. }
  22478. }
  22479. }
  22480. };
  22481. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  22482. if (deleteFrames === void 0) { deleteFrames = true; }
  22483. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22484. if (this.bones[i].animations[0]) {
  22485. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  22486. }
  22487. }
  22488. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22489. };
  22490. Skeleton.prototype.getAnimationRange = function (name) {
  22491. return this._ranges[name];
  22492. };
  22493. /**
  22494. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  22495. */
  22496. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  22497. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22498. if (this._ranges[name] || !source.getAnimationRange(name)) {
  22499. return false;
  22500. }
  22501. var ret = true;
  22502. var frameOffset = this._getHighestAnimationFrame() + 1;
  22503. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  22504. var boneDict = {};
  22505. var sourceBones = source.bones;
  22506. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  22507. boneDict[sourceBones[i].name] = sourceBones[i];
  22508. }
  22509. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22510. var boneName = this.bones[i].name;
  22511. var sourceBone = boneDict[boneName];
  22512. if (sourceBone) {
  22513. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  22514. }
  22515. else {
  22516. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  22517. ret = false;
  22518. }
  22519. }
  22520. // do not call createAnimationRange(), since it also is done to bones, which was already done
  22521. var range = source.getAnimationRange(name);
  22522. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  22523. return ret;
  22524. };
  22525. Skeleton.prototype._getHighestAnimationFrame = function () {
  22526. var ret = 0;
  22527. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22528. if (this.bones[i].animations[0]) {
  22529. var highest = this.bones[i].animations[0].getHighestFrame();
  22530. if (ret < highest) {
  22531. ret = highest;
  22532. }
  22533. }
  22534. }
  22535. return ret;
  22536. };
  22537. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22538. var range = this.getAnimationRange(name);
  22539. if (!range) {
  22540. return null;
  22541. }
  22542. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22543. };
  22544. Skeleton.prototype._markAsDirty = function () {
  22545. this._isDirty = true;
  22546. };
  22547. Skeleton.prototype.prepare = function () {
  22548. if (!this._isDirty) {
  22549. return;
  22550. }
  22551. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22552. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22553. }
  22554. for (var index = 0; index < this.bones.length; index++) {
  22555. var bone = this.bones[index];
  22556. var parentBone = bone.getParent();
  22557. if (parentBone) {
  22558. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22559. }
  22560. else {
  22561. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22562. }
  22563. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22564. }
  22565. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22566. this._isDirty = false;
  22567. this._scene._activeBones += this.bones.length;
  22568. };
  22569. Skeleton.prototype.getAnimatables = function () {
  22570. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22571. this._animatables = [];
  22572. for (var index = 0; index < this.bones.length; index++) {
  22573. this._animatables.push(this.bones[index]);
  22574. }
  22575. }
  22576. return this._animatables;
  22577. };
  22578. Skeleton.prototype.clone = function (name, id) {
  22579. var result = new Skeleton(name, id || name, this._scene);
  22580. for (var index = 0; index < this.bones.length; index++) {
  22581. var source = this.bones[index];
  22582. var parentBone = null;
  22583. if (source.getParent()) {
  22584. var parentIndex = this.bones.indexOf(source.getParent());
  22585. parentBone = result.bones[parentIndex];
  22586. }
  22587. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone());
  22588. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22589. }
  22590. return result;
  22591. };
  22592. Skeleton.prototype.dispose = function () {
  22593. // Animations
  22594. this.getScene().stopAnimation(this);
  22595. // Remove from scene
  22596. this.getScene().removeSkeleton(this);
  22597. };
  22598. Skeleton.prototype.serialize = function () {
  22599. var serializationObject = {};
  22600. serializationObject.name = this.name;
  22601. serializationObject.id = this.id;
  22602. serializationObject.bones = [];
  22603. for (var index = 0; index < this.bones.length; index++) {
  22604. var bone = this.bones[index];
  22605. var serializedBone = {
  22606. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22607. name: bone.name,
  22608. matrix: bone.getLocalMatrix().toArray()
  22609. };
  22610. serializationObject.bones.push(serializedBone);
  22611. if (bone.length) {
  22612. serializedBone.length = bone.length;
  22613. }
  22614. if (bone.animations && bone.animations.length > 0) {
  22615. serializedBone.animation = bone.animations[0].serialize();
  22616. }
  22617. serializationObject.ranges = [];
  22618. for (var name in this._ranges) {
  22619. var range = {};
  22620. range.name = name;
  22621. range.from = this._ranges[name].from;
  22622. range.to = this._ranges[name].to;
  22623. serializationObject.ranges.push(range);
  22624. }
  22625. }
  22626. return serializationObject;
  22627. };
  22628. Skeleton.Parse = function (parsedSkeleton, scene) {
  22629. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22630. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22631. var parsedBone = parsedSkeleton.bones[index];
  22632. var parentBone = null;
  22633. if (parsedBone.parentBoneIndex > -1) {
  22634. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22635. }
  22636. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22637. if (parsedBone.length) {
  22638. bone.length = parsedBone.length;
  22639. }
  22640. if (parsedBone.animation) {
  22641. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22642. }
  22643. }
  22644. // placed after bones, so createAnimationRange can cascade down
  22645. if (parsedSkeleton.ranges) {
  22646. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  22647. var data = parsedSkeleton.ranges[index];
  22648. skeleton.createAnimationRange(data.name, data.from, data.to);
  22649. }
  22650. }
  22651. return skeleton;
  22652. };
  22653. return Skeleton;
  22654. })();
  22655. BABYLON.Skeleton = Skeleton;
  22656. })(BABYLON || (BABYLON = {}));
  22657. var BABYLON;
  22658. (function (BABYLON) {
  22659. var PostProcess = (function () {
  22660. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22662. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22663. this.name = name;
  22664. this.width = -1;
  22665. this.height = -1;
  22666. this._reusable = false;
  22667. this._textures = new BABYLON.SmartArray(2);
  22668. this._currentRenderTextureInd = 0;
  22669. if (camera != null) {
  22670. this._camera = camera;
  22671. this._scene = camera.getScene();
  22672. camera.attachPostProcess(this);
  22673. this._engine = this._scene.getEngine();
  22674. }
  22675. else {
  22676. this._engine = engine;
  22677. }
  22678. this._renderRatio = ratio;
  22679. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22680. this._reusable = reusable || false;
  22681. this._textureType = textureType;
  22682. this._samplers = samplers || [];
  22683. this._samplers.push("textureSampler");
  22684. this._fragmentUrl = fragmentUrl;
  22685. this._parameters = parameters || [];
  22686. this.updateEffect(defines);
  22687. }
  22688. PostProcess.prototype.updateEffect = function (defines) {
  22689. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22690. };
  22691. PostProcess.prototype.isReusable = function () {
  22692. return this._reusable;
  22693. };
  22694. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22695. camera = camera || this._camera;
  22696. var scene = camera.getScene();
  22697. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22698. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22699. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22700. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22701. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22702. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22703. if (this._textures.length > 0) {
  22704. for (var i = 0; i < this._textures.length; i++) {
  22705. this._engine._releaseTexture(this._textures.data[i]);
  22706. }
  22707. this._textures.reset();
  22708. }
  22709. this.width = desiredWidth;
  22710. this.height = desiredHeight;
  22711. 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 }));
  22712. if (this._reusable) {
  22713. 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 }));
  22714. }
  22715. if (this.onSizeChanged) {
  22716. this.onSizeChanged();
  22717. }
  22718. }
  22719. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22720. if (this.onActivate) {
  22721. this.onActivate(camera);
  22722. }
  22723. // Clear
  22724. if (this.clearColor) {
  22725. this._engine.clear(this.clearColor, true, true);
  22726. }
  22727. else {
  22728. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22729. }
  22730. if (this._reusable) {
  22731. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22732. }
  22733. };
  22734. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22735. get: function () {
  22736. return this._effect.isSupported;
  22737. },
  22738. enumerable: true,
  22739. configurable: true
  22740. });
  22741. PostProcess.prototype.apply = function () {
  22742. // Check
  22743. if (!this._effect.isReady())
  22744. return null;
  22745. // States
  22746. this._engine.enableEffect(this._effect);
  22747. this._engine.setState(false);
  22748. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22749. this._engine.setDepthBuffer(false);
  22750. this._engine.setDepthWrite(false);
  22751. // Texture
  22752. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22753. // Parameters
  22754. if (this.onApply) {
  22755. this.onApply(this._effect);
  22756. }
  22757. return this._effect;
  22758. };
  22759. PostProcess.prototype.dispose = function (camera) {
  22760. camera = camera || this._camera;
  22761. if (this._textures.length > 0) {
  22762. for (var i = 0; i < this._textures.length; i++) {
  22763. this._engine._releaseTexture(this._textures.data[i]);
  22764. }
  22765. this._textures.reset();
  22766. }
  22767. if (!camera) {
  22768. return;
  22769. }
  22770. camera.detachPostProcess(this);
  22771. var index = camera._postProcesses.indexOf(this);
  22772. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22773. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22774. }
  22775. };
  22776. return PostProcess;
  22777. })();
  22778. BABYLON.PostProcess = PostProcess;
  22779. })(BABYLON || (BABYLON = {}));
  22780. var BABYLON;
  22781. (function (BABYLON) {
  22782. var PostProcessManager = (function () {
  22783. function PostProcessManager(scene) {
  22784. this._vertexDeclaration = [2];
  22785. this._vertexStrideSize = 2 * 4;
  22786. this._scene = scene;
  22787. }
  22788. PostProcessManager.prototype._prepareBuffers = function () {
  22789. if (this._vertexBuffer) {
  22790. return;
  22791. }
  22792. // VBO
  22793. var vertices = [];
  22794. vertices.push(1, 1);
  22795. vertices.push(-1, 1);
  22796. vertices.push(-1, -1);
  22797. vertices.push(1, -1);
  22798. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22799. // Indices
  22800. var indices = [];
  22801. indices.push(0);
  22802. indices.push(1);
  22803. indices.push(2);
  22804. indices.push(0);
  22805. indices.push(2);
  22806. indices.push(3);
  22807. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22808. };
  22809. // Methods
  22810. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22811. var postProcesses = this._scene.activeCamera._postProcesses;
  22812. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22813. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22814. return false;
  22815. }
  22816. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22817. return true;
  22818. };
  22819. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22820. var engine = this._scene.getEngine();
  22821. for (var index = 0; index < postProcesses.length; index++) {
  22822. if (index < postProcesses.length - 1) {
  22823. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22824. }
  22825. else {
  22826. if (targetTexture) {
  22827. engine.bindFramebuffer(targetTexture);
  22828. }
  22829. else {
  22830. engine.restoreDefaultFramebuffer();
  22831. }
  22832. }
  22833. var pp = postProcesses[index];
  22834. var effect = pp.apply();
  22835. if (effect) {
  22836. if (pp.onBeforeRender) {
  22837. pp.onBeforeRender(effect);
  22838. }
  22839. // VBOs
  22840. this._prepareBuffers();
  22841. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22842. // Draw order
  22843. engine.draw(true, 0, 6);
  22844. if (pp.onAfterRender) {
  22845. pp.onAfterRender(effect);
  22846. }
  22847. }
  22848. }
  22849. // Restore depth buffer
  22850. engine.setDepthBuffer(true);
  22851. engine.setDepthWrite(true);
  22852. };
  22853. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22854. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22855. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22856. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22857. return;
  22858. }
  22859. var engine = this._scene.getEngine();
  22860. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22861. if (index < postProcessesTakenIndices.length - 1) {
  22862. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  22863. }
  22864. else {
  22865. if (targetTexture) {
  22866. engine.bindFramebuffer(targetTexture, faceIndex);
  22867. }
  22868. else {
  22869. engine.restoreDefaultFramebuffer();
  22870. }
  22871. }
  22872. if (doNotPresent) {
  22873. break;
  22874. }
  22875. var pp = postProcesses[postProcessesTakenIndices[index]];
  22876. var effect = pp.apply();
  22877. if (effect) {
  22878. if (pp.onBeforeRender) {
  22879. pp.onBeforeRender(effect);
  22880. }
  22881. // VBOs
  22882. this._prepareBuffers();
  22883. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22884. // Draw order
  22885. engine.draw(true, 0, 6);
  22886. if (pp.onAfterRender) {
  22887. pp.onAfterRender(effect);
  22888. }
  22889. }
  22890. }
  22891. // Restore depth buffer
  22892. engine.setDepthBuffer(true);
  22893. engine.setDepthWrite(true);
  22894. };
  22895. PostProcessManager.prototype.dispose = function () {
  22896. if (this._vertexBuffer) {
  22897. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22898. this._vertexBuffer = null;
  22899. }
  22900. if (this._indexBuffer) {
  22901. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22902. this._indexBuffer = null;
  22903. }
  22904. };
  22905. return PostProcessManager;
  22906. })();
  22907. BABYLON.PostProcessManager = PostProcessManager;
  22908. })(BABYLON || (BABYLON = {}));
  22909. var BABYLON;
  22910. (function (BABYLON) {
  22911. var PassPostProcess = (function (_super) {
  22912. __extends(PassPostProcess, _super);
  22913. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22914. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22915. }
  22916. return PassPostProcess;
  22917. })(BABYLON.PostProcess);
  22918. BABYLON.PassPostProcess = PassPostProcess;
  22919. })(BABYLON || (BABYLON = {}));
  22920. var BABYLON;
  22921. (function (BABYLON) {
  22922. var PhysicsEngine = (function () {
  22923. function PhysicsEngine(plugin) {
  22924. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22925. }
  22926. PhysicsEngine.prototype._initialize = function (gravity) {
  22927. this._currentPlugin.initialize();
  22928. this._setGravity(gravity);
  22929. };
  22930. PhysicsEngine.prototype._runOneStep = function (delta) {
  22931. if (delta > 0.1) {
  22932. delta = 0.1;
  22933. }
  22934. else if (delta <= 0) {
  22935. delta = 1.0 / 60.0;
  22936. }
  22937. this._currentPlugin.runOneStep(delta);
  22938. };
  22939. PhysicsEngine.prototype._setGravity = function (gravity) {
  22940. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22941. this._currentPlugin.setGravity(this.gravity);
  22942. };
  22943. PhysicsEngine.prototype._getGravity = function () {
  22944. return this._currentPlugin.getGravity();
  22945. };
  22946. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22947. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22948. };
  22949. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22950. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22951. };
  22952. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22953. this._currentPlugin.unregisterMesh(mesh);
  22954. };
  22955. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22956. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22957. };
  22958. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22959. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22960. };
  22961. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22962. this._currentPlugin.updateBodyPosition(mesh);
  22963. };
  22964. PhysicsEngine.prototype.dispose = function () {
  22965. this._currentPlugin.dispose();
  22966. };
  22967. PhysicsEngine.prototype.isSupported = function () {
  22968. return this._currentPlugin.isSupported();
  22969. };
  22970. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22971. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22972. };
  22973. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22974. return this._currentPlugin.name;
  22975. };
  22976. // Statics
  22977. PhysicsEngine.NoImpostor = 0;
  22978. PhysicsEngine.SphereImpostor = 1;
  22979. PhysicsEngine.BoxImpostor = 2;
  22980. PhysicsEngine.PlaneImpostor = 3;
  22981. PhysicsEngine.MeshImpostor = 4;
  22982. PhysicsEngine.CapsuleImpostor = 5;
  22983. PhysicsEngine.ConeImpostor = 6;
  22984. PhysicsEngine.CylinderImpostor = 7;
  22985. PhysicsEngine.ConvexHullImpostor = 8;
  22986. PhysicsEngine.HeightmapImpostor = 9;
  22987. PhysicsEngine.Epsilon = 0.001;
  22988. return PhysicsEngine;
  22989. })();
  22990. BABYLON.PhysicsEngine = PhysicsEngine;
  22991. })(BABYLON || (BABYLON = {}));
  22992. var BABYLON;
  22993. (function (BABYLON) {
  22994. var VertexData = (function () {
  22995. function VertexData() {
  22996. }
  22997. VertexData.prototype.set = function (data, kind) {
  22998. switch (kind) {
  22999. case BABYLON.VertexBuffer.PositionKind:
  23000. this.positions = data;
  23001. break;
  23002. case BABYLON.VertexBuffer.NormalKind:
  23003. this.normals = data;
  23004. break;
  23005. case BABYLON.VertexBuffer.UVKind:
  23006. this.uvs = data;
  23007. break;
  23008. case BABYLON.VertexBuffer.UV2Kind:
  23009. this.uvs2 = data;
  23010. break;
  23011. case BABYLON.VertexBuffer.UV3Kind:
  23012. this.uvs3 = data;
  23013. break;
  23014. case BABYLON.VertexBuffer.UV4Kind:
  23015. this.uvs4 = data;
  23016. break;
  23017. case BABYLON.VertexBuffer.UV5Kind:
  23018. this.uvs5 = data;
  23019. break;
  23020. case BABYLON.VertexBuffer.UV6Kind:
  23021. this.uvs6 = data;
  23022. break;
  23023. case BABYLON.VertexBuffer.ColorKind:
  23024. this.colors = data;
  23025. break;
  23026. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23027. this.matricesIndices = data;
  23028. break;
  23029. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23030. this.matricesWeights = data;
  23031. break;
  23032. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23033. this.matricesIndicesExtra = data;
  23034. break;
  23035. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23036. this.matricesWeightsExtra = data;
  23037. break;
  23038. }
  23039. };
  23040. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23041. this._applyTo(mesh, updatable);
  23042. };
  23043. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23044. this._applyTo(geometry, updatable);
  23045. };
  23046. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23047. this._update(mesh);
  23048. };
  23049. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23050. this._update(geometry);
  23051. };
  23052. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23053. if (this.positions) {
  23054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23055. }
  23056. if (this.normals) {
  23057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23058. }
  23059. if (this.uvs) {
  23060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23061. }
  23062. if (this.uvs2) {
  23063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23064. }
  23065. if (this.uvs3) {
  23066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23067. }
  23068. if (this.uvs4) {
  23069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23070. }
  23071. if (this.uvs5) {
  23072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23073. }
  23074. if (this.uvs6) {
  23075. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23076. }
  23077. if (this.colors) {
  23078. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23079. }
  23080. if (this.matricesIndices) {
  23081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23082. }
  23083. if (this.matricesWeights) {
  23084. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23085. }
  23086. if (this.matricesIndicesExtra) {
  23087. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23088. }
  23089. if (this.matricesWeightsExtra) {
  23090. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23091. }
  23092. if (this.indices) {
  23093. meshOrGeometry.setIndices(this.indices);
  23094. }
  23095. };
  23096. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23097. if (this.positions) {
  23098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23099. }
  23100. if (this.normals) {
  23101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23102. }
  23103. if (this.uvs) {
  23104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23105. }
  23106. if (this.uvs2) {
  23107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23108. }
  23109. if (this.uvs3) {
  23110. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23111. }
  23112. if (this.uvs4) {
  23113. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23114. }
  23115. if (this.uvs5) {
  23116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23117. }
  23118. if (this.uvs6) {
  23119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23120. }
  23121. if (this.colors) {
  23122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23123. }
  23124. if (this.matricesIndices) {
  23125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23126. }
  23127. if (this.matricesWeights) {
  23128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23129. }
  23130. if (this.matricesIndicesExtra) {
  23131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23132. }
  23133. if (this.matricesWeightsExtra) {
  23134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23135. }
  23136. if (this.indices) {
  23137. meshOrGeometry.setIndices(this.indices);
  23138. }
  23139. };
  23140. VertexData.prototype.transform = function (matrix) {
  23141. var transformed = BABYLON.Vector3.Zero();
  23142. var index;
  23143. if (this.positions) {
  23144. var position = BABYLON.Vector3.Zero();
  23145. for (index = 0; index < this.positions.length; index += 3) {
  23146. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23147. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23148. this.positions[index] = transformed.x;
  23149. this.positions[index + 1] = transformed.y;
  23150. this.positions[index + 2] = transformed.z;
  23151. }
  23152. }
  23153. if (this.normals) {
  23154. var normal = BABYLON.Vector3.Zero();
  23155. for (index = 0; index < this.normals.length; index += 3) {
  23156. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23157. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23158. this.normals[index] = transformed.x;
  23159. this.normals[index + 1] = transformed.y;
  23160. this.normals[index + 2] = transformed.z;
  23161. }
  23162. }
  23163. };
  23164. VertexData.prototype.merge = function (other) {
  23165. if (other.indices) {
  23166. if (!this.indices) {
  23167. this.indices = [];
  23168. }
  23169. var offset = this.positions ? this.positions.length / 3 : 0;
  23170. for (var index = 0; index < other.indices.length; index++) {
  23171. //TODO check type - if Int32Array!
  23172. this.indices.push(other.indices[index] + offset);
  23173. }
  23174. }
  23175. this.positions = this._mergeElement(this.positions, other.positions);
  23176. this.normals = this._mergeElement(this.normals, other.normals);
  23177. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23178. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23179. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23180. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23181. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23182. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23183. this.colors = this._mergeElement(this.colors, other.colors);
  23184. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23185. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23186. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23187. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23188. };
  23189. VertexData.prototype._mergeElement = function (source, other) {
  23190. if (!other)
  23191. return source;
  23192. if (!source)
  23193. return other;
  23194. var len = other.length + source.length;
  23195. var isSrcTypedArray = source instanceof Float32Array;
  23196. var isOthTypedArray = other instanceof Float32Array;
  23197. // use non-loop method when the source is Float32Array
  23198. if (isSrcTypedArray) {
  23199. var ret32 = new Float32Array(len);
  23200. ret32.set(source);
  23201. ret32.set(other, source.length);
  23202. return ret32;
  23203. }
  23204. else if (!isOthTypedArray) {
  23205. return source.concat(other);
  23206. }
  23207. else {
  23208. var ret = source.slice(0); // copy source to a separate array
  23209. for (var i = 0, len = other.length; i < len; i++) {
  23210. ret.push(other[i]);
  23211. }
  23212. return ret;
  23213. }
  23214. };
  23215. VertexData.prototype.serialize = function () {
  23216. var serializationObject = this.serialize();
  23217. if (this.positions) {
  23218. serializationObject.positions = this.positions;
  23219. }
  23220. if (this.normals) {
  23221. serializationObject.normals = this.normals;
  23222. }
  23223. if (this.uvs) {
  23224. serializationObject.uvs = this.uvs;
  23225. }
  23226. if (this.uvs2) {
  23227. serializationObject.uvs2 = this.uvs2;
  23228. }
  23229. if (this.uvs3) {
  23230. serializationObject.uvs3 = this.uvs3;
  23231. }
  23232. if (this.uvs4) {
  23233. serializationObject.uvs4 = this.uvs4;
  23234. }
  23235. if (this.uvs5) {
  23236. serializationObject.uvs5 = this.uvs5;
  23237. }
  23238. if (this.uvs6) {
  23239. serializationObject.uvs6 = this.uvs6;
  23240. }
  23241. if (this.colors) {
  23242. serializationObject.colors = this.colors;
  23243. }
  23244. if (this.matricesIndices) {
  23245. serializationObject.matricesIndices = this.matricesIndices;
  23246. serializationObject.matricesIndices._isExpanded = true;
  23247. }
  23248. if (this.matricesWeights) {
  23249. serializationObject.matricesWeights = this.matricesWeights;
  23250. }
  23251. if (this.matricesIndicesExtra) {
  23252. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23253. serializationObject.matricesIndicesExtra._isExpanded = true;
  23254. }
  23255. if (this.matricesWeightsExtra) {
  23256. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23257. }
  23258. serializationObject.indices = this.indices;
  23259. return serializationObject;
  23260. };
  23261. // Statics
  23262. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23263. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23264. };
  23265. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23266. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23267. };
  23268. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23269. var result = new VertexData();
  23270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23271. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23272. }
  23273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23274. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23275. }
  23276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23277. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23278. }
  23279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23280. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23281. }
  23282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23283. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23284. }
  23285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23286. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23287. }
  23288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23289. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23290. }
  23291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23292. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23293. }
  23294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23295. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23296. }
  23297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23298. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23299. }
  23300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23301. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23302. }
  23303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23304. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23305. }
  23306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23307. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23308. }
  23309. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23310. return result;
  23311. };
  23312. VertexData.CreateRibbon = function (options) {
  23313. var pathArray = options.pathArray;
  23314. var closeArray = options.closeArray || false;
  23315. var closePath = options.closePath || false;
  23316. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23317. var offset = options.offset || defaultOffset;
  23318. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23319. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23320. var positions = [];
  23321. var indices = [];
  23322. var normals = [];
  23323. var uvs = [];
  23324. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23325. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23326. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23327. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23328. var minlg; // minimal length among all paths from pathArray
  23329. var lg = []; // array of path lengths : nb of vertex per path
  23330. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23331. var p; // path iterator
  23332. var i; // point iterator
  23333. var j; // point iterator
  23334. // if single path in pathArray
  23335. if (pathArray.length < 2) {
  23336. var ar1 = [];
  23337. var ar2 = [];
  23338. for (i = 0; i < pathArray[0].length - offset; i++) {
  23339. ar1.push(pathArray[0][i]);
  23340. ar2.push(pathArray[0][i + offset]);
  23341. }
  23342. pathArray = [ar1, ar2];
  23343. }
  23344. // positions and horizontal distances (u)
  23345. var idc = 0;
  23346. var closePathCorr = (closePath) ? 1 : 0;
  23347. var path;
  23348. var l;
  23349. minlg = pathArray[0].length;
  23350. var vectlg;
  23351. var dist;
  23352. for (p = 0; p < pathArray.length; p++) {
  23353. uTotalDistance[p] = 0;
  23354. us[p] = [0];
  23355. path = pathArray[p];
  23356. l = path.length;
  23357. minlg = (minlg < l) ? minlg : l;
  23358. j = 0;
  23359. while (j < l) {
  23360. positions.push(path[j].x, path[j].y, path[j].z);
  23361. if (j > 0) {
  23362. vectlg = path[j].subtract(path[j - 1]).length();
  23363. dist = vectlg + uTotalDistance[p];
  23364. us[p].push(dist);
  23365. uTotalDistance[p] = dist;
  23366. }
  23367. j++;
  23368. }
  23369. if (closePath) {
  23370. j--;
  23371. positions.push(path[0].x, path[0].y, path[0].z);
  23372. vectlg = path[j].subtract(path[0]).length();
  23373. dist = vectlg + uTotalDistance[p];
  23374. us[p].push(dist);
  23375. uTotalDistance[p] = dist;
  23376. }
  23377. lg[p] = l + closePathCorr;
  23378. idx[p] = idc;
  23379. idc += (l + closePathCorr);
  23380. }
  23381. // vertical distances (v)
  23382. var path1;
  23383. var path2;
  23384. var vertex1;
  23385. var vertex2;
  23386. for (i = 0; i < minlg + closePathCorr; i++) {
  23387. vTotalDistance[i] = 0;
  23388. vs[i] = [0];
  23389. for (p = 0; p < pathArray.length - 1; p++) {
  23390. path1 = pathArray[p];
  23391. path2 = pathArray[p + 1];
  23392. if (i === minlg) {
  23393. vertex1 = path1[0];
  23394. vertex2 = path2[0];
  23395. }
  23396. else {
  23397. vertex1 = path1[i];
  23398. vertex2 = path2[i];
  23399. }
  23400. vectlg = vertex2.subtract(vertex1).length();
  23401. dist = vectlg + vTotalDistance[i];
  23402. vs[i].push(dist);
  23403. vTotalDistance[i] = dist;
  23404. }
  23405. if (closeArray) {
  23406. path1 = pathArray[p];
  23407. path2 = pathArray[0];
  23408. if (i === minlg) {
  23409. vertex2 = path2[0];
  23410. }
  23411. vectlg = vertex2.subtract(vertex1).length();
  23412. dist = vectlg + vTotalDistance[i];
  23413. vTotalDistance[i] = dist;
  23414. }
  23415. }
  23416. // uvs
  23417. var u;
  23418. var v;
  23419. for (p = 0; p < pathArray.length; p++) {
  23420. for (i = 0; i < minlg + closePathCorr; i++) {
  23421. u = us[p][i] / uTotalDistance[p];
  23422. v = vs[i][p] / vTotalDistance[i];
  23423. uvs.push(u, v);
  23424. }
  23425. }
  23426. // indices
  23427. p = 0; // path index
  23428. var pi = 0; // positions array index
  23429. var l1 = lg[p] - 1; // path1 length
  23430. var l2 = lg[p + 1] - 1; // path2 length
  23431. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23432. var shft = idx[1] - idx[0]; // shift
  23433. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23434. while (pi <= min && p < path1nb) {
  23435. // 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
  23436. indices.push(pi, pi + shft, pi + 1);
  23437. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23438. pi += 1;
  23439. if (pi === min) {
  23440. p++;
  23441. if (p === lg.length - 1) {
  23442. shft = idx[0] - idx[p];
  23443. l1 = lg[p] - 1;
  23444. l2 = lg[0] - 1;
  23445. }
  23446. else {
  23447. shft = idx[p + 1] - idx[p];
  23448. l1 = lg[p] - 1;
  23449. l2 = lg[p + 1] - 1;
  23450. }
  23451. pi = idx[p];
  23452. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23453. }
  23454. }
  23455. // normals
  23456. VertexData.ComputeNormals(positions, indices, normals);
  23457. if (closePath) {
  23458. var indexFirst = 0;
  23459. var indexLast = 0;
  23460. for (p = 0; p < pathArray.length; p++) {
  23461. indexFirst = idx[p] * 3;
  23462. if (p + 1 < pathArray.length) {
  23463. indexLast = (idx[p + 1] - 1) * 3;
  23464. }
  23465. else {
  23466. indexLast = normals.length - 3;
  23467. }
  23468. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23469. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23470. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23471. normals[indexLast] = normals[indexFirst];
  23472. normals[indexLast + 1] = normals[indexFirst + 1];
  23473. normals[indexLast + 2] = normals[indexFirst + 2];
  23474. }
  23475. }
  23476. // sides
  23477. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23478. // Result
  23479. var vertexData = new VertexData();
  23480. vertexData.indices = indices;
  23481. vertexData.positions = positions;
  23482. vertexData.normals = normals;
  23483. vertexData.uvs = uvs;
  23484. if (closePath) {
  23485. vertexData._idx = idx;
  23486. }
  23487. return vertexData;
  23488. };
  23489. VertexData.CreateBox = function (options) {
  23490. var normalsSource = [
  23491. new BABYLON.Vector3(0, 0, 1),
  23492. new BABYLON.Vector3(0, 0, -1),
  23493. new BABYLON.Vector3(1, 0, 0),
  23494. new BABYLON.Vector3(-1, 0, 0),
  23495. new BABYLON.Vector3(0, 1, 0),
  23496. new BABYLON.Vector3(0, -1, 0)
  23497. ];
  23498. var indices = [];
  23499. var positions = [];
  23500. var normals = [];
  23501. var uvs = [];
  23502. var width = options.width || options.size || 1;
  23503. var height = options.height || options.size || 1;
  23504. var depth = options.depth || options.size || 1;
  23505. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23506. var faceUV = options.faceUV || new Array(6);
  23507. var faceColors = options.faceColors;
  23508. var colors = [];
  23509. // default face colors and UV if undefined
  23510. for (var f = 0; f < 6; f++) {
  23511. if (faceUV[f] === undefined) {
  23512. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23513. }
  23514. if (faceColors && faceColors[f] === undefined) {
  23515. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23516. }
  23517. }
  23518. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23519. // Create each face in turn.
  23520. for (var index = 0; index < normalsSource.length; index++) {
  23521. var normal = normalsSource[index];
  23522. // Get two vectors perpendicular to the face normal and to each other.
  23523. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23524. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23525. // Six indices (two triangles) per face.
  23526. var verticesLength = positions.length / 3;
  23527. indices.push(verticesLength);
  23528. indices.push(verticesLength + 1);
  23529. indices.push(verticesLength + 2);
  23530. indices.push(verticesLength);
  23531. indices.push(verticesLength + 2);
  23532. indices.push(verticesLength + 3);
  23533. // Four vertices per face.
  23534. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23535. positions.push(vertex.x, vertex.y, vertex.z);
  23536. normals.push(normal.x, normal.y, normal.z);
  23537. uvs.push(faceUV[index].z, faceUV[index].w);
  23538. if (faceColors) {
  23539. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23540. }
  23541. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23542. positions.push(vertex.x, vertex.y, vertex.z);
  23543. normals.push(normal.x, normal.y, normal.z);
  23544. uvs.push(faceUV[index].x, faceUV[index].w);
  23545. if (faceColors) {
  23546. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23547. }
  23548. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23549. positions.push(vertex.x, vertex.y, vertex.z);
  23550. normals.push(normal.x, normal.y, normal.z);
  23551. uvs.push(faceUV[index].x, faceUV[index].y);
  23552. if (faceColors) {
  23553. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23554. }
  23555. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23556. positions.push(vertex.x, vertex.y, vertex.z);
  23557. normals.push(normal.x, normal.y, normal.z);
  23558. uvs.push(faceUV[index].z, faceUV[index].y);
  23559. if (faceColors) {
  23560. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23561. }
  23562. }
  23563. // sides
  23564. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23565. // Result
  23566. var vertexData = new VertexData();
  23567. vertexData.indices = indices;
  23568. vertexData.positions = positions;
  23569. vertexData.normals = normals;
  23570. vertexData.uvs = uvs;
  23571. if (faceColors) {
  23572. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23573. vertexData.colors = totalColors;
  23574. }
  23575. return vertexData;
  23576. };
  23577. VertexData.CreateSphere = function (options) {
  23578. var segments = options.segments || 32;
  23579. var diameterX = options.diameterX || options.diameter || 1;
  23580. var diameterY = options.diameterY || options.diameter || 1;
  23581. var diameterZ = options.diameterZ || options.diameter || 1;
  23582. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23583. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23584. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23585. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23586. var totalZRotationSteps = 2 + segments;
  23587. var totalYRotationSteps = 2 * totalZRotationSteps;
  23588. var indices = [];
  23589. var positions = [];
  23590. var normals = [];
  23591. var uvs = [];
  23592. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23593. var normalizedZ = zRotationStep / totalZRotationSteps;
  23594. var angleZ = normalizedZ * Math.PI * slice;
  23595. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23596. var normalizedY = yRotationStep / totalYRotationSteps;
  23597. var angleY = normalizedY * Math.PI * 2 * arc;
  23598. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23599. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23600. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23601. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23602. var vertex = complete.multiply(radius);
  23603. var normal = complete.divide(radius).normalize();
  23604. positions.push(vertex.x, vertex.y, vertex.z);
  23605. normals.push(normal.x, normal.y, normal.z);
  23606. uvs.push(normalizedY, normalizedZ);
  23607. }
  23608. if (zRotationStep > 0) {
  23609. var verticesCount = positions.length / 3;
  23610. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23611. indices.push((firstIndex));
  23612. indices.push((firstIndex + 1));
  23613. indices.push(firstIndex + totalYRotationSteps + 1);
  23614. indices.push((firstIndex + totalYRotationSteps + 1));
  23615. indices.push((firstIndex + 1));
  23616. indices.push((firstIndex + totalYRotationSteps + 2));
  23617. }
  23618. }
  23619. }
  23620. // Sides
  23621. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23622. // Result
  23623. var vertexData = new VertexData();
  23624. vertexData.indices = indices;
  23625. vertexData.positions = positions;
  23626. vertexData.normals = normals;
  23627. vertexData.uvs = uvs;
  23628. return vertexData;
  23629. };
  23630. // Cylinder and cone
  23631. VertexData.CreateCylinder = function (options) {
  23632. var height = options.height || 2;
  23633. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23634. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23635. var tessellation = options.tessellation || 24;
  23636. var subdivisions = options.subdivisions || 1;
  23637. var hasRings = options.hasRings;
  23638. var enclose = options.enclose;
  23639. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23641. var faceUV = options.faceUV || new Array(3);
  23642. var faceColors = options.faceColors;
  23643. // default face colors and UV if undefined
  23644. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23645. var ringNb = (hasRings) ? subdivisions : 1;
  23646. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23647. var f;
  23648. for (f = 0; f < surfaceNb; f++) {
  23649. if (faceColors && faceColors[f] === undefined) {
  23650. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23651. }
  23652. }
  23653. for (f = 0; f < surfaceNb; f++) {
  23654. if (faceUV && faceUV[f] === undefined) {
  23655. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23656. }
  23657. }
  23658. var indices = [];
  23659. var positions = [];
  23660. var normals = [];
  23661. var uvs = [];
  23662. var colors = [];
  23663. var angle_step = Math.PI * 2 * arc / tessellation;
  23664. var angle;
  23665. var h;
  23666. var radius;
  23667. var tan = (diameterBottom - diameterTop) / 2 / height;
  23668. var ringVertex = BABYLON.Vector3.Zero();
  23669. var ringNormal = BABYLON.Vector3.Zero();
  23670. var ringFirstVertex = BABYLON.Vector3.Zero();
  23671. var ringFirstNormal = BABYLON.Vector3.Zero();
  23672. var quadNormal = BABYLON.Vector3.Zero();
  23673. var Y = BABYLON.Axis.Y;
  23674. // positions, normals, uvs
  23675. var i;
  23676. var j;
  23677. var r;
  23678. var ringIdx = 1;
  23679. var s = 1; // surface index
  23680. var cs = 0;
  23681. var v = 0;
  23682. for (i = 0; i <= subdivisions; i++) {
  23683. h = i / subdivisions;
  23684. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23685. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23686. for (r = 0; r < ringIdx; r++) {
  23687. if (hasRings) {
  23688. s += r;
  23689. }
  23690. if (enclose) {
  23691. s += 2 * r;
  23692. }
  23693. for (j = 0; j <= tessellation; j++) {
  23694. angle = j * angle_step;
  23695. // position
  23696. ringVertex.x = Math.cos(-angle) * radius;
  23697. ringVertex.y = -height / 2 + h * height;
  23698. ringVertex.z = Math.sin(-angle) * radius;
  23699. // normal
  23700. if (diameterTop === 0 && i === subdivisions) {
  23701. // if no top cap, reuse former normals
  23702. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23703. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23704. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23705. }
  23706. else {
  23707. ringNormal.x = ringVertex.x;
  23708. ringNormal.z = ringVertex.z;
  23709. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23710. ringNormal.normalize();
  23711. }
  23712. // keep first ring vertex values for enclose
  23713. if (j === 0) {
  23714. ringFirstVertex.copyFrom(ringVertex);
  23715. ringFirstNormal.copyFrom(ringNormal);
  23716. }
  23717. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23718. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23719. if (hasRings) {
  23720. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23721. }
  23722. else {
  23723. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23724. }
  23725. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23726. if (faceColors) {
  23727. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23728. }
  23729. }
  23730. // if enclose, add four vertices and their dedicated normals
  23731. if (arc !== 1 && enclose) {
  23732. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23733. positions.push(0, ringVertex.y, 0);
  23734. positions.push(0, ringVertex.y, 0);
  23735. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23736. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23737. quadNormal.normalize();
  23738. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23739. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23740. quadNormal.normalize();
  23741. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23742. if (hasRings) {
  23743. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23744. }
  23745. else {
  23746. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23747. }
  23748. uvs.push(faceUV[s + 1].x, v);
  23749. uvs.push(faceUV[s + 1].z, v);
  23750. if (hasRings) {
  23751. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23752. }
  23753. else {
  23754. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23755. }
  23756. uvs.push(faceUV[s + 2].x, v);
  23757. uvs.push(faceUV[s + 2].z, v);
  23758. if (faceColors) {
  23759. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23760. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23761. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23762. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23763. }
  23764. }
  23765. if (cs !== s) {
  23766. cs = s;
  23767. }
  23768. }
  23769. }
  23770. // indices
  23771. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23772. var s;
  23773. i = 0;
  23774. for (s = 0; s < subdivisions; s++) {
  23775. for (j = 0; j < tessellation; j++) {
  23776. var i0 = i * (e + 1) + j;
  23777. var i1 = (i + 1) * (e + 1) + j;
  23778. var i2 = i * (e + 1) + (j + 1);
  23779. var i3 = (i + 1) * (e + 1) + (j + 1);
  23780. indices.push(i0, i1, i2);
  23781. indices.push(i3, i2, i1);
  23782. }
  23783. if (arc !== 1 && enclose) {
  23784. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23785. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23786. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23787. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23788. }
  23789. i = (hasRings) ? (i + 2) : (i + 1);
  23790. }
  23791. // Caps
  23792. var createCylinderCap = function (isTop) {
  23793. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23794. if (radius === 0) {
  23795. return;
  23796. }
  23797. // Cap positions, normals & uvs
  23798. var angle;
  23799. var circleVector;
  23800. var i;
  23801. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23802. var c;
  23803. if (faceColors) {
  23804. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23805. }
  23806. // cap center
  23807. var vbase = positions.length / 3;
  23808. var offset = isTop ? height / 2 : -height / 2;
  23809. var center = new BABYLON.Vector3(0, offset, 0);
  23810. positions.push(center.x, center.y, center.z);
  23811. normals.push(0, isTop ? 1 : -1, 0);
  23812. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23813. if (faceColors) {
  23814. colors.push(c.r, c.g, c.b, c.a);
  23815. }
  23816. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23817. for (i = 0; i <= tessellation; i++) {
  23818. angle = Math.PI * 2 * i * arc / tessellation;
  23819. var cos = Math.cos(-angle);
  23820. var sin = Math.sin(-angle);
  23821. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23822. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23823. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23824. normals.push(0, isTop ? 1 : -1, 0);
  23825. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23826. if (faceColors) {
  23827. colors.push(c.r, c.g, c.b, c.a);
  23828. }
  23829. }
  23830. // Cap indices
  23831. for (i = 0; i < tessellation; i++) {
  23832. if (!isTop) {
  23833. indices.push(vbase);
  23834. indices.push(vbase + (i + 1));
  23835. indices.push(vbase + (i + 2));
  23836. }
  23837. else {
  23838. indices.push(vbase);
  23839. indices.push(vbase + (i + 2));
  23840. indices.push(vbase + (i + 1));
  23841. }
  23842. }
  23843. };
  23844. // add caps to geometry
  23845. createCylinderCap(false);
  23846. createCylinderCap(true);
  23847. // Sides
  23848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23849. var vertexData = new VertexData();
  23850. vertexData.indices = indices;
  23851. vertexData.positions = positions;
  23852. vertexData.normals = normals;
  23853. vertexData.uvs = uvs;
  23854. if (faceColors) {
  23855. vertexData.colors = colors;
  23856. }
  23857. return vertexData;
  23858. };
  23859. VertexData.CreateTorus = function (options) {
  23860. var indices = [];
  23861. var positions = [];
  23862. var normals = [];
  23863. var uvs = [];
  23864. var diameter = options.diameter || 1;
  23865. var thickness = options.thickness || 0.5;
  23866. var tessellation = options.tessellation || 16;
  23867. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23868. var stride = tessellation + 1;
  23869. for (var i = 0; i <= tessellation; i++) {
  23870. var u = i / tessellation;
  23871. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23872. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23873. for (var j = 0; j <= tessellation; j++) {
  23874. var v = 1 - j / tessellation;
  23875. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23876. var dx = Math.cos(innerAngle);
  23877. var dy = Math.sin(innerAngle);
  23878. // Create a vertex.
  23879. var normal = new BABYLON.Vector3(dx, dy, 0);
  23880. var position = normal.scale(thickness / 2);
  23881. var textureCoordinate = new BABYLON.Vector2(u, v);
  23882. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23883. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23884. positions.push(position.x, position.y, position.z);
  23885. normals.push(normal.x, normal.y, normal.z);
  23886. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23887. // And create indices for two triangles.
  23888. var nextI = (i + 1) % stride;
  23889. var nextJ = (j + 1) % stride;
  23890. indices.push(i * stride + j);
  23891. indices.push(i * stride + nextJ);
  23892. indices.push(nextI * stride + j);
  23893. indices.push(i * stride + nextJ);
  23894. indices.push(nextI * stride + nextJ);
  23895. indices.push(nextI * stride + j);
  23896. }
  23897. }
  23898. // Sides
  23899. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23900. // Result
  23901. var vertexData = new VertexData();
  23902. vertexData.indices = indices;
  23903. vertexData.positions = positions;
  23904. vertexData.normals = normals;
  23905. vertexData.uvs = uvs;
  23906. return vertexData;
  23907. };
  23908. VertexData.CreateLines = function (options) {
  23909. var indices = [];
  23910. var positions = [];
  23911. var points = options.points;
  23912. for (var index = 0; index < points.length; index++) {
  23913. positions.push(points[index].x, points[index].y, points[index].z);
  23914. if (index > 0) {
  23915. indices.push(index - 1);
  23916. indices.push(index);
  23917. }
  23918. }
  23919. // Result
  23920. var vertexData = new VertexData();
  23921. vertexData.indices = indices;
  23922. vertexData.positions = positions;
  23923. return vertexData;
  23924. };
  23925. VertexData.CreateDashedLines = function (options) {
  23926. var dashSize = options.dashSize || 3;
  23927. var gapSize = options.gapSize || 1;
  23928. var dashNb = options.dashNb || 200;
  23929. var points = options.points;
  23930. var positions = new Array();
  23931. var indices = new Array();
  23932. var curvect = BABYLON.Vector3.Zero();
  23933. var lg = 0;
  23934. var nb = 0;
  23935. var shft = 0;
  23936. var dashshft = 0;
  23937. var curshft = 0;
  23938. var idx = 0;
  23939. var i = 0;
  23940. for (i = 0; i < points.length - 1; i++) {
  23941. points[i + 1].subtractToRef(points[i], curvect);
  23942. lg += curvect.length();
  23943. }
  23944. shft = lg / dashNb;
  23945. dashshft = dashSize * shft / (dashSize + gapSize);
  23946. for (i = 0; i < points.length - 1; i++) {
  23947. points[i + 1].subtractToRef(points[i], curvect);
  23948. nb = Math.floor(curvect.length() / shft);
  23949. curvect.normalize();
  23950. for (var j = 0; j < nb; j++) {
  23951. curshft = shft * j;
  23952. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23953. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23954. indices.push(idx, idx + 1);
  23955. idx += 2;
  23956. }
  23957. }
  23958. // Result
  23959. var vertexData = new VertexData();
  23960. vertexData.positions = positions;
  23961. vertexData.indices = indices;
  23962. return vertexData;
  23963. };
  23964. VertexData.CreateGround = function (options) {
  23965. var indices = [];
  23966. var positions = [];
  23967. var normals = [];
  23968. var uvs = [];
  23969. var row, col;
  23970. var width = options.width || 1;
  23971. var height = options.height || 1;
  23972. var subdivisions = options.subdivisions || 1;
  23973. for (row = 0; row <= subdivisions; row++) {
  23974. for (col = 0; col <= subdivisions; col++) {
  23975. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23976. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23977. positions.push(position.x, position.y, position.z);
  23978. normals.push(normal.x, normal.y, normal.z);
  23979. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23980. }
  23981. }
  23982. for (row = 0; row < subdivisions; row++) {
  23983. for (col = 0; col < subdivisions; col++) {
  23984. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23985. indices.push(col + 1 + row * (subdivisions + 1));
  23986. indices.push(col + row * (subdivisions + 1));
  23987. indices.push(col + (row + 1) * (subdivisions + 1));
  23988. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23989. indices.push(col + row * (subdivisions + 1));
  23990. }
  23991. }
  23992. // Result
  23993. var vertexData = new VertexData();
  23994. vertexData.indices = indices;
  23995. vertexData.positions = positions;
  23996. vertexData.normals = normals;
  23997. vertexData.uvs = uvs;
  23998. return vertexData;
  23999. };
  24000. VertexData.CreateTiledGround = function (options) {
  24001. var xmin = options.xmin;
  24002. var zmin = options.zmin;
  24003. var xmax = options.xmax;
  24004. var zmax = options.zmax;
  24005. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24006. var precision = options.precision || { w: 1, h: 1 };
  24007. var indices = [];
  24008. var positions = [];
  24009. var normals = [];
  24010. var uvs = [];
  24011. var row, col, tileRow, tileCol;
  24012. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24013. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24014. precision.w = (precision.w < 1) ? 1 : precision.w;
  24015. precision.h = (precision.h < 1) ? 1 : precision.h;
  24016. var tileSize = {
  24017. 'w': (xmax - xmin) / subdivisions.w,
  24018. 'h': (zmax - zmin) / subdivisions.h
  24019. };
  24020. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24021. // Indices
  24022. var base = positions.length / 3;
  24023. var rowLength = precision.w + 1;
  24024. for (row = 0; row < precision.h; row++) {
  24025. for (col = 0; col < precision.w; col++) {
  24026. var square = [
  24027. base + col + row * rowLength,
  24028. base + (col + 1) + row * rowLength,
  24029. base + (col + 1) + (row + 1) * rowLength,
  24030. base + col + (row + 1) * rowLength
  24031. ];
  24032. indices.push(square[1]);
  24033. indices.push(square[2]);
  24034. indices.push(square[3]);
  24035. indices.push(square[0]);
  24036. indices.push(square[1]);
  24037. indices.push(square[3]);
  24038. }
  24039. }
  24040. // Position, normals and uvs
  24041. var position = BABYLON.Vector3.Zero();
  24042. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24043. for (row = 0; row <= precision.h; row++) {
  24044. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24045. for (col = 0; col <= precision.w; col++) {
  24046. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24047. position.y = 0;
  24048. positions.push(position.x, position.y, position.z);
  24049. normals.push(normal.x, normal.y, normal.z);
  24050. uvs.push(col / precision.w, row / precision.h);
  24051. }
  24052. }
  24053. }
  24054. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24055. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24056. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24057. }
  24058. }
  24059. // Result
  24060. var vertexData = new VertexData();
  24061. vertexData.indices = indices;
  24062. vertexData.positions = positions;
  24063. vertexData.normals = normals;
  24064. vertexData.uvs = uvs;
  24065. return vertexData;
  24066. };
  24067. VertexData.CreateGroundFromHeightMap = function (options) {
  24068. var indices = [];
  24069. var positions = [];
  24070. var normals = [];
  24071. var uvs = [];
  24072. var row, col;
  24073. // Vertices
  24074. for (row = 0; row <= options.subdivisions; row++) {
  24075. for (col = 0; col <= options.subdivisions; col++) {
  24076. 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));
  24077. // Compute height
  24078. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24079. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24080. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24081. var r = options.buffer[pos] / 255.0;
  24082. var g = options.buffer[pos + 1] / 255.0;
  24083. var b = options.buffer[pos + 2] / 255.0;
  24084. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24085. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24086. // Add vertex
  24087. positions.push(position.x, position.y, position.z);
  24088. normals.push(0, 0, 0);
  24089. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24090. }
  24091. }
  24092. // Indices
  24093. for (row = 0; row < options.subdivisions; row++) {
  24094. for (col = 0; col < options.subdivisions; col++) {
  24095. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24096. indices.push(col + 1 + row * (options.subdivisions + 1));
  24097. indices.push(col + row * (options.subdivisions + 1));
  24098. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24099. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24100. indices.push(col + row * (options.subdivisions + 1));
  24101. }
  24102. }
  24103. // Normals
  24104. VertexData.ComputeNormals(positions, indices, normals);
  24105. // Result
  24106. var vertexData = new VertexData();
  24107. vertexData.indices = indices;
  24108. vertexData.positions = positions;
  24109. vertexData.normals = normals;
  24110. vertexData.uvs = uvs;
  24111. return vertexData;
  24112. };
  24113. VertexData.CreatePlane = function (options) {
  24114. var indices = [];
  24115. var positions = [];
  24116. var normals = [];
  24117. var uvs = [];
  24118. var width = options.width || options.size || 1;
  24119. var height = options.height || options.size || 1;
  24120. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24121. // Vertices
  24122. var halfWidth = width / 2.0;
  24123. var halfHeight = height / 2.0;
  24124. positions.push(-halfWidth, -halfHeight, 0);
  24125. normals.push(0, 0, -1.0);
  24126. uvs.push(0.0, 0.0);
  24127. positions.push(halfWidth, -halfHeight, 0);
  24128. normals.push(0, 0, -1.0);
  24129. uvs.push(1.0, 0.0);
  24130. positions.push(halfWidth, halfHeight, 0);
  24131. normals.push(0, 0, -1.0);
  24132. uvs.push(1.0, 1.0);
  24133. positions.push(-halfWidth, halfHeight, 0);
  24134. normals.push(0, 0, -1.0);
  24135. uvs.push(0.0, 1.0);
  24136. // Indices
  24137. indices.push(0);
  24138. indices.push(1);
  24139. indices.push(2);
  24140. indices.push(0);
  24141. indices.push(2);
  24142. indices.push(3);
  24143. // Sides
  24144. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24145. // Result
  24146. var vertexData = new VertexData();
  24147. vertexData.indices = indices;
  24148. vertexData.positions = positions;
  24149. vertexData.normals = normals;
  24150. vertexData.uvs = uvs;
  24151. return vertexData;
  24152. };
  24153. VertexData.CreateDisc = function (options) {
  24154. var positions = [];
  24155. var indices = [];
  24156. var normals = [];
  24157. var uvs = [];
  24158. var radius = options.radius || 0.5;
  24159. var tessellation = options.tessellation || 64;
  24160. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24161. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24162. // positions and uvs
  24163. positions.push(0, 0, 0); // disc center first
  24164. uvs.push(0.5, 0.5);
  24165. var theta = Math.PI * 2 * arc;
  24166. var step = theta / tessellation;
  24167. for (var a = 0; a < theta; a += step) {
  24168. var x = Math.cos(a);
  24169. var y = Math.sin(a);
  24170. var u = (x + 1) / 2;
  24171. var v = (1 - y) / 2;
  24172. positions.push(radius * x, radius * y, 0);
  24173. uvs.push(u, v);
  24174. }
  24175. if (arc === 1) {
  24176. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24177. uvs.push(uvs[2], uvs[3]);
  24178. }
  24179. //indices
  24180. var vertexNb = positions.length / 3;
  24181. for (var i = 1; i < vertexNb - 1; i++) {
  24182. indices.push(i + 1, 0, i);
  24183. }
  24184. // result
  24185. VertexData.ComputeNormals(positions, indices, normals);
  24186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24187. var vertexData = new VertexData();
  24188. vertexData.indices = indices;
  24189. vertexData.positions = positions;
  24190. vertexData.normals = normals;
  24191. vertexData.uvs = uvs;
  24192. return vertexData;
  24193. };
  24194. VertexData.CreateIcoSphere = function (options) {
  24195. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24196. var radius = options.radius || 1;
  24197. var flat = (options.flat === undefined) ? true : options.flat;
  24198. var subdivisions = options.subdivisions || 4;
  24199. var radiusX = options.radiusX || radius;
  24200. var radiusY = options.radiusY || radius;
  24201. var radiusZ = options.radiusZ || radius;
  24202. var t = (1 + Math.sqrt(5)) / 2;
  24203. // 12 vertex x,y,z
  24204. var ico_vertices = [
  24205. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24206. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24207. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24208. ];
  24209. // index of 3 vertex makes a face of icopshere
  24210. var ico_indices = [
  24211. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24212. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24213. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24214. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24215. ];
  24216. // vertex for uv have aliased position, not for UV
  24217. var vertices_unalias_id = [
  24218. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24219. // vertex alias
  24220. 0,
  24221. 2,
  24222. 3,
  24223. 3,
  24224. 3,
  24225. 4,
  24226. 7,
  24227. 8,
  24228. 9,
  24229. 9,
  24230. 10,
  24231. 11 // 23: B + 12
  24232. ];
  24233. // uv as integer step (not pixels !)
  24234. var ico_vertexuv = [
  24235. 5, 1, 3, 1, 6, 4, 0, 0,
  24236. 5, 3, 4, 2, 2, 2, 4, 0,
  24237. 2, 0, 1, 1, 6, 0, 6, 2,
  24238. // vertex alias (for same vertex on different faces)
  24239. 0, 4,
  24240. 3, 3,
  24241. 4, 4,
  24242. 3, 1,
  24243. 4, 2,
  24244. 4, 4,
  24245. 0, 2,
  24246. 1, 1,
  24247. 2, 2,
  24248. 3, 3,
  24249. 1, 3,
  24250. 2, 4 // 23: B + 12
  24251. ];
  24252. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24253. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24254. // First island of uv mapping
  24255. // v = 4h 3+ 2
  24256. // v = 3h 9+ 4
  24257. // v = 2h 9+ 5 B
  24258. // v = 1h 9 1 0
  24259. // v = 0h 3 8 7 A
  24260. // u = 0 1 2 3 4 5 6 *a
  24261. // Second island of uv mapping
  24262. // v = 4h 0+ B+ 4+
  24263. // v = 3h A+ 2+
  24264. // v = 2h 7+ 6 3+
  24265. // v = 1h 8+ 3+
  24266. // v = 0h
  24267. // u = 0 1 2 3 4 5 6 *a
  24268. // Face layout on texture UV mapping
  24269. // ============
  24270. // \ 4 /\ 16 / ======
  24271. // \ / \ / /\ 11 /
  24272. // \/ 7 \/ / \ /
  24273. // ======= / 10 \/
  24274. // /\ 17 /\ =======
  24275. // / \ / \ \ 15 /\
  24276. // / 8 \/ 12 \ \ / \
  24277. // ============ \/ 6 \
  24278. // \ 18 /\ ============
  24279. // \ / \ \ 5 /\ 0 /
  24280. // \/ 13 \ \ / \ /
  24281. // ======= \/ 1 \/
  24282. // =============
  24283. // /\ 19 /\ 2 /\
  24284. // / \ / \ / \
  24285. // / 14 \/ 9 \/ 3 \
  24286. // ===================
  24287. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24288. var ustep = 138 / 1024;
  24289. var vstep = 239 / 1024;
  24290. var uoffset = 60 / 1024;
  24291. var voffset = 26 / 1024;
  24292. // Second island should have margin, not to touch the first island
  24293. // avoid any borderline artefact in pixel rounding
  24294. var island_u_offset = -40 / 1024;
  24295. var island_v_offset = +20 / 1024;
  24296. // face is either island 0 or 1 :
  24297. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24298. var island = [
  24299. 0, 0, 0, 0, 1,
  24300. 0, 0, 1, 1, 0,
  24301. 0, 0, 1, 1, 0,
  24302. 0, 1, 1, 1, 0 // 15 - 19
  24303. ];
  24304. var indices = [];
  24305. var positions = [];
  24306. var normals = [];
  24307. var uvs = [];
  24308. var current_indice = 0;
  24309. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24310. var face_vertex_pos = new Array(3);
  24311. var face_vertex_uv = new Array(3);
  24312. var v012;
  24313. for (v012 = 0; v012 < 3; v012++) {
  24314. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24315. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24316. }
  24317. // create all with normals
  24318. for (var face = 0; face < 20; face++) {
  24319. // 3 vertex per face
  24320. for (v012 = 0; v012 < 3; v012++) {
  24321. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24322. var v_id = ico_indices[3 * face + v012];
  24323. // vertex have 3D position (x,y,z)
  24324. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  24325. // Normalize to get normal, then scale to radius
  24326. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24327. // uv Coordinates from vertex ID
  24328. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  24329. }
  24330. // Subdivide the face (interpolate pos, norm, uv)
  24331. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24332. // - norm is linear interpolation of vertex corner normal
  24333. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24334. // - uv is linear interpolation
  24335. //
  24336. // Topology is as below for sub-divide by 2
  24337. // vertex shown as v0,v1,v2
  24338. // interp index is i1 to progress in range [v0,v1[
  24339. // interp index is i2 to progress in range [v0,v2[
  24340. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24341. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24342. //
  24343. //
  24344. // i2 v2
  24345. // ^ ^
  24346. // / / \
  24347. // / / \
  24348. // / / \
  24349. // / / (0,1) \
  24350. // / #---------\
  24351. // / / \ (0,0)'/ \
  24352. // / / \ / \
  24353. // / / \ / \
  24354. // / / (0,0) \ / (1,0) \
  24355. // / #---------#---------\
  24356. // v0 v1
  24357. //
  24358. // --------------------> i1
  24359. //
  24360. // interp of (i1,i2):
  24361. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24362. // along i1 : lerp(x0,x1, i1/(S-i2))
  24363. //
  24364. // centroid of triangle is needed to get help normal computation
  24365. // (c1,c2) are used for centroid location
  24366. var interp_vertex = function (i1, i2, c1, c2) {
  24367. // vertex is interpolated from
  24368. // - face_vertex_pos[0..2]
  24369. // - face_vertex_uv[0..2]
  24370. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24371. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24372. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24373. pos_interp.normalize();
  24374. var vertex_normal;
  24375. if (flat) {
  24376. // in flat mode, recalculate normal as face centroid normal
  24377. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24378. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24379. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24380. }
  24381. else {
  24382. // in smooth mode, recalculate normal from each single vertex position
  24383. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24384. }
  24385. // Vertex normal need correction due to X,Y,Z radius scaling
  24386. vertex_normal.x /= radiusX;
  24387. vertex_normal.y /= radiusY;
  24388. vertex_normal.z /= radiusZ;
  24389. vertex_normal.normalize();
  24390. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24391. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24392. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24393. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24394. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24395. uvs.push(uv_interp.x, uv_interp.y);
  24396. // push each vertex has member of a face
  24397. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24398. indices.push(current_indice);
  24399. current_indice++;
  24400. };
  24401. for (var i2 = 0; i2 < subdivisions; i2++) {
  24402. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24403. // face : (i1,i2) for /\ :
  24404. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24405. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24406. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24407. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24408. if (i1 + i2 + 1 < subdivisions) {
  24409. // face : (i1,i2)' for \/ :
  24410. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24411. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24412. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24413. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24414. }
  24415. }
  24416. }
  24417. }
  24418. // Sides
  24419. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24420. // Result
  24421. var vertexData = new VertexData();
  24422. vertexData.indices = indices;
  24423. vertexData.positions = positions;
  24424. vertexData.normals = normals;
  24425. vertexData.uvs = uvs;
  24426. return vertexData;
  24427. };
  24428. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24429. VertexData.CreatePolyhedron = function (options) {
  24430. // provided polyhedron types :
  24431. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24432. // 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)
  24433. var polyhedra = [];
  24434. 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]] };
  24435. 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]] };
  24436. polyhedra[2] = {
  24437. 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]],
  24438. 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]]
  24439. };
  24440. polyhedra[3] = {
  24441. 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]],
  24442. 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]]
  24443. };
  24444. polyhedra[4] = {
  24445. 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]],
  24446. 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]]
  24447. };
  24448. 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]] };
  24449. 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]] };
  24450. 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]] };
  24451. 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]] };
  24452. 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]] };
  24453. 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]] };
  24454. 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]] };
  24455. 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]] };
  24456. 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]] };
  24457. polyhedra[14] = {
  24458. 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]],
  24459. 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]]
  24460. };
  24461. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24462. var size = options.size;
  24463. var sizeX = options.sizeX || size || 1;
  24464. var sizeY = options.sizeY || size || 1;
  24465. var sizeZ = options.sizeZ || size || 1;
  24466. var data = options.custom || polyhedra[type];
  24467. var nbfaces = data.face.length;
  24468. var faceUV = options.faceUV || new Array(nbfaces);
  24469. var faceColors = options.faceColors;
  24470. var flat = (options.flat === undefined) ? true : options.flat;
  24471. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24472. var positions = [];
  24473. var indices = [];
  24474. var normals = [];
  24475. var uvs = [];
  24476. var colors = [];
  24477. var index = 0;
  24478. var faceIdx = 0; // face cursor in the array "indexes"
  24479. var indexes = [];
  24480. var i = 0;
  24481. var f = 0;
  24482. var u, v, ang, x, y, tmp;
  24483. // default face colors and UV if undefined
  24484. if (flat) {
  24485. for (f = 0; f < nbfaces; f++) {
  24486. if (faceColors && faceColors[f] === undefined) {
  24487. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24488. }
  24489. if (faceUV && faceUV[f] === undefined) {
  24490. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24491. }
  24492. }
  24493. }
  24494. if (!flat) {
  24495. for (i = 0; i < data.vertex.length; i++) {
  24496. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24497. uvs.push(0, 0);
  24498. }
  24499. for (f = 0; f < nbfaces; f++) {
  24500. for (i = 0; i < data.face[f].length - 2; i++) {
  24501. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24502. }
  24503. }
  24504. }
  24505. else {
  24506. for (f = 0; f < nbfaces; f++) {
  24507. var fl = data.face[f].length; // number of vertices of the current face
  24508. ang = 2 * Math.PI / fl;
  24509. x = 0.5 * Math.tan(ang / 2);
  24510. y = 0.5;
  24511. // positions, uvs, colors
  24512. for (i = 0; i < fl; i++) {
  24513. // positions
  24514. 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);
  24515. indexes.push(index);
  24516. index++;
  24517. // uvs
  24518. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24519. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24520. uvs.push(u, v);
  24521. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24522. y = x * Math.sin(ang) + y * Math.cos(ang);
  24523. x = tmp;
  24524. // colors
  24525. if (faceColors) {
  24526. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24527. }
  24528. }
  24529. // indices from indexes
  24530. for (i = 0; i < fl - 2; i++) {
  24531. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24532. }
  24533. faceIdx += fl;
  24534. }
  24535. }
  24536. VertexData.ComputeNormals(positions, indices, normals);
  24537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24538. var vertexData = new VertexData();
  24539. vertexData.positions = positions;
  24540. vertexData.indices = indices;
  24541. vertexData.normals = normals;
  24542. vertexData.uvs = uvs;
  24543. if (faceColors && flat) {
  24544. vertexData.colors = colors;
  24545. }
  24546. return vertexData;
  24547. };
  24548. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24549. VertexData.CreateTorusKnot = function (options) {
  24550. var indices = [];
  24551. var positions = [];
  24552. var normals = [];
  24553. var uvs = [];
  24554. var radius = options.radius || 2;
  24555. var tube = options.tube || 0.5;
  24556. var radialSegments = options.radialSegments || 32;
  24557. var tubularSegments = options.tubularSegments || 32;
  24558. var p = options.p || 2;
  24559. var q = options.q || 3;
  24560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24561. // Helper
  24562. var getPos = function (angle) {
  24563. var cu = Math.cos(angle);
  24564. var su = Math.sin(angle);
  24565. var quOverP = q / p * angle;
  24566. var cs = Math.cos(quOverP);
  24567. var tx = radius * (2 + cs) * 0.5 * cu;
  24568. var ty = radius * (2 + cs) * su * 0.5;
  24569. var tz = radius * Math.sin(quOverP) * 0.5;
  24570. return new BABYLON.Vector3(tx, ty, tz);
  24571. };
  24572. // Vertices
  24573. var i;
  24574. var j;
  24575. for (i = 0; i <= radialSegments; i++) {
  24576. var modI = i % radialSegments;
  24577. var u = modI / radialSegments * 2 * p * Math.PI;
  24578. var p1 = getPos(u);
  24579. var p2 = getPos(u + 0.01);
  24580. var tang = p2.subtract(p1);
  24581. var n = p2.add(p1);
  24582. var bitan = BABYLON.Vector3.Cross(tang, n);
  24583. n = BABYLON.Vector3.Cross(bitan, tang);
  24584. bitan.normalize();
  24585. n.normalize();
  24586. for (j = 0; j < tubularSegments; j++) {
  24587. var modJ = j % tubularSegments;
  24588. var v = modJ / tubularSegments * 2 * Math.PI;
  24589. var cx = -tube * Math.cos(v);
  24590. var cy = tube * Math.sin(v);
  24591. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24592. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24593. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24594. uvs.push(i / radialSegments);
  24595. uvs.push(j / tubularSegments);
  24596. }
  24597. }
  24598. for (i = 0; i < radialSegments; i++) {
  24599. for (j = 0; j < tubularSegments; j++) {
  24600. var jNext = (j + 1) % tubularSegments;
  24601. var a = i * tubularSegments + j;
  24602. var b = (i + 1) * tubularSegments + j;
  24603. var c = (i + 1) * tubularSegments + jNext;
  24604. var d = i * tubularSegments + jNext;
  24605. indices.push(d);
  24606. indices.push(b);
  24607. indices.push(a);
  24608. indices.push(d);
  24609. indices.push(c);
  24610. indices.push(b);
  24611. }
  24612. }
  24613. // Normals
  24614. VertexData.ComputeNormals(positions, indices, normals);
  24615. // Sides
  24616. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24617. // Result
  24618. var vertexData = new VertexData();
  24619. vertexData.indices = indices;
  24620. vertexData.positions = positions;
  24621. vertexData.normals = normals;
  24622. vertexData.uvs = uvs;
  24623. return vertexData;
  24624. };
  24625. // Tools
  24626. /**
  24627. * @param {any} - positions (number[] or Float32Array)
  24628. * @param {any} - indices (number[] or Uint16Array)
  24629. * @param {any} - normals (number[] or Float32Array)
  24630. */
  24631. VertexData.ComputeNormals = function (positions, indices, normals) {
  24632. var index = 0;
  24633. var p1p2x = 0.0;
  24634. var p1p2y = 0.0;
  24635. var p1p2z = 0.0;
  24636. var p3p2x = 0.0;
  24637. var p3p2y = 0.0;
  24638. var p3p2z = 0.0;
  24639. var faceNormalx = 0.0;
  24640. var faceNormaly = 0.0;
  24641. var faceNormalz = 0.0;
  24642. var length = 0.0;
  24643. var i1 = 0;
  24644. var i2 = 0;
  24645. var i3 = 0;
  24646. for (index = 0; index < positions.length; index++) {
  24647. normals[index] = 0.0;
  24648. }
  24649. // indice triplet = 1 face
  24650. var nbFaces = indices.length / 3;
  24651. for (index = 0; index < nbFaces; index++) {
  24652. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24653. i2 = indices[index * 3 + 1];
  24654. i3 = indices[index * 3 + 2];
  24655. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24656. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24657. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24658. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24659. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24660. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24661. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24662. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24663. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24664. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24665. length = (length === 0) ? 1.0 : length;
  24666. faceNormalx /= length; // normalize this normal
  24667. faceNormaly /= length;
  24668. faceNormalz /= length;
  24669. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24670. normals[i1 * 3 + 1] += faceNormaly;
  24671. normals[i1 * 3 + 2] += faceNormalz;
  24672. normals[i2 * 3] += faceNormalx;
  24673. normals[i2 * 3 + 1] += faceNormaly;
  24674. normals[i2 * 3 + 2] += faceNormalz;
  24675. normals[i3 * 3] += faceNormalx;
  24676. normals[i3 * 3 + 1] += faceNormaly;
  24677. normals[i3 * 3 + 2] += faceNormalz;
  24678. }
  24679. // last normalization of each normal
  24680. for (index = 0; index < normals.length / 3; index++) {
  24681. faceNormalx = normals[index * 3];
  24682. faceNormaly = normals[index * 3 + 1];
  24683. faceNormalz = normals[index * 3 + 2];
  24684. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24685. length = (length === 0) ? 1.0 : length;
  24686. faceNormalx /= length;
  24687. faceNormaly /= length;
  24688. faceNormalz /= length;
  24689. normals[index * 3] = faceNormalx;
  24690. normals[index * 3 + 1] = faceNormaly;
  24691. normals[index * 3 + 2] = faceNormalz;
  24692. }
  24693. };
  24694. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24695. var li = indices.length;
  24696. var ln = normals.length;
  24697. var i;
  24698. var n;
  24699. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24700. switch (sideOrientation) {
  24701. case BABYLON.Mesh.FRONTSIDE:
  24702. // nothing changed
  24703. break;
  24704. case BABYLON.Mesh.BACKSIDE:
  24705. var tmp;
  24706. // indices
  24707. for (i = 0; i < li; i += 3) {
  24708. tmp = indices[i];
  24709. indices[i] = indices[i + 2];
  24710. indices[i + 2] = tmp;
  24711. }
  24712. // normals
  24713. for (n = 0; n < ln; n++) {
  24714. normals[n] = -normals[n];
  24715. }
  24716. break;
  24717. case BABYLON.Mesh.DOUBLESIDE:
  24718. // positions
  24719. var lp = positions.length;
  24720. var l = lp / 3;
  24721. for (var p = 0; p < lp; p++) {
  24722. positions[lp + p] = positions[p];
  24723. }
  24724. // indices
  24725. for (i = 0; i < li; i += 3) {
  24726. indices[i + li] = indices[i + 2] + l;
  24727. indices[i + 1 + li] = indices[i + 1] + l;
  24728. indices[i + 2 + li] = indices[i] + l;
  24729. }
  24730. // normals
  24731. for (n = 0; n < ln; n++) {
  24732. normals[ln + n] = -normals[n];
  24733. }
  24734. // uvs
  24735. var lu = uvs.length;
  24736. for (var u = 0; u < lu; u++) {
  24737. uvs[u + lu] = uvs[u];
  24738. }
  24739. break;
  24740. }
  24741. };
  24742. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24743. var vertexData = new VertexData();
  24744. // positions
  24745. var positions = parsedVertexData.positions;
  24746. if (positions) {
  24747. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24748. }
  24749. // normals
  24750. var normals = parsedVertexData.normals;
  24751. if (normals) {
  24752. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24753. }
  24754. // uvs
  24755. var uvs = parsedVertexData.uvs;
  24756. if (uvs) {
  24757. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24758. }
  24759. // uv2s
  24760. var uv2s = parsedVertexData.uv2s;
  24761. if (uv2s) {
  24762. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24763. }
  24764. // uv3s
  24765. var uv3s = parsedVertexData.uv3s;
  24766. if (uv3s) {
  24767. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24768. }
  24769. // uv4s
  24770. var uv4s = parsedVertexData.uv4s;
  24771. if (uv4s) {
  24772. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24773. }
  24774. // uv5s
  24775. var uv5s = parsedVertexData.uv5s;
  24776. if (uv5s) {
  24777. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24778. }
  24779. // uv6s
  24780. var uv6s = parsedVertexData.uv6s;
  24781. if (uv6s) {
  24782. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24783. }
  24784. // colors
  24785. var colors = parsedVertexData.colors;
  24786. if (colors) {
  24787. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24788. }
  24789. // matricesIndices
  24790. var matricesIndices = parsedVertexData.matricesIndices;
  24791. if (matricesIndices) {
  24792. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24793. }
  24794. // matricesWeights
  24795. var matricesWeights = parsedVertexData.matricesWeights;
  24796. if (matricesWeights) {
  24797. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24798. }
  24799. // indices
  24800. var indices = parsedVertexData.indices;
  24801. if (indices) {
  24802. vertexData.indices = indices;
  24803. }
  24804. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24805. };
  24806. return VertexData;
  24807. })();
  24808. BABYLON.VertexData = VertexData;
  24809. })(BABYLON || (BABYLON = {}));
  24810. var BABYLON;
  24811. (function (BABYLON) {
  24812. var Tags = (function () {
  24813. function Tags() {
  24814. }
  24815. Tags.EnableFor = function (obj) {
  24816. obj._tags = obj._tags || {};
  24817. obj.hasTags = function () {
  24818. return Tags.HasTags(obj);
  24819. };
  24820. obj.addTags = function (tagsString) {
  24821. return Tags.AddTagsTo(obj, tagsString);
  24822. };
  24823. obj.removeTags = function (tagsString) {
  24824. return Tags.RemoveTagsFrom(obj, tagsString);
  24825. };
  24826. obj.matchesTagsQuery = function (tagsQuery) {
  24827. return Tags.MatchesQuery(obj, tagsQuery);
  24828. };
  24829. };
  24830. Tags.DisableFor = function (obj) {
  24831. delete obj._tags;
  24832. delete obj.hasTags;
  24833. delete obj.addTags;
  24834. delete obj.removeTags;
  24835. delete obj.matchesTagsQuery;
  24836. };
  24837. Tags.HasTags = function (obj) {
  24838. if (!obj._tags) {
  24839. return false;
  24840. }
  24841. return !BABYLON.Tools.IsEmpty(obj._tags);
  24842. };
  24843. Tags.GetTags = function (obj) {
  24844. if (!obj._tags) {
  24845. return null;
  24846. }
  24847. return obj._tags;
  24848. };
  24849. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24850. // a tag cannot start with '||', '&&', and '!'
  24851. // it cannot contain whitespaces
  24852. Tags.AddTagsTo = function (obj, tagsString) {
  24853. if (!tagsString) {
  24854. return;
  24855. }
  24856. if (typeof tagsString !== "string") {
  24857. return;
  24858. }
  24859. var tags = tagsString.split(" ");
  24860. for (var t in tags) {
  24861. Tags._AddTagTo(obj, tags[t]);
  24862. }
  24863. };
  24864. Tags._AddTagTo = function (obj, tag) {
  24865. tag = tag.trim();
  24866. if (tag === "" || tag === "true" || tag === "false") {
  24867. return;
  24868. }
  24869. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24870. return;
  24871. }
  24872. Tags.EnableFor(obj);
  24873. obj._tags[tag] = true;
  24874. };
  24875. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24876. if (!Tags.HasTags(obj)) {
  24877. return;
  24878. }
  24879. var tags = tagsString.split(" ");
  24880. for (var t in tags) {
  24881. Tags._RemoveTagFrom(obj, tags[t]);
  24882. }
  24883. };
  24884. Tags._RemoveTagFrom = function (obj, tag) {
  24885. delete obj._tags[tag];
  24886. };
  24887. Tags.MatchesQuery = function (obj, tagsQuery) {
  24888. if (tagsQuery === undefined) {
  24889. return true;
  24890. }
  24891. if (tagsQuery === "") {
  24892. return Tags.HasTags(obj);
  24893. }
  24894. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24895. };
  24896. return Tags;
  24897. })();
  24898. BABYLON.Tags = Tags;
  24899. })(BABYLON || (BABYLON = {}));
  24900. var BABYLON;
  24901. (function (BABYLON) {
  24902. var Internals;
  24903. (function (Internals) {
  24904. var AndOrNotEvaluator = (function () {
  24905. function AndOrNotEvaluator() {
  24906. }
  24907. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24908. if (!query.match(/\([^\(\)]*\)/g)) {
  24909. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24910. }
  24911. else {
  24912. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24913. // remove parenthesis
  24914. r = r.slice(1, r.length - 1);
  24915. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24916. });
  24917. }
  24918. if (query === "true") {
  24919. return true;
  24920. }
  24921. if (query === "false") {
  24922. return false;
  24923. }
  24924. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24925. };
  24926. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24927. evaluateCallback = evaluateCallback || (function (r) {
  24928. return r === "true" ? true : false;
  24929. });
  24930. var result;
  24931. var or = parenthesisContent.split("||");
  24932. for (var i in or) {
  24933. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24934. var and = ori.split("&&");
  24935. if (and.length > 1) {
  24936. for (var j = 0; j < and.length; ++j) {
  24937. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24938. if (andj !== "true" && andj !== "false") {
  24939. if (andj[0] === "!") {
  24940. result = !evaluateCallback(andj.substring(1));
  24941. }
  24942. else {
  24943. result = evaluateCallback(andj);
  24944. }
  24945. }
  24946. else {
  24947. result = andj === "true" ? true : false;
  24948. }
  24949. if (!result) {
  24950. ori = "false";
  24951. break;
  24952. }
  24953. }
  24954. }
  24955. if (result || ori === "true") {
  24956. result = true;
  24957. break;
  24958. }
  24959. // result equals false (or undefined)
  24960. if (ori !== "true" && ori !== "false") {
  24961. if (ori[0] === "!") {
  24962. result = !evaluateCallback(ori.substring(1));
  24963. }
  24964. else {
  24965. result = evaluateCallback(ori);
  24966. }
  24967. }
  24968. else {
  24969. result = ori === "true" ? true : false;
  24970. }
  24971. }
  24972. // the whole parenthesis scope is replaced by 'true' or 'false'
  24973. return result ? "true" : "false";
  24974. };
  24975. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24976. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24977. // remove whitespaces
  24978. r = r.replace(/[\s]/g, function () { return ""; });
  24979. return r.length % 2 ? "!" : "";
  24980. });
  24981. booleanString = booleanString.trim();
  24982. if (booleanString === "!true") {
  24983. booleanString = "false";
  24984. }
  24985. else if (booleanString === "!false") {
  24986. booleanString = "true";
  24987. }
  24988. return booleanString;
  24989. };
  24990. return AndOrNotEvaluator;
  24991. })();
  24992. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24993. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24994. })(BABYLON || (BABYLON = {}));
  24995. var BABYLON;
  24996. (function (BABYLON) {
  24997. var PostProcessRenderPass = (function () {
  24998. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24999. this._enabled = true;
  25000. this._refCount = 0;
  25001. this._name = name;
  25002. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25003. this.setRenderList(renderList);
  25004. this._renderTexture.onBeforeRender = beforeRender;
  25005. this._renderTexture.onAfterRender = afterRender;
  25006. this._scene = scene;
  25007. this._renderList = renderList;
  25008. }
  25009. // private
  25010. PostProcessRenderPass.prototype._incRefCount = function () {
  25011. if (this._refCount === 0) {
  25012. this._scene.customRenderTargets.push(this._renderTexture);
  25013. }
  25014. return ++this._refCount;
  25015. };
  25016. PostProcessRenderPass.prototype._decRefCount = function () {
  25017. this._refCount--;
  25018. if (this._refCount <= 0) {
  25019. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25020. }
  25021. return this._refCount;
  25022. };
  25023. PostProcessRenderPass.prototype._update = function () {
  25024. this.setRenderList(this._renderList);
  25025. };
  25026. // public
  25027. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25028. this._renderTexture.renderList = renderList;
  25029. };
  25030. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25031. return this._renderTexture;
  25032. };
  25033. return PostProcessRenderPass;
  25034. })();
  25035. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25036. })(BABYLON || (BABYLON = {}));
  25037. var BABYLON;
  25038. (function (BABYLON) {
  25039. var PostProcessRenderEffect = (function () {
  25040. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25041. this._engine = engine;
  25042. this._name = name;
  25043. this._singleInstance = singleInstance || true;
  25044. this._getPostProcess = getPostProcess;
  25045. this._cameras = [];
  25046. this._indicesForCamera = [];
  25047. this._postProcesses = {};
  25048. this._renderPasses = {};
  25049. this._renderEffectAsPasses = {};
  25050. }
  25051. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25052. get: function () {
  25053. for (var index in this._postProcesses) {
  25054. if (!this._postProcesses[index].isSupported) {
  25055. return false;
  25056. }
  25057. }
  25058. return true;
  25059. },
  25060. enumerable: true,
  25061. configurable: true
  25062. });
  25063. PostProcessRenderEffect.prototype._update = function () {
  25064. for (var renderPassName in this._renderPasses) {
  25065. this._renderPasses[renderPassName]._update();
  25066. }
  25067. };
  25068. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25069. this._renderPasses[renderPass._name] = renderPass;
  25070. this._linkParameters();
  25071. };
  25072. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25073. delete this._renderPasses[renderPass._name];
  25074. this._linkParameters();
  25075. };
  25076. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25077. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25078. this._linkParameters();
  25079. };
  25080. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25081. for (var renderPassName in this._renderPasses) {
  25082. if (renderPassName === passName) {
  25083. return this._renderPasses[passName];
  25084. }
  25085. }
  25086. };
  25087. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25088. this._renderPasses = {};
  25089. this._linkParameters();
  25090. };
  25091. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25092. var cameraKey;
  25093. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25094. for (var i = 0; i < _cam.length; i++) {
  25095. var camera = _cam[i];
  25096. var cameraName = camera.name;
  25097. if (this._singleInstance) {
  25098. cameraKey = 0;
  25099. }
  25100. else {
  25101. cameraKey = cameraName;
  25102. }
  25103. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25104. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25105. if (!this._indicesForCamera[cameraName]) {
  25106. this._indicesForCamera[cameraName] = [];
  25107. }
  25108. this._indicesForCamera[cameraName].push(index);
  25109. if (this._cameras.indexOf(camera) === -1) {
  25110. this._cameras[cameraName] = camera;
  25111. }
  25112. for (var passName in this._renderPasses) {
  25113. this._renderPasses[passName]._incRefCount();
  25114. }
  25115. }
  25116. this._linkParameters();
  25117. };
  25118. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25119. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25120. for (var i = 0; i < _cam.length; i++) {
  25121. var camera = _cam[i];
  25122. var cameraName = camera.name;
  25123. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25124. var index = this._cameras.indexOf(cameraName);
  25125. this._indicesForCamera.splice(index, 1);
  25126. this._cameras.splice(index, 1);
  25127. for (var passName in this._renderPasses) {
  25128. this._renderPasses[passName]._decRefCount();
  25129. }
  25130. }
  25131. };
  25132. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25133. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25134. for (var i = 0; i < _cam.length; i++) {
  25135. var camera = _cam[i];
  25136. var cameraName = camera.name;
  25137. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25138. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25139. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25140. }
  25141. }
  25142. for (var passName in this._renderPasses) {
  25143. this._renderPasses[passName]._incRefCount();
  25144. }
  25145. }
  25146. };
  25147. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25148. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25149. for (var i = 0; i < _cam.length; i++) {
  25150. var camera = _cam[i];
  25151. var cameraName = camera.Name;
  25152. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25153. for (var passName in this._renderPasses) {
  25154. this._renderPasses[passName]._decRefCount();
  25155. }
  25156. }
  25157. };
  25158. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25159. if (this._singleInstance) {
  25160. return this._postProcesses[0];
  25161. }
  25162. else {
  25163. return this._postProcesses[camera.name];
  25164. }
  25165. };
  25166. PostProcessRenderEffect.prototype._linkParameters = function () {
  25167. var _this = this;
  25168. for (var index in this._postProcesses) {
  25169. if (this.applyParameters) {
  25170. this.applyParameters(this._postProcesses[index]);
  25171. }
  25172. this._postProcesses[index].onBeforeRender = function (effect) {
  25173. _this._linkTextures(effect);
  25174. };
  25175. }
  25176. };
  25177. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25178. for (var renderPassName in this._renderPasses) {
  25179. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25180. }
  25181. for (var renderEffectName in this._renderEffectAsPasses) {
  25182. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25183. }
  25184. };
  25185. return PostProcessRenderEffect;
  25186. })();
  25187. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25188. })(BABYLON || (BABYLON = {}));
  25189. var BABYLON;
  25190. (function (BABYLON) {
  25191. var PostProcessRenderPipeline = (function () {
  25192. function PostProcessRenderPipeline(engine, name) {
  25193. this._engine = engine;
  25194. this._name = name;
  25195. this._renderEffects = {};
  25196. this._renderEffectsForIsolatedPass = {};
  25197. this._cameras = [];
  25198. }
  25199. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25200. get: function () {
  25201. for (var renderEffectName in this._renderEffects) {
  25202. if (!this._renderEffects[renderEffectName].isSupported) {
  25203. return false;
  25204. }
  25205. }
  25206. return true;
  25207. },
  25208. enumerable: true,
  25209. configurable: true
  25210. });
  25211. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25212. this._renderEffects[renderEffect._name] = renderEffect;
  25213. };
  25214. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25215. var renderEffects = this._renderEffects[renderEffectName];
  25216. if (!renderEffects) {
  25217. return;
  25218. }
  25219. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25220. };
  25221. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25222. var renderEffects = this._renderEffects[renderEffectName];
  25223. if (!renderEffects) {
  25224. return;
  25225. }
  25226. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25227. };
  25228. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25229. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25230. var indicesToDelete = [];
  25231. var i;
  25232. for (i = 0; i < _cam.length; i++) {
  25233. var camera = _cam[i];
  25234. var cameraName = camera.name;
  25235. if (this._cameras.indexOf(camera) === -1) {
  25236. this._cameras[cameraName] = camera;
  25237. }
  25238. else if (unique) {
  25239. indicesToDelete.push(i);
  25240. }
  25241. }
  25242. for (i = 0; i < indicesToDelete.length; i++) {
  25243. cameras.splice(indicesToDelete[i], 1);
  25244. }
  25245. for (var renderEffectName in this._renderEffects) {
  25246. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25247. }
  25248. };
  25249. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25250. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25251. for (var renderEffectName in this._renderEffects) {
  25252. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25253. }
  25254. for (var i = 0; i < _cam.length; i++) {
  25255. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25256. }
  25257. };
  25258. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25259. var _this = this;
  25260. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25261. var pass = null;
  25262. var renderEffectName;
  25263. for (renderEffectName in this._renderEffects) {
  25264. pass = this._renderEffects[renderEffectName].getPass(passName);
  25265. if (pass != null) {
  25266. break;
  25267. }
  25268. }
  25269. if (pass === null) {
  25270. return;
  25271. }
  25272. for (renderEffectName in this._renderEffects) {
  25273. this._renderEffects[renderEffectName]._disable(_cam);
  25274. }
  25275. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25276. for (var i = 0; i < _cam.length; i++) {
  25277. var camera = _cam[i];
  25278. var cameraName = camera.name;
  25279. 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); });
  25280. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25281. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25282. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25283. }
  25284. };
  25285. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25286. var _this = this;
  25287. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25288. for (var i = 0; i < _cam.length; i++) {
  25289. var camera = _cam[i];
  25290. var cameraName = camera.name;
  25291. 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); });
  25292. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25293. }
  25294. for (var renderEffectName in this._renderEffects) {
  25295. this._renderEffects[renderEffectName]._enable(_cam);
  25296. }
  25297. };
  25298. PostProcessRenderPipeline.prototype._update = function () {
  25299. for (var renderEffectName in this._renderEffects) {
  25300. this._renderEffects[renderEffectName]._update();
  25301. }
  25302. for (var i = 0; i < this._cameras.length; i++) {
  25303. var cameraName = this._cameras[i].name;
  25304. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25305. this._renderEffectsForIsolatedPass[cameraName]._update();
  25306. }
  25307. }
  25308. };
  25309. PostProcessRenderPipeline.prototype.dispose = function () {
  25310. // Must be implemented by children
  25311. };
  25312. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25313. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25314. return PostProcessRenderPipeline;
  25315. })();
  25316. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25317. })(BABYLON || (BABYLON = {}));
  25318. var BABYLON;
  25319. (function (BABYLON) {
  25320. var PostProcessRenderPipelineManager = (function () {
  25321. function PostProcessRenderPipelineManager() {
  25322. this._renderPipelines = {};
  25323. }
  25324. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25325. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25326. };
  25327. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25328. var renderPipeline = this._renderPipelines[renderPipelineName];
  25329. if (!renderPipeline) {
  25330. return;
  25331. }
  25332. renderPipeline._attachCameras(cameras, unique);
  25333. };
  25334. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25335. var renderPipeline = this._renderPipelines[renderPipelineName];
  25336. if (!renderPipeline) {
  25337. return;
  25338. }
  25339. renderPipeline._detachCameras(cameras);
  25340. };
  25341. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25342. var renderPipeline = this._renderPipelines[renderPipelineName];
  25343. if (!renderPipeline) {
  25344. return;
  25345. }
  25346. renderPipeline._enableEffect(renderEffectName, cameras);
  25347. };
  25348. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25349. var renderPipeline = this._renderPipelines[renderPipelineName];
  25350. if (!renderPipeline) {
  25351. return;
  25352. }
  25353. renderPipeline._disableEffect(renderEffectName, cameras);
  25354. };
  25355. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25356. var renderPipeline = this._renderPipelines[renderPipelineName];
  25357. if (!renderPipeline) {
  25358. return;
  25359. }
  25360. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25361. };
  25362. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25363. var renderPipeline = this._renderPipelines[renderPipelineName];
  25364. if (!renderPipeline) {
  25365. return;
  25366. }
  25367. renderPipeline._disableDisplayOnlyPass(cameras);
  25368. };
  25369. PostProcessRenderPipelineManager.prototype.update = function () {
  25370. for (var renderPipelineName in this._renderPipelines) {
  25371. var pipeline = this._renderPipelines[renderPipelineName];
  25372. if (!pipeline.isSupported) {
  25373. pipeline.dispose();
  25374. delete this._renderPipelines[renderPipelineName];
  25375. }
  25376. else {
  25377. pipeline._update();
  25378. }
  25379. }
  25380. };
  25381. return PostProcessRenderPipelineManager;
  25382. })();
  25383. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25384. })(BABYLON || (BABYLON = {}));
  25385. var BABYLON;
  25386. (function (BABYLON) {
  25387. var BoundingBoxRenderer = (function () {
  25388. function BoundingBoxRenderer(scene) {
  25389. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25390. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25391. this.showBackLines = true;
  25392. this.renderList = new BABYLON.SmartArray(32);
  25393. this._scene = scene;
  25394. }
  25395. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25396. if (this._colorShader) {
  25397. return;
  25398. }
  25399. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25400. attributes: ["position"],
  25401. uniforms: ["worldViewProjection", "color"]
  25402. });
  25403. var engine = this._scene.getEngine();
  25404. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25405. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25406. 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]);
  25407. };
  25408. BoundingBoxRenderer.prototype.reset = function () {
  25409. this.renderList.reset();
  25410. };
  25411. BoundingBoxRenderer.prototype.render = function () {
  25412. if (this.renderList.length === 0) {
  25413. return;
  25414. }
  25415. this._prepareRessources();
  25416. if (!this._colorShader.isReady()) {
  25417. return;
  25418. }
  25419. var engine = this._scene.getEngine();
  25420. engine.setDepthWrite(false);
  25421. this._colorShader._preBind();
  25422. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25423. var boundingBox = this.renderList.data[boundingBoxIndex];
  25424. var min = boundingBox.minimum;
  25425. var max = boundingBox.maximum;
  25426. var diff = max.subtract(min);
  25427. var median = min.add(diff.scale(0.5));
  25428. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25429. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25430. .multiply(boundingBox.getWorldMatrix());
  25431. // VBOs
  25432. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25433. if (this.showBackLines) {
  25434. // Back
  25435. engine.setDepthFunctionToGreaterOrEqual();
  25436. this._scene.resetCachedMaterial();
  25437. this._colorShader.setColor4("color", this.backColor.toColor4());
  25438. this._colorShader.bind(worldMatrix);
  25439. // Draw order
  25440. engine.draw(false, 0, 24);
  25441. }
  25442. // Front
  25443. engine.setDepthFunctionToLess();
  25444. this._scene.resetCachedMaterial();
  25445. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25446. this._colorShader.bind(worldMatrix);
  25447. // Draw order
  25448. engine.draw(false, 0, 24);
  25449. }
  25450. this._colorShader.unbind();
  25451. engine.setDepthFunctionToLessOrEqual();
  25452. engine.setDepthWrite(true);
  25453. };
  25454. BoundingBoxRenderer.prototype.dispose = function () {
  25455. if (!this._colorShader) {
  25456. return;
  25457. }
  25458. this._colorShader.dispose();
  25459. this._vb.dispose();
  25460. this._scene.getEngine()._releaseBuffer(this._ib);
  25461. };
  25462. return BoundingBoxRenderer;
  25463. })();
  25464. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25465. })(BABYLON || (BABYLON = {}));
  25466. var BABYLON;
  25467. (function (BABYLON) {
  25468. var Condition = (function () {
  25469. function Condition(actionManager) {
  25470. this._actionManager = actionManager;
  25471. }
  25472. Condition.prototype.isValid = function () {
  25473. return true;
  25474. };
  25475. Condition.prototype._getProperty = function (propertyPath) {
  25476. return this._actionManager._getProperty(propertyPath);
  25477. };
  25478. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25479. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25480. };
  25481. return Condition;
  25482. })();
  25483. BABYLON.Condition = Condition;
  25484. var ValueCondition = (function (_super) {
  25485. __extends(ValueCondition, _super);
  25486. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25487. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25488. _super.call(this, actionManager);
  25489. this.propertyPath = propertyPath;
  25490. this.value = value;
  25491. this.operator = operator;
  25492. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25493. this._property = this._getProperty(this.propertyPath);
  25494. }
  25495. Object.defineProperty(ValueCondition, "IsEqual", {
  25496. get: function () {
  25497. return ValueCondition._IsEqual;
  25498. },
  25499. enumerable: true,
  25500. configurable: true
  25501. });
  25502. Object.defineProperty(ValueCondition, "IsDifferent", {
  25503. get: function () {
  25504. return ValueCondition._IsDifferent;
  25505. },
  25506. enumerable: true,
  25507. configurable: true
  25508. });
  25509. Object.defineProperty(ValueCondition, "IsGreater", {
  25510. get: function () {
  25511. return ValueCondition._IsGreater;
  25512. },
  25513. enumerable: true,
  25514. configurable: true
  25515. });
  25516. Object.defineProperty(ValueCondition, "IsLesser", {
  25517. get: function () {
  25518. return ValueCondition._IsLesser;
  25519. },
  25520. enumerable: true,
  25521. configurable: true
  25522. });
  25523. // Methods
  25524. ValueCondition.prototype.isValid = function () {
  25525. switch (this.operator) {
  25526. case ValueCondition.IsGreater:
  25527. return this._target[this._property] > this.value;
  25528. case ValueCondition.IsLesser:
  25529. return this._target[this._property] < this.value;
  25530. case ValueCondition.IsEqual:
  25531. case ValueCondition.IsDifferent:
  25532. var check;
  25533. if (this.value.equals) {
  25534. check = this.value.equals(this._target[this._property]);
  25535. }
  25536. else {
  25537. check = this.value === this._target[this._property];
  25538. }
  25539. return this.operator === ValueCondition.IsEqual ? check : !check;
  25540. }
  25541. return false;
  25542. };
  25543. // Statics
  25544. ValueCondition._IsEqual = 0;
  25545. ValueCondition._IsDifferent = 1;
  25546. ValueCondition._IsGreater = 2;
  25547. ValueCondition._IsLesser = 3;
  25548. return ValueCondition;
  25549. })(Condition);
  25550. BABYLON.ValueCondition = ValueCondition;
  25551. var PredicateCondition = (function (_super) {
  25552. __extends(PredicateCondition, _super);
  25553. function PredicateCondition(actionManager, predicate) {
  25554. _super.call(this, actionManager);
  25555. this.predicate = predicate;
  25556. }
  25557. PredicateCondition.prototype.isValid = function () {
  25558. return this.predicate();
  25559. };
  25560. return PredicateCondition;
  25561. })(Condition);
  25562. BABYLON.PredicateCondition = PredicateCondition;
  25563. var StateCondition = (function (_super) {
  25564. __extends(StateCondition, _super);
  25565. function StateCondition(actionManager, target, value) {
  25566. _super.call(this, actionManager);
  25567. this.value = value;
  25568. this._target = target;
  25569. }
  25570. // Methods
  25571. StateCondition.prototype.isValid = function () {
  25572. return this._target.state === this.value;
  25573. };
  25574. return StateCondition;
  25575. })(Condition);
  25576. BABYLON.StateCondition = StateCondition;
  25577. })(BABYLON || (BABYLON = {}));
  25578. var BABYLON;
  25579. (function (BABYLON) {
  25580. var Action = (function () {
  25581. function Action(triggerOptions, condition) {
  25582. this.triggerOptions = triggerOptions;
  25583. if (triggerOptions.parameter) {
  25584. this.trigger = triggerOptions.trigger;
  25585. this._triggerParameter = triggerOptions.parameter;
  25586. }
  25587. else {
  25588. this.trigger = triggerOptions;
  25589. }
  25590. this._nextActiveAction = this;
  25591. this._condition = condition;
  25592. }
  25593. // Methods
  25594. Action.prototype._prepare = function () {
  25595. };
  25596. Action.prototype.getTriggerParameter = function () {
  25597. return this._triggerParameter;
  25598. };
  25599. Action.prototype._executeCurrent = function (evt) {
  25600. if (this._nextActiveAction._condition) {
  25601. var condition = this._nextActiveAction._condition;
  25602. var currentRenderId = this._actionManager.getScene().getRenderId();
  25603. // We cache the current evaluation for the current frame
  25604. if (condition._evaluationId === currentRenderId) {
  25605. if (!condition._currentResult) {
  25606. return;
  25607. }
  25608. }
  25609. else {
  25610. condition._evaluationId = currentRenderId;
  25611. if (!condition.isValid()) {
  25612. condition._currentResult = false;
  25613. return;
  25614. }
  25615. condition._currentResult = true;
  25616. }
  25617. }
  25618. this._nextActiveAction.execute(evt);
  25619. this.skipToNextActiveAction();
  25620. };
  25621. Action.prototype.execute = function (evt) {
  25622. };
  25623. Action.prototype.skipToNextActiveAction = function () {
  25624. if (this._nextActiveAction._child) {
  25625. if (!this._nextActiveAction._child._actionManager) {
  25626. this._nextActiveAction._child._actionManager = this._actionManager;
  25627. }
  25628. this._nextActiveAction = this._nextActiveAction._child;
  25629. }
  25630. else {
  25631. this._nextActiveAction = this;
  25632. }
  25633. };
  25634. Action.prototype.then = function (action) {
  25635. this._child = action;
  25636. action._actionManager = this._actionManager;
  25637. action._prepare();
  25638. return action;
  25639. };
  25640. Action.prototype._getProperty = function (propertyPath) {
  25641. return this._actionManager._getProperty(propertyPath);
  25642. };
  25643. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25644. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25645. };
  25646. return Action;
  25647. })();
  25648. BABYLON.Action = Action;
  25649. })(BABYLON || (BABYLON = {}));
  25650. var BABYLON;
  25651. (function (BABYLON) {
  25652. /**
  25653. * ActionEvent is the event beint sent when an action is triggered.
  25654. */
  25655. var ActionEvent = (function () {
  25656. /**
  25657. * @constructor
  25658. * @param source The mesh or sprite that triggered the action.
  25659. * @param pointerX The X mouse cursor position at the time of the event
  25660. * @param pointerY The Y mouse cursor position at the time of the event
  25661. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25662. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25663. */
  25664. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25665. this.source = source;
  25666. this.pointerX = pointerX;
  25667. this.pointerY = pointerY;
  25668. this.meshUnderPointer = meshUnderPointer;
  25669. this.sourceEvent = sourceEvent;
  25670. this.additionalData = additionalData;
  25671. }
  25672. /**
  25673. * Helper function to auto-create an ActionEvent from a source mesh.
  25674. * @param source The source mesh that triggered the event
  25675. * @param evt {Event} The original (browser) event
  25676. */
  25677. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25678. var scene = source.getScene();
  25679. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25680. };
  25681. /**
  25682. * Helper function to auto-create an ActionEvent from a source mesh.
  25683. * @param source The source sprite that triggered the event
  25684. * @param scene Scene associated with the sprite
  25685. * @param evt {Event} The original (browser) event
  25686. */
  25687. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25688. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25689. };
  25690. /**
  25691. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25692. * @param scene the scene where the event occurred
  25693. * @param evt {Event} The original (browser) event
  25694. */
  25695. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25696. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25697. };
  25698. return ActionEvent;
  25699. })();
  25700. BABYLON.ActionEvent = ActionEvent;
  25701. /**
  25702. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25703. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25704. */
  25705. var ActionManager = (function () {
  25706. function ActionManager(scene) {
  25707. // Members
  25708. this.actions = new Array();
  25709. this._scene = scene;
  25710. scene._actionManagers.push(this);
  25711. }
  25712. Object.defineProperty(ActionManager, "NothingTrigger", {
  25713. get: function () {
  25714. return ActionManager._NothingTrigger;
  25715. },
  25716. enumerable: true,
  25717. configurable: true
  25718. });
  25719. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25720. get: function () {
  25721. return ActionManager._OnPickTrigger;
  25722. },
  25723. enumerable: true,
  25724. configurable: true
  25725. });
  25726. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25727. get: function () {
  25728. return ActionManager._OnLeftPickTrigger;
  25729. },
  25730. enumerable: true,
  25731. configurable: true
  25732. });
  25733. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25734. get: function () {
  25735. return ActionManager._OnRightPickTrigger;
  25736. },
  25737. enumerable: true,
  25738. configurable: true
  25739. });
  25740. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25741. get: function () {
  25742. return ActionManager._OnCenterPickTrigger;
  25743. },
  25744. enumerable: true,
  25745. configurable: true
  25746. });
  25747. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  25748. get: function () {
  25749. return ActionManager._OnPickDownTrigger;
  25750. },
  25751. enumerable: true,
  25752. configurable: true
  25753. });
  25754. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25755. get: function () {
  25756. return ActionManager._OnPickUpTrigger;
  25757. },
  25758. enumerable: true,
  25759. configurable: true
  25760. });
  25761. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  25762. get: function () {
  25763. return ActionManager._OnLongPressTrigger;
  25764. },
  25765. enumerable: true,
  25766. configurable: true
  25767. });
  25768. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25769. get: function () {
  25770. return ActionManager._OnPointerOverTrigger;
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25776. get: function () {
  25777. return ActionManager._OnPointerOutTrigger;
  25778. },
  25779. enumerable: true,
  25780. configurable: true
  25781. });
  25782. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25783. get: function () {
  25784. return ActionManager._OnEveryFrameTrigger;
  25785. },
  25786. enumerable: true,
  25787. configurable: true
  25788. });
  25789. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25790. get: function () {
  25791. return ActionManager._OnIntersectionEnterTrigger;
  25792. },
  25793. enumerable: true,
  25794. configurable: true
  25795. });
  25796. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25797. get: function () {
  25798. return ActionManager._OnIntersectionExitTrigger;
  25799. },
  25800. enumerable: true,
  25801. configurable: true
  25802. });
  25803. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25804. get: function () {
  25805. return ActionManager._OnKeyDownTrigger;
  25806. },
  25807. enumerable: true,
  25808. configurable: true
  25809. });
  25810. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25811. get: function () {
  25812. return ActionManager._OnKeyUpTrigger;
  25813. },
  25814. enumerable: true,
  25815. configurable: true
  25816. });
  25817. // Methods
  25818. ActionManager.prototype.dispose = function () {
  25819. var index = this._scene._actionManagers.indexOf(this);
  25820. if (index > -1) {
  25821. this._scene._actionManagers.splice(index, 1);
  25822. }
  25823. };
  25824. ActionManager.prototype.getScene = function () {
  25825. return this._scene;
  25826. };
  25827. /**
  25828. * Does this action manager handles actions of any of the given triggers
  25829. * @param {number[]} triggers - the triggers to be tested
  25830. * @return {boolean} whether one (or more) of the triggers is handeled
  25831. */
  25832. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25833. for (var index = 0; index < this.actions.length; index++) {
  25834. var action = this.actions[index];
  25835. if (triggers.indexOf(action.trigger) > -1) {
  25836. return true;
  25837. }
  25838. }
  25839. return false;
  25840. };
  25841. /**
  25842. * Does this action manager handles actions of a given trigger
  25843. * @param {number} trigger - the trigger to be tested
  25844. * @return {boolean} whether the trigger is handeled
  25845. */
  25846. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25847. for (var index = 0; index < this.actions.length; index++) {
  25848. var action = this.actions[index];
  25849. if (action.trigger === trigger) {
  25850. return true;
  25851. }
  25852. }
  25853. return false;
  25854. };
  25855. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25856. /**
  25857. * Does this action manager has pointer triggers
  25858. * @return {boolean} whether or not it has pointer triggers
  25859. */
  25860. get: function () {
  25861. for (var index = 0; index < this.actions.length; index++) {
  25862. var action = this.actions[index];
  25863. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25864. return true;
  25865. }
  25866. }
  25867. return false;
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25873. /**
  25874. * Does this action manager has pick triggers
  25875. * @return {boolean} whether or not it has pick triggers
  25876. */
  25877. get: function () {
  25878. for (var index = 0; index < this.actions.length; index++) {
  25879. var action = this.actions[index];
  25880. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  25881. return true;
  25882. }
  25883. }
  25884. return false;
  25885. },
  25886. enumerable: true,
  25887. configurable: true
  25888. });
  25889. /**
  25890. * Registers an action to this action manager
  25891. * @param {BABYLON.Action} action - the action to be registered
  25892. * @return {BABYLON.Action} the action amended (prepared) after registration
  25893. */
  25894. ActionManager.prototype.registerAction = function (action) {
  25895. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25896. if (this.getScene().actionManager !== this) {
  25897. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25898. return null;
  25899. }
  25900. }
  25901. this.actions.push(action);
  25902. action._actionManager = this;
  25903. action._prepare();
  25904. return action;
  25905. };
  25906. /**
  25907. * Process a specific trigger
  25908. * @param {number} trigger - the trigger to process
  25909. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25910. */
  25911. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25912. for (var index = 0; index < this.actions.length; index++) {
  25913. var action = this.actions[index];
  25914. if (action.trigger === trigger) {
  25915. if (trigger === ActionManager.OnKeyUpTrigger
  25916. || trigger === ActionManager.OnKeyDownTrigger) {
  25917. var parameter = action.getTriggerParameter();
  25918. if (parameter) {
  25919. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25920. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25921. if (actualkey !== parameter.toLowerCase()) {
  25922. continue;
  25923. }
  25924. }
  25925. }
  25926. action._executeCurrent(evt);
  25927. }
  25928. }
  25929. };
  25930. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25931. var properties = propertyPath.split(".");
  25932. for (var index = 0; index < properties.length - 1; index++) {
  25933. target = target[properties[index]];
  25934. }
  25935. return target;
  25936. };
  25937. ActionManager.prototype._getProperty = function (propertyPath) {
  25938. var properties = propertyPath.split(".");
  25939. return properties[properties.length - 1];
  25940. };
  25941. ActionManager.Parse = function (parsedActions, object, scene) {
  25942. var actionManager = new BABYLON.ActionManager(scene);
  25943. if (object === null)
  25944. scene.actionManager = actionManager;
  25945. else
  25946. object.actionManager = actionManager;
  25947. // instanciate a new object
  25948. var instanciate = function (name, params) {
  25949. var newInstance = Object.create(BABYLON[name].prototype);
  25950. newInstance.constructor.apply(newInstance, params);
  25951. return newInstance;
  25952. };
  25953. var parseParameter = function (name, value, target, propertyPath) {
  25954. if (propertyPath === null) {
  25955. // String, boolean or float
  25956. var floatValue = parseFloat(value);
  25957. if (value === "true" || value === "false")
  25958. return value === "true";
  25959. else
  25960. return isNaN(floatValue) ? value : floatValue;
  25961. }
  25962. var effectiveTarget = propertyPath.split(".");
  25963. var values = value.split(",");
  25964. // Get effective Target
  25965. for (var i = 0; i < effectiveTarget.length; i++) {
  25966. target = target[effectiveTarget[i]];
  25967. }
  25968. // Return appropriate value with its type
  25969. if (typeof (target) === "boolean")
  25970. return values[0] === "true";
  25971. if (typeof (target) === "string")
  25972. return values[0];
  25973. // Parameters with multiple values such as Vector3 etc.
  25974. var split = new Array();
  25975. for (var i = 0; i < values.length; i++)
  25976. split.push(parseFloat(values[i]));
  25977. if (target instanceof BABYLON.Vector3)
  25978. return BABYLON.Vector3.FromArray(split);
  25979. if (target instanceof BABYLON.Vector4)
  25980. return BABYLON.Vector4.FromArray(split);
  25981. if (target instanceof BABYLON.Color3)
  25982. return BABYLON.Color3.FromArray(split);
  25983. if (target instanceof BABYLON.Color4)
  25984. return BABYLON.Color4.FromArray(split);
  25985. return parseFloat(values[0]);
  25986. };
  25987. // traverse graph per trigger
  25988. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25989. if (combineArray === void 0) { combineArray = null; }
  25990. if (parsedAction.detached)
  25991. return;
  25992. var parameters = new Array();
  25993. var target = null;
  25994. var propertyPath = null;
  25995. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25996. // Parameters
  25997. if (parsedAction.type === 2)
  25998. parameters.push(actionManager);
  25999. else
  26000. parameters.push(trigger);
  26001. if (combine) {
  26002. var actions = new Array();
  26003. for (var j = 0; j < parsedAction.combine.length; j++) {
  26004. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26005. }
  26006. parameters.push(actions);
  26007. }
  26008. else {
  26009. for (var i = 0; i < parsedAction.properties.length; i++) {
  26010. var value = parsedAction.properties[i].value;
  26011. var name = parsedAction.properties[i].name;
  26012. var targetType = parsedAction.properties[i].targetType;
  26013. if (name === "target")
  26014. if (targetType !== null && targetType === "SceneProperties")
  26015. value = target = scene;
  26016. else
  26017. value = target = scene.getNodeByName(value);
  26018. else if (name === "parent")
  26019. value = scene.getNodeByName(value);
  26020. else if (name === "sound")
  26021. value = scene.getSoundByName(value);
  26022. else if (name !== "propertyPath") {
  26023. if (parsedAction.type === 2 && name === "operator")
  26024. value = BABYLON.ValueCondition[value];
  26025. else
  26026. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26027. }
  26028. else {
  26029. propertyPath = value;
  26030. }
  26031. parameters.push(value);
  26032. }
  26033. }
  26034. if (combineArray === null) {
  26035. parameters.push(condition);
  26036. }
  26037. else {
  26038. parameters.push(null);
  26039. }
  26040. // If interpolate value action
  26041. if (parsedAction.name === "InterpolateValueAction") {
  26042. var param = parameters[parameters.length - 2];
  26043. parameters[parameters.length - 1] = param;
  26044. parameters[parameters.length - 2] = condition;
  26045. }
  26046. // Action or condition(s) and not CombineAction
  26047. var newAction = instanciate(parsedAction.name, parameters);
  26048. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26049. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26050. if (action)
  26051. action.then(nothing);
  26052. else
  26053. actionManager.registerAction(nothing);
  26054. action = nothing;
  26055. }
  26056. if (combineArray === null) {
  26057. if (newAction instanceof BABYLON.Condition) {
  26058. condition = newAction;
  26059. newAction = action;
  26060. }
  26061. else {
  26062. condition = null;
  26063. if (action)
  26064. action.then(newAction);
  26065. else
  26066. actionManager.registerAction(newAction);
  26067. }
  26068. }
  26069. else {
  26070. combineArray.push(newAction);
  26071. }
  26072. for (var i = 0; i < parsedAction.children.length; i++)
  26073. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26074. };
  26075. // triggers
  26076. for (var i = 0; i < parsedActions.children.length; i++) {
  26077. var triggerParams;
  26078. var trigger = parsedActions.children[i];
  26079. if (trigger.properties.length > 0) {
  26080. var param = trigger.properties[0].value;
  26081. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26082. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26083. }
  26084. else
  26085. triggerParams = BABYLON.ActionManager[trigger.name];
  26086. for (var j = 0; j < trigger.children.length; j++) {
  26087. if (!trigger.detached)
  26088. traverse(trigger.children[j], triggerParams, null, null);
  26089. }
  26090. }
  26091. };
  26092. // Statics
  26093. ActionManager._NothingTrigger = 0;
  26094. ActionManager._OnPickTrigger = 1;
  26095. ActionManager._OnLeftPickTrigger = 2;
  26096. ActionManager._OnRightPickTrigger = 3;
  26097. ActionManager._OnCenterPickTrigger = 4;
  26098. ActionManager._OnPickDownTrigger = 5;
  26099. ActionManager._OnPickUpTrigger = 6;
  26100. ActionManager._OnLongPressTrigger = 7;
  26101. ActionManager._OnPointerOverTrigger = 8;
  26102. ActionManager._OnPointerOutTrigger = 9;
  26103. ActionManager._OnEveryFrameTrigger = 10;
  26104. ActionManager._OnIntersectionEnterTrigger = 11;
  26105. ActionManager._OnIntersectionExitTrigger = 12;
  26106. ActionManager._OnKeyDownTrigger = 13;
  26107. ActionManager._OnKeyUpTrigger = 14;
  26108. ActionManager.DragMovementThreshold = 10; // in pixels
  26109. ActionManager.LongPressDelay = 500; // in milliseconds
  26110. return ActionManager;
  26111. })();
  26112. BABYLON.ActionManager = ActionManager;
  26113. })(BABYLON || (BABYLON = {}));
  26114. var BABYLON;
  26115. (function (BABYLON) {
  26116. var InterpolateValueAction = (function (_super) {
  26117. __extends(InterpolateValueAction, _super);
  26118. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26119. if (duration === void 0) { duration = 1000; }
  26120. _super.call(this, triggerOptions, condition);
  26121. this.propertyPath = propertyPath;
  26122. this.value = value;
  26123. this.duration = duration;
  26124. this.stopOtherAnimations = stopOtherAnimations;
  26125. this.onInterpolationDone = onInterpolationDone;
  26126. this._target = target;
  26127. }
  26128. InterpolateValueAction.prototype._prepare = function () {
  26129. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26130. this._property = this._getProperty(this.propertyPath);
  26131. };
  26132. InterpolateValueAction.prototype.execute = function () {
  26133. var scene = this._actionManager.getScene();
  26134. var keys = [
  26135. {
  26136. frame: 0,
  26137. value: this._target[this._property]
  26138. }, {
  26139. frame: 100,
  26140. value: this.value
  26141. }
  26142. ];
  26143. var dataType;
  26144. if (typeof this.value === "number") {
  26145. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26146. }
  26147. else if (this.value instanceof BABYLON.Color3) {
  26148. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26149. }
  26150. else if (this.value instanceof BABYLON.Vector3) {
  26151. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26152. }
  26153. else if (this.value instanceof BABYLON.Matrix) {
  26154. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26155. }
  26156. else if (this.value instanceof BABYLON.Quaternion) {
  26157. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26158. }
  26159. else {
  26160. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26161. return;
  26162. }
  26163. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26164. animation.setKeys(keys);
  26165. if (this.stopOtherAnimations) {
  26166. scene.stopAnimation(this._target);
  26167. }
  26168. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26169. };
  26170. return InterpolateValueAction;
  26171. })(BABYLON.Action);
  26172. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26173. })(BABYLON || (BABYLON = {}));
  26174. var BABYLON;
  26175. (function (BABYLON) {
  26176. var SwitchBooleanAction = (function (_super) {
  26177. __extends(SwitchBooleanAction, _super);
  26178. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26179. _super.call(this, triggerOptions, condition);
  26180. this.propertyPath = propertyPath;
  26181. this._target = target;
  26182. }
  26183. SwitchBooleanAction.prototype._prepare = function () {
  26184. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26185. this._property = this._getProperty(this.propertyPath);
  26186. };
  26187. SwitchBooleanAction.prototype.execute = function () {
  26188. this._target[this._property] = !this._target[this._property];
  26189. };
  26190. return SwitchBooleanAction;
  26191. })(BABYLON.Action);
  26192. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26193. var SetStateAction = (function (_super) {
  26194. __extends(SetStateAction, _super);
  26195. function SetStateAction(triggerOptions, target, value, condition) {
  26196. _super.call(this, triggerOptions, condition);
  26197. this.value = value;
  26198. this._target = target;
  26199. }
  26200. SetStateAction.prototype.execute = function () {
  26201. this._target.state = this.value;
  26202. };
  26203. return SetStateAction;
  26204. })(BABYLON.Action);
  26205. BABYLON.SetStateAction = SetStateAction;
  26206. var SetValueAction = (function (_super) {
  26207. __extends(SetValueAction, _super);
  26208. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26209. _super.call(this, triggerOptions, condition);
  26210. this.propertyPath = propertyPath;
  26211. this.value = value;
  26212. this._target = target;
  26213. }
  26214. SetValueAction.prototype._prepare = function () {
  26215. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26216. this._property = this._getProperty(this.propertyPath);
  26217. };
  26218. SetValueAction.prototype.execute = function () {
  26219. this._target[this._property] = this.value;
  26220. };
  26221. return SetValueAction;
  26222. })(BABYLON.Action);
  26223. BABYLON.SetValueAction = SetValueAction;
  26224. var IncrementValueAction = (function (_super) {
  26225. __extends(IncrementValueAction, _super);
  26226. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26227. _super.call(this, triggerOptions, condition);
  26228. this.propertyPath = propertyPath;
  26229. this.value = value;
  26230. this._target = target;
  26231. }
  26232. IncrementValueAction.prototype._prepare = function () {
  26233. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26234. this._property = this._getProperty(this.propertyPath);
  26235. if (typeof this._target[this._property] !== "number") {
  26236. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26237. }
  26238. };
  26239. IncrementValueAction.prototype.execute = function () {
  26240. this._target[this._property] += this.value;
  26241. };
  26242. return IncrementValueAction;
  26243. })(BABYLON.Action);
  26244. BABYLON.IncrementValueAction = IncrementValueAction;
  26245. var PlayAnimationAction = (function (_super) {
  26246. __extends(PlayAnimationAction, _super);
  26247. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26248. _super.call(this, triggerOptions, condition);
  26249. this.from = from;
  26250. this.to = to;
  26251. this.loop = loop;
  26252. this._target = target;
  26253. }
  26254. PlayAnimationAction.prototype._prepare = function () {
  26255. };
  26256. PlayAnimationAction.prototype.execute = function () {
  26257. var scene = this._actionManager.getScene();
  26258. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26259. };
  26260. return PlayAnimationAction;
  26261. })(BABYLON.Action);
  26262. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26263. var StopAnimationAction = (function (_super) {
  26264. __extends(StopAnimationAction, _super);
  26265. function StopAnimationAction(triggerOptions, target, condition) {
  26266. _super.call(this, triggerOptions, condition);
  26267. this._target = target;
  26268. }
  26269. StopAnimationAction.prototype._prepare = function () {
  26270. };
  26271. StopAnimationAction.prototype.execute = function () {
  26272. var scene = this._actionManager.getScene();
  26273. scene.stopAnimation(this._target);
  26274. };
  26275. return StopAnimationAction;
  26276. })(BABYLON.Action);
  26277. BABYLON.StopAnimationAction = StopAnimationAction;
  26278. var DoNothingAction = (function (_super) {
  26279. __extends(DoNothingAction, _super);
  26280. function DoNothingAction(triggerOptions, condition) {
  26281. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26282. _super.call(this, triggerOptions, condition);
  26283. }
  26284. DoNothingAction.prototype.execute = function () {
  26285. };
  26286. return DoNothingAction;
  26287. })(BABYLON.Action);
  26288. BABYLON.DoNothingAction = DoNothingAction;
  26289. var CombineAction = (function (_super) {
  26290. __extends(CombineAction, _super);
  26291. function CombineAction(triggerOptions, children, condition) {
  26292. _super.call(this, triggerOptions, condition);
  26293. this.children = children;
  26294. }
  26295. CombineAction.prototype._prepare = function () {
  26296. for (var index = 0; index < this.children.length; index++) {
  26297. this.children[index]._actionManager = this._actionManager;
  26298. this.children[index]._prepare();
  26299. }
  26300. };
  26301. CombineAction.prototype.execute = function (evt) {
  26302. for (var index = 0; index < this.children.length; index++) {
  26303. this.children[index].execute(evt);
  26304. }
  26305. };
  26306. return CombineAction;
  26307. })(BABYLON.Action);
  26308. BABYLON.CombineAction = CombineAction;
  26309. var ExecuteCodeAction = (function (_super) {
  26310. __extends(ExecuteCodeAction, _super);
  26311. function ExecuteCodeAction(triggerOptions, func, condition) {
  26312. _super.call(this, triggerOptions, condition);
  26313. this.func = func;
  26314. }
  26315. ExecuteCodeAction.prototype.execute = function (evt) {
  26316. this.func(evt);
  26317. };
  26318. return ExecuteCodeAction;
  26319. })(BABYLON.Action);
  26320. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26321. var SetParentAction = (function (_super) {
  26322. __extends(SetParentAction, _super);
  26323. function SetParentAction(triggerOptions, target, parent, condition) {
  26324. _super.call(this, triggerOptions, condition);
  26325. this._target = target;
  26326. this._parent = parent;
  26327. }
  26328. SetParentAction.prototype._prepare = function () {
  26329. };
  26330. SetParentAction.prototype.execute = function () {
  26331. if (this._target.parent === this._parent) {
  26332. return;
  26333. }
  26334. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26335. invertParentWorldMatrix.invert();
  26336. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26337. this._target.parent = this._parent;
  26338. };
  26339. return SetParentAction;
  26340. })(BABYLON.Action);
  26341. BABYLON.SetParentAction = SetParentAction;
  26342. var PlaySoundAction = (function (_super) {
  26343. __extends(PlaySoundAction, _super);
  26344. function PlaySoundAction(triggerOptions, sound, condition) {
  26345. _super.call(this, triggerOptions, condition);
  26346. this._sound = sound;
  26347. }
  26348. PlaySoundAction.prototype._prepare = function () {
  26349. };
  26350. PlaySoundAction.prototype.execute = function () {
  26351. if (this._sound !== undefined)
  26352. this._sound.play();
  26353. };
  26354. return PlaySoundAction;
  26355. })(BABYLON.Action);
  26356. BABYLON.PlaySoundAction = PlaySoundAction;
  26357. var StopSoundAction = (function (_super) {
  26358. __extends(StopSoundAction, _super);
  26359. function StopSoundAction(triggerOptions, sound, condition) {
  26360. _super.call(this, triggerOptions, condition);
  26361. this._sound = sound;
  26362. }
  26363. StopSoundAction.prototype._prepare = function () {
  26364. };
  26365. StopSoundAction.prototype.execute = function () {
  26366. if (this._sound !== undefined)
  26367. this._sound.stop();
  26368. };
  26369. return StopSoundAction;
  26370. })(BABYLON.Action);
  26371. BABYLON.StopSoundAction = StopSoundAction;
  26372. })(BABYLON || (BABYLON = {}));
  26373. var BABYLON;
  26374. (function (BABYLON) {
  26375. var Geometry = (function () {
  26376. function Geometry(id, scene, vertexData, updatable, mesh) {
  26377. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26378. this._totalVertices = 0;
  26379. this._isDisposed = false;
  26380. this.id = id;
  26381. this._engine = scene.getEngine();
  26382. this._meshes = [];
  26383. this._scene = scene;
  26384. //Init vertex buffer cache
  26385. this._vertexBuffers = {};
  26386. this._indices = [];
  26387. // vertexData
  26388. if (vertexData) {
  26389. this.setAllVerticesData(vertexData, updatable);
  26390. }
  26391. else {
  26392. this._totalVertices = 0;
  26393. this._indices = [];
  26394. }
  26395. // applyToMesh
  26396. if (mesh) {
  26397. this.applyToMesh(mesh);
  26398. mesh.computeWorldMatrix(true);
  26399. }
  26400. }
  26401. Object.defineProperty(Geometry.prototype, "extend", {
  26402. get: function () {
  26403. return this._extend;
  26404. },
  26405. enumerable: true,
  26406. configurable: true
  26407. });
  26408. Geometry.prototype.getScene = function () {
  26409. return this._scene;
  26410. };
  26411. Geometry.prototype.getEngine = function () {
  26412. return this._engine;
  26413. };
  26414. Geometry.prototype.isReady = function () {
  26415. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26416. };
  26417. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26418. vertexData.applyToGeometry(this, updatable);
  26419. this.notifyUpdate();
  26420. };
  26421. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26422. if (this._vertexBuffers[kind]) {
  26423. this._vertexBuffers[kind].dispose();
  26424. }
  26425. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26426. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26427. stride = this._vertexBuffers[kind].getStrideSize();
  26428. this._totalVertices = data.length / stride;
  26429. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26430. var meshes = this._meshes;
  26431. var numOfMeshes = meshes.length;
  26432. for (var index = 0; index < numOfMeshes; index++) {
  26433. var mesh = meshes[index];
  26434. mesh._resetPointsArrayCache();
  26435. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26436. mesh._createGlobalSubMesh();
  26437. mesh.computeWorldMatrix(true);
  26438. }
  26439. }
  26440. this.notifyUpdate(kind);
  26441. };
  26442. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26443. var vertexBuffer = this.getVertexBuffer(kind);
  26444. if (!vertexBuffer) {
  26445. return;
  26446. }
  26447. vertexBuffer.updateDirectly(data, offset);
  26448. this.notifyUpdate(kind);
  26449. };
  26450. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26451. var vertexBuffer = this.getVertexBuffer(kind);
  26452. if (!vertexBuffer) {
  26453. return;
  26454. }
  26455. vertexBuffer.update(data);
  26456. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26457. var stride = vertexBuffer.getStrideSize();
  26458. this._totalVertices = data.length / stride;
  26459. if (updateExtends) {
  26460. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26461. }
  26462. var meshes = this._meshes;
  26463. var numOfMeshes = meshes.length;
  26464. for (var index = 0; index < numOfMeshes; index++) {
  26465. var mesh = meshes[index];
  26466. mesh._resetPointsArrayCache();
  26467. if (updateExtends) {
  26468. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26469. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26470. var subMesh = mesh.subMeshes[subIndex];
  26471. subMesh.refreshBoundingInfo();
  26472. }
  26473. }
  26474. }
  26475. }
  26476. this.notifyUpdate(kind);
  26477. };
  26478. Geometry.prototype.getTotalVertices = function () {
  26479. if (!this.isReady()) {
  26480. return 0;
  26481. }
  26482. return this._totalVertices;
  26483. };
  26484. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26485. var vertexBuffer = this.getVertexBuffer(kind);
  26486. if (!vertexBuffer) {
  26487. return null;
  26488. }
  26489. var orig = vertexBuffer.getData();
  26490. if (!copyWhenShared || this._meshes.length === 1) {
  26491. return orig;
  26492. }
  26493. else {
  26494. var len = orig.length;
  26495. var copy = [];
  26496. for (var i = 0; i < len; i++) {
  26497. copy.push(orig[i]);
  26498. }
  26499. return copy;
  26500. }
  26501. };
  26502. Geometry.prototype.getVertexBuffer = function (kind) {
  26503. if (!this.isReady()) {
  26504. return null;
  26505. }
  26506. return this._vertexBuffers[kind];
  26507. };
  26508. Geometry.prototype.getVertexBuffers = function () {
  26509. if (!this.isReady()) {
  26510. return null;
  26511. }
  26512. return this._vertexBuffers;
  26513. };
  26514. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26515. if (!this._vertexBuffers) {
  26516. if (this._delayInfo) {
  26517. return this._delayInfo.indexOf(kind) !== -1;
  26518. }
  26519. return false;
  26520. }
  26521. return this._vertexBuffers[kind] !== undefined;
  26522. };
  26523. Geometry.prototype.getVerticesDataKinds = function () {
  26524. var result = [];
  26525. var kind;
  26526. if (!this._vertexBuffers && this._delayInfo) {
  26527. for (kind in this._delayInfo) {
  26528. result.push(kind);
  26529. }
  26530. }
  26531. else {
  26532. for (kind in this._vertexBuffers) {
  26533. result.push(kind);
  26534. }
  26535. }
  26536. return result;
  26537. };
  26538. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26539. if (this._indexBuffer) {
  26540. this._engine._releaseBuffer(this._indexBuffer);
  26541. }
  26542. this._indices = indices;
  26543. if (this._meshes.length !== 0 && this._indices) {
  26544. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26545. }
  26546. if (totalVertices !== undefined) {
  26547. this._totalVertices = totalVertices;
  26548. }
  26549. var meshes = this._meshes;
  26550. var numOfMeshes = meshes.length;
  26551. for (var index = 0; index < numOfMeshes; index++) {
  26552. meshes[index]._createGlobalSubMesh();
  26553. }
  26554. this.notifyUpdate();
  26555. };
  26556. Geometry.prototype.getTotalIndices = function () {
  26557. if (!this.isReady()) {
  26558. return 0;
  26559. }
  26560. return this._indices.length;
  26561. };
  26562. Geometry.prototype.getIndices = function (copyWhenShared) {
  26563. if (!this.isReady()) {
  26564. return null;
  26565. }
  26566. var orig = this._indices;
  26567. if (!copyWhenShared || this._meshes.length === 1) {
  26568. return orig;
  26569. }
  26570. else {
  26571. var len = orig.length;
  26572. var copy = [];
  26573. for (var i = 0; i < len; i++) {
  26574. copy.push(orig[i]);
  26575. }
  26576. return copy;
  26577. }
  26578. };
  26579. Geometry.prototype.getIndexBuffer = function () {
  26580. if (!this.isReady()) {
  26581. return null;
  26582. }
  26583. return this._indexBuffer;
  26584. };
  26585. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26586. var meshes = this._meshes;
  26587. var index = meshes.indexOf(mesh);
  26588. if (index === -1) {
  26589. return;
  26590. }
  26591. for (var kind in this._vertexBuffers) {
  26592. this._vertexBuffers[kind].dispose();
  26593. }
  26594. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26595. this._indexBuffer = null;
  26596. }
  26597. meshes.splice(index, 1);
  26598. mesh._geometry = null;
  26599. if (meshes.length === 0 && shouldDispose) {
  26600. this.dispose();
  26601. }
  26602. };
  26603. Geometry.prototype.applyToMesh = function (mesh) {
  26604. if (mesh._geometry === this) {
  26605. return;
  26606. }
  26607. var previousGeometry = mesh._geometry;
  26608. if (previousGeometry) {
  26609. previousGeometry.releaseForMesh(mesh);
  26610. }
  26611. var meshes = this._meshes;
  26612. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26613. mesh._geometry = this;
  26614. this._scene.pushGeometry(this);
  26615. meshes.push(mesh);
  26616. if (this.isReady()) {
  26617. this._applyToMesh(mesh);
  26618. }
  26619. else {
  26620. mesh._boundingInfo = this._boundingInfo;
  26621. }
  26622. };
  26623. Geometry.prototype._applyToMesh = function (mesh) {
  26624. var numOfMeshes = this._meshes.length;
  26625. // vertexBuffers
  26626. for (var kind in this._vertexBuffers) {
  26627. if (numOfMeshes === 1) {
  26628. this._vertexBuffers[kind].create();
  26629. }
  26630. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26631. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26632. mesh._resetPointsArrayCache();
  26633. if (!this._extend) {
  26634. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26635. }
  26636. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26637. mesh._createGlobalSubMesh();
  26638. //bounding info was just created again, world matrix should be applied again.
  26639. mesh._updateBoundingInfo();
  26640. }
  26641. }
  26642. // indexBuffer
  26643. if (numOfMeshes === 1 && this._indices) {
  26644. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26645. }
  26646. if (this._indexBuffer) {
  26647. this._indexBuffer.references = numOfMeshes;
  26648. }
  26649. };
  26650. Geometry.prototype.notifyUpdate = function (kind) {
  26651. if (this.onGeometryUpdated) {
  26652. this.onGeometryUpdated(this, kind);
  26653. }
  26654. };
  26655. Geometry.prototype.load = function (scene, onLoaded) {
  26656. var _this = this;
  26657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26658. return;
  26659. }
  26660. if (this.isReady()) {
  26661. if (onLoaded) {
  26662. onLoaded();
  26663. }
  26664. return;
  26665. }
  26666. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26667. scene._addPendingData(this);
  26668. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26669. _this._delayLoadingFunction(JSON.parse(data), _this);
  26670. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26671. _this._delayInfo = [];
  26672. scene._removePendingData(_this);
  26673. var meshes = _this._meshes;
  26674. var numOfMeshes = meshes.length;
  26675. for (var index = 0; index < numOfMeshes; index++) {
  26676. _this._applyToMesh(meshes[index]);
  26677. }
  26678. if (onLoaded) {
  26679. onLoaded();
  26680. }
  26681. }, function () { }, scene.database);
  26682. };
  26683. Geometry.prototype.isDisposed = function () {
  26684. return this._isDisposed;
  26685. };
  26686. Geometry.prototype.dispose = function () {
  26687. var meshes = this._meshes;
  26688. var numOfMeshes = meshes.length;
  26689. var index;
  26690. for (index = 0; index < numOfMeshes; index++) {
  26691. this.releaseForMesh(meshes[index]);
  26692. }
  26693. this._meshes = [];
  26694. for (var kind in this._vertexBuffers) {
  26695. this._vertexBuffers[kind].dispose();
  26696. }
  26697. this._vertexBuffers = [];
  26698. this._totalVertices = 0;
  26699. if (this._indexBuffer) {
  26700. this._engine._releaseBuffer(this._indexBuffer);
  26701. }
  26702. this._indexBuffer = null;
  26703. this._indices = [];
  26704. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26705. this.delayLoadingFile = null;
  26706. this._delayLoadingFunction = null;
  26707. this._delayInfo = [];
  26708. this._boundingInfo = null;
  26709. this._scene.removeGeometry(this);
  26710. this._isDisposed = true;
  26711. };
  26712. Geometry.prototype.copy = function (id) {
  26713. var vertexData = new BABYLON.VertexData();
  26714. vertexData.indices = [];
  26715. var indices = this.getIndices();
  26716. for (var index = 0; index < indices.length; index++) {
  26717. vertexData.indices.push(indices[index]);
  26718. }
  26719. var updatable = false;
  26720. var stopChecking = false;
  26721. var kind;
  26722. for (kind in this._vertexBuffers) {
  26723. // using slice() to make a copy of the array and not just reference it
  26724. var data = this.getVerticesData(kind);
  26725. if (data instanceof Float32Array) {
  26726. vertexData.set(new Float32Array(data), kind);
  26727. }
  26728. else {
  26729. vertexData.set(data.slice(0), kind);
  26730. }
  26731. if (!stopChecking) {
  26732. updatable = this.getVertexBuffer(kind).isUpdatable();
  26733. stopChecking = !updatable;
  26734. }
  26735. }
  26736. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26737. geometry.delayLoadState = this.delayLoadState;
  26738. geometry.delayLoadingFile = this.delayLoadingFile;
  26739. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26740. for (kind in this._delayInfo) {
  26741. geometry._delayInfo = geometry._delayInfo || [];
  26742. geometry._delayInfo.push(kind);
  26743. }
  26744. // Bounding info
  26745. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26746. return geometry;
  26747. };
  26748. Geometry.prototype.serialize = function () {
  26749. var serializationObject = {};
  26750. serializationObject.id = this.id;
  26751. if (BABYLON.Tags.HasTags(this)) {
  26752. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26753. }
  26754. return serializationObject;
  26755. };
  26756. Geometry.prototype.serializeVerticeData = function () {
  26757. var serializationObject = this.serialize();
  26758. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26759. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26760. }
  26761. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26762. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26763. }
  26764. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26765. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26766. }
  26767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26768. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26769. }
  26770. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26771. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26772. }
  26773. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26774. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26775. }
  26776. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26777. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26778. }
  26779. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26780. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26781. }
  26782. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26783. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26784. }
  26785. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26786. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26787. serializationObject.matricesIndices._isExpanded = true;
  26788. }
  26789. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26790. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26791. }
  26792. serializationObject.indices = this.getIndices();
  26793. return serializationObject;
  26794. };
  26795. // Statics
  26796. Geometry.ExtractFromMesh = function (mesh, id) {
  26797. var geometry = mesh._geometry;
  26798. if (!geometry) {
  26799. return null;
  26800. }
  26801. return geometry.copy(id);
  26802. };
  26803. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26804. // be aware Math.random() could cause collisions
  26805. Geometry.RandomId = function () {
  26806. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26807. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26808. return v.toString(16);
  26809. });
  26810. };
  26811. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26812. var scene = mesh.getScene();
  26813. // Geometry
  26814. var geometryId = parsedGeometry.geometryId;
  26815. if (geometryId) {
  26816. var geometry = scene.getGeometryByID(geometryId);
  26817. if (geometry) {
  26818. geometry.applyToMesh(mesh);
  26819. }
  26820. }
  26821. else if (parsedGeometry instanceof ArrayBuffer) {
  26822. var binaryInfo = mesh._binaryInfo;
  26823. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26824. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26825. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26826. }
  26827. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26828. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26829. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26830. }
  26831. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26832. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26833. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26834. }
  26835. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26836. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26837. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26838. }
  26839. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26840. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26841. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26842. }
  26843. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26844. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26845. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26846. }
  26847. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26848. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26849. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26850. }
  26851. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26852. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26853. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26854. }
  26855. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26856. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26857. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26858. }
  26859. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26860. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26861. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26862. }
  26863. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26864. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26865. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26866. }
  26867. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26868. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26869. mesh.setIndices(indicesData);
  26870. }
  26871. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26872. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26873. mesh.subMeshes = [];
  26874. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26875. var materialIndex = subMeshesData[(i * 5) + 0];
  26876. var verticesStart = subMeshesData[(i * 5) + 1];
  26877. var verticesCount = subMeshesData[(i * 5) + 2];
  26878. var indexStart = subMeshesData[(i * 5) + 3];
  26879. var indexCount = subMeshesData[(i * 5) + 4];
  26880. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26881. }
  26882. }
  26883. }
  26884. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26885. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26886. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26887. if (parsedGeometry.uvs) {
  26888. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26889. }
  26890. if (parsedGeometry.uvs2) {
  26891. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26892. }
  26893. if (parsedGeometry.uvs3) {
  26894. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26895. }
  26896. if (parsedGeometry.uvs4) {
  26897. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26898. }
  26899. if (parsedGeometry.uvs5) {
  26900. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26901. }
  26902. if (parsedGeometry.uvs6) {
  26903. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26904. }
  26905. if (parsedGeometry.colors) {
  26906. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26907. }
  26908. if (parsedGeometry.matricesIndices) {
  26909. if (!parsedGeometry.matricesIndices._isExpanded) {
  26910. var floatIndices = [];
  26911. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26912. var matricesIndex = parsedGeometry.matricesIndices[i];
  26913. floatIndices.push(matricesIndex & 0x000000FF);
  26914. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26915. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26916. floatIndices.push(matricesIndex >> 24);
  26917. }
  26918. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26919. }
  26920. else {
  26921. delete parsedGeometry.matricesIndices._isExpanded;
  26922. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26923. }
  26924. }
  26925. if (parsedGeometry.matricesIndicesExtra) {
  26926. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26927. var floatIndices = [];
  26928. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26929. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26930. floatIndices.push(matricesIndex & 0x000000FF);
  26931. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26932. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26933. floatIndices.push(matricesIndex >> 24);
  26934. }
  26935. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26936. }
  26937. else {
  26938. delete parsedGeometry.matricesIndices._isExpanded;
  26939. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26940. }
  26941. }
  26942. if (parsedGeometry.matricesWeights) {
  26943. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26944. }
  26945. if (parsedGeometry.matricesWeightsExtra) {
  26946. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26947. }
  26948. mesh.setIndices(parsedGeometry.indices);
  26949. }
  26950. // SubMeshes
  26951. if (parsedGeometry.subMeshes) {
  26952. mesh.subMeshes = [];
  26953. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26954. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26955. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26956. }
  26957. }
  26958. // Flat shading
  26959. if (mesh._shouldGenerateFlatShading) {
  26960. mesh.convertToFlatShadedMesh();
  26961. delete mesh._shouldGenerateFlatShading;
  26962. }
  26963. // Update
  26964. mesh.computeWorldMatrix(true);
  26965. // Octree
  26966. if (scene['_selectionOctree']) {
  26967. scene['_selectionOctree'].addMesh(mesh);
  26968. }
  26969. };
  26970. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26971. if (scene.getGeometryByID(parsedVertexData.id)) {
  26972. return null; // null since geometry could be something else than a box...
  26973. }
  26974. var geometry = new Geometry(parsedVertexData.id, scene);
  26975. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26976. if (parsedVertexData.delayLoadingFile) {
  26977. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26978. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26979. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26980. geometry._delayInfo = [];
  26981. if (parsedVertexData.hasUVs) {
  26982. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26983. }
  26984. if (parsedVertexData.hasUVs2) {
  26985. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26986. }
  26987. if (parsedVertexData.hasUVs3) {
  26988. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26989. }
  26990. if (parsedVertexData.hasUVs4) {
  26991. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26992. }
  26993. if (parsedVertexData.hasUVs5) {
  26994. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26995. }
  26996. if (parsedVertexData.hasUVs6) {
  26997. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26998. }
  26999. if (parsedVertexData.hasColors) {
  27000. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27001. }
  27002. if (parsedVertexData.hasMatricesIndices) {
  27003. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27004. }
  27005. if (parsedVertexData.hasMatricesWeights) {
  27006. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27007. }
  27008. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27009. }
  27010. else {
  27011. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27012. }
  27013. scene.pushGeometry(geometry, true);
  27014. return geometry;
  27015. };
  27016. return Geometry;
  27017. })();
  27018. BABYLON.Geometry = Geometry;
  27019. /////// Primitives //////////////////////////////////////////////
  27020. var Geometry;
  27021. (function (Geometry) {
  27022. var Primitives;
  27023. (function (Primitives) {
  27024. /// Abstract class
  27025. var _Primitive = (function (_super) {
  27026. __extends(_Primitive, _super);
  27027. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27028. this._beingRegenerated = true;
  27029. this._canBeRegenerated = canBeRegenerated;
  27030. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27031. this._beingRegenerated = false;
  27032. }
  27033. _Primitive.prototype.canBeRegenerated = function () {
  27034. return this._canBeRegenerated;
  27035. };
  27036. _Primitive.prototype.regenerate = function () {
  27037. if (!this._canBeRegenerated) {
  27038. return;
  27039. }
  27040. this._beingRegenerated = true;
  27041. this.setAllVerticesData(this._regenerateVertexData(), false);
  27042. this._beingRegenerated = false;
  27043. };
  27044. _Primitive.prototype.asNewGeometry = function (id) {
  27045. return _super.prototype.copy.call(this, id);
  27046. };
  27047. // overrides
  27048. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27049. if (!this._beingRegenerated) {
  27050. return;
  27051. }
  27052. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27053. };
  27054. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27055. if (!this._beingRegenerated) {
  27056. return;
  27057. }
  27058. _super.prototype.setVerticesData.call(this, kind, data, false);
  27059. };
  27060. // to override
  27061. // protected
  27062. _Primitive.prototype._regenerateVertexData = function () {
  27063. throw new Error("Abstract method");
  27064. };
  27065. _Primitive.prototype.copy = function (id) {
  27066. throw new Error("Must be overriden in sub-classes.");
  27067. };
  27068. _Primitive.prototype.serialize = function () {
  27069. var serializationObject = _super.prototype.serialize.call(this);
  27070. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27071. return serializationObject;
  27072. };
  27073. return _Primitive;
  27074. })(Geometry);
  27075. Primitives._Primitive = _Primitive;
  27076. var Ribbon = (function (_super) {
  27077. __extends(Ribbon, _super);
  27078. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27079. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27080. this.pathArray = pathArray;
  27081. this.closeArray = closeArray;
  27082. this.closePath = closePath;
  27083. this.offset = offset;
  27084. this.side = side;
  27085. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27086. }
  27087. Ribbon.prototype._regenerateVertexData = function () {
  27088. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27089. };
  27090. Ribbon.prototype.copy = function (id) {
  27091. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27092. };
  27093. return Ribbon;
  27094. })(_Primitive);
  27095. Primitives.Ribbon = Ribbon;
  27096. var Box = (function (_super) {
  27097. __extends(Box, _super);
  27098. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27099. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27100. this.size = size;
  27101. this.side = side;
  27102. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27103. }
  27104. Box.prototype._regenerateVertexData = function () {
  27105. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27106. };
  27107. Box.prototype.copy = function (id) {
  27108. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27109. };
  27110. Box.prototype.serialize = function () {
  27111. var serializationObject = _super.prototype.serialize.call(this);
  27112. serializationObject.size = this.size;
  27113. return serializationObject;
  27114. };
  27115. Box.Parse = function (parsedBox, scene) {
  27116. if (scene.getGeometryByID(parsedBox.id)) {
  27117. return null; // null since geometry could be something else than a box...
  27118. }
  27119. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27120. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27121. scene.pushGeometry(box, true);
  27122. return box;
  27123. };
  27124. return Box;
  27125. })(_Primitive);
  27126. Primitives.Box = Box;
  27127. var Sphere = (function (_super) {
  27128. __extends(Sphere, _super);
  27129. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27130. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27131. this.segments = segments;
  27132. this.diameter = diameter;
  27133. this.side = side;
  27134. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27135. }
  27136. Sphere.prototype._regenerateVertexData = function () {
  27137. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27138. };
  27139. Sphere.prototype.copy = function (id) {
  27140. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27141. };
  27142. Sphere.prototype.serialize = function () {
  27143. var serializationObject = _super.prototype.serialize.call(this);
  27144. serializationObject.segments = this.segments;
  27145. serializationObject.diameter = this.diameter;
  27146. return serializationObject;
  27147. };
  27148. Sphere.Parse = function (parsedSphere, scene) {
  27149. if (scene.getGeometryByID(parsedSphere.id)) {
  27150. return null; // null since geometry could be something else than a sphere...
  27151. }
  27152. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27153. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27154. scene.pushGeometry(sphere, true);
  27155. return sphere;
  27156. };
  27157. return Sphere;
  27158. })(_Primitive);
  27159. Primitives.Sphere = Sphere;
  27160. var Disc = (function (_super) {
  27161. __extends(Disc, _super);
  27162. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27163. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27164. this.radius = radius;
  27165. this.tessellation = tessellation;
  27166. this.side = side;
  27167. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27168. }
  27169. Disc.prototype._regenerateVertexData = function () {
  27170. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27171. };
  27172. Disc.prototype.copy = function (id) {
  27173. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27174. };
  27175. return Disc;
  27176. })(_Primitive);
  27177. Primitives.Disc = Disc;
  27178. var Cylinder = (function (_super) {
  27179. __extends(Cylinder, _super);
  27180. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27181. if (subdivisions === void 0) { subdivisions = 1; }
  27182. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27183. this.height = height;
  27184. this.diameterTop = diameterTop;
  27185. this.diameterBottom = diameterBottom;
  27186. this.tessellation = tessellation;
  27187. this.subdivisions = subdivisions;
  27188. this.side = side;
  27189. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27190. }
  27191. Cylinder.prototype._regenerateVertexData = function () {
  27192. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27193. };
  27194. Cylinder.prototype.copy = function (id) {
  27195. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27196. };
  27197. Cylinder.prototype.serialize = function () {
  27198. var serializationObject = _super.prototype.serialize.call(this);
  27199. serializationObject.height = this.height;
  27200. serializationObject.diameterTop = this.diameterTop;
  27201. serializationObject.diameterBottom = this.diameterBottom;
  27202. serializationObject.tessellation = this.tessellation;
  27203. return serializationObject;
  27204. };
  27205. Cylinder.Parse = function (parsedCylinder, scene) {
  27206. if (scene.getGeometryByID(parsedCylinder.id)) {
  27207. return null; // null since geometry could be something else than a cylinder...
  27208. }
  27209. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27210. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27211. scene.pushGeometry(cylinder, true);
  27212. return cylinder;
  27213. };
  27214. return Cylinder;
  27215. })(_Primitive);
  27216. Primitives.Cylinder = Cylinder;
  27217. var Torus = (function (_super) {
  27218. __extends(Torus, _super);
  27219. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27220. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27221. this.diameter = diameter;
  27222. this.thickness = thickness;
  27223. this.tessellation = tessellation;
  27224. this.side = side;
  27225. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27226. }
  27227. Torus.prototype._regenerateVertexData = function () {
  27228. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27229. };
  27230. Torus.prototype.copy = function (id) {
  27231. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27232. };
  27233. Torus.prototype.serialize = function () {
  27234. var serializationObject = _super.prototype.serialize.call(this);
  27235. serializationObject.diameter = this.diameter;
  27236. serializationObject.thickness = this.thickness;
  27237. serializationObject.tessellation = this.tessellation;
  27238. return serializationObject;
  27239. };
  27240. Torus.Parse = function (parsedTorus, scene) {
  27241. if (scene.getGeometryByID(parsedTorus.id)) {
  27242. return null; // null since geometry could be something else than a torus...
  27243. }
  27244. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27245. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27246. scene.pushGeometry(torus, true);
  27247. return torus;
  27248. };
  27249. return Torus;
  27250. })(_Primitive);
  27251. Primitives.Torus = Torus;
  27252. var Ground = (function (_super) {
  27253. __extends(Ground, _super);
  27254. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27255. this.width = width;
  27256. this.height = height;
  27257. this.subdivisions = subdivisions;
  27258. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27259. }
  27260. Ground.prototype._regenerateVertexData = function () {
  27261. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27262. };
  27263. Ground.prototype.copy = function (id) {
  27264. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27265. };
  27266. Ground.prototype.serialize = function () {
  27267. var serializationObject = _super.prototype.serialize.call(this);
  27268. serializationObject.width = this.width;
  27269. serializationObject.height = this.height;
  27270. serializationObject.subdivisions = this.subdivisions;
  27271. return serializationObject;
  27272. };
  27273. Ground.Parse = function (parsedGround, scene) {
  27274. if (scene.getGeometryByID(parsedGround.id)) {
  27275. return null; // null since geometry could be something else than a ground...
  27276. }
  27277. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27278. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27279. scene.pushGeometry(ground, true);
  27280. return ground;
  27281. };
  27282. return Ground;
  27283. })(_Primitive);
  27284. Primitives.Ground = Ground;
  27285. var TiledGround = (function (_super) {
  27286. __extends(TiledGround, _super);
  27287. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27288. this.xmin = xmin;
  27289. this.zmin = zmin;
  27290. this.xmax = xmax;
  27291. this.zmax = zmax;
  27292. this.subdivisions = subdivisions;
  27293. this.precision = precision;
  27294. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27295. }
  27296. TiledGround.prototype._regenerateVertexData = function () {
  27297. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27298. };
  27299. TiledGround.prototype.copy = function (id) {
  27300. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27301. };
  27302. return TiledGround;
  27303. })(_Primitive);
  27304. Primitives.TiledGround = TiledGround;
  27305. var Plane = (function (_super) {
  27306. __extends(Plane, _super);
  27307. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27308. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27309. this.size = size;
  27310. this.side = side;
  27311. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27312. }
  27313. Plane.prototype._regenerateVertexData = function () {
  27314. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27315. };
  27316. Plane.prototype.copy = function (id) {
  27317. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27318. };
  27319. Plane.prototype.serialize = function () {
  27320. var serializationObject = _super.prototype.serialize.call(this);
  27321. serializationObject.size = this.size;
  27322. return serializationObject;
  27323. };
  27324. Plane.Parse = function (parsedPlane, scene) {
  27325. if (scene.getGeometryByID(parsedPlane.id)) {
  27326. return null; // null since geometry could be something else than a ground...
  27327. }
  27328. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27329. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27330. scene.pushGeometry(plane, true);
  27331. return plane;
  27332. };
  27333. return Plane;
  27334. })(_Primitive);
  27335. Primitives.Plane = Plane;
  27336. var TorusKnot = (function (_super) {
  27337. __extends(TorusKnot, _super);
  27338. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27339. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27340. this.radius = radius;
  27341. this.tube = tube;
  27342. this.radialSegments = radialSegments;
  27343. this.tubularSegments = tubularSegments;
  27344. this.p = p;
  27345. this.q = q;
  27346. this.side = side;
  27347. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27348. }
  27349. TorusKnot.prototype._regenerateVertexData = function () {
  27350. 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 });
  27351. };
  27352. TorusKnot.prototype.copy = function (id) {
  27353. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27354. };
  27355. TorusKnot.prototype.serialize = function () {
  27356. var serializationObject = _super.prototype.serialize.call(this);
  27357. serializationObject.radius = this.radius;
  27358. serializationObject.tube = this.tube;
  27359. serializationObject.radialSegments = this.radialSegments;
  27360. serializationObject.tubularSegments = this.tubularSegments;
  27361. serializationObject.p = this.p;
  27362. serializationObject.q = this.q;
  27363. return serializationObject;
  27364. };
  27365. ;
  27366. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27367. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27368. return null; // null since geometry could be something else than a ground...
  27369. }
  27370. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27371. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27372. scene.pushGeometry(torusKnot, true);
  27373. return torusKnot;
  27374. };
  27375. return TorusKnot;
  27376. })(_Primitive);
  27377. Primitives.TorusKnot = TorusKnot;
  27378. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27379. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27380. })(BABYLON || (BABYLON = {}));
  27381. var BABYLON;
  27382. (function (BABYLON) {
  27383. var GroundMesh = (function (_super) {
  27384. __extends(GroundMesh, _super);
  27385. function GroundMesh(name, scene) {
  27386. _super.call(this, name, scene);
  27387. this.generateOctree = false;
  27388. this._worldInverse = new BABYLON.Matrix();
  27389. }
  27390. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27391. get: function () {
  27392. return this._subdivisions;
  27393. },
  27394. enumerable: true,
  27395. configurable: true
  27396. });
  27397. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27398. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27399. this._subdivisions = chunksCount;
  27400. this.subdivide(this._subdivisions);
  27401. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27402. };
  27403. /**
  27404. * Returns a height (y) value in the Worl system :
  27405. * the ground altitude at the coordinates (x, z) expressed in the World system.
  27406. * Returns the ground y position if (x, z) are outside the ground surface.
  27407. * Not pertinent if the ground is rotated.
  27408. */
  27409. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27410. // express x and y in the ground local system
  27411. x -= this.position.x;
  27412. z -= this.position.z;
  27413. x /= this.scaling.x;
  27414. z /= this.scaling.z;
  27415. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27416. return this.position.y;
  27417. }
  27418. if (!this._heightQuads || this._heightQuads.length == 0) {
  27419. this._computeHeightQuads();
  27420. }
  27421. var facet = this._getFacetAt(x, z);
  27422. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27423. // return y in the World system
  27424. return y * this.scaling.y + this.position.y;
  27425. };
  27426. /**
  27427. * Returns a normalized vector (Vector3) orthogonal to the ground
  27428. * at the ground coordinates (x, z) expressed in the World system.
  27429. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  27430. * Not pertinent if the ground is rotated.
  27431. */
  27432. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27433. var normal = new BABYLON.Vector3(0, 1, 0);
  27434. this.getNormalAtCoordinatesToRef(x, z, normal);
  27435. return normal;
  27436. };
  27437. /**
  27438. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  27439. * at the ground coordinates (x, z) expressed in the World system.
  27440. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  27441. * Not pertinent if the ground is rotated.
  27442. */
  27443. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27444. // express x and y in the ground local system
  27445. x -= this.position.x;
  27446. z -= this.position.z;
  27447. x /= this.scaling.x;
  27448. z /= this.scaling.z;
  27449. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27450. return;
  27451. }
  27452. if (!this._heightQuads || this._heightQuads.length == 0) {
  27453. this._computeHeightQuads();
  27454. }
  27455. var facet = this._getFacetAt(x, z);
  27456. ref.x = facet.x;
  27457. ref.y = facet.y;
  27458. ref.z = facet.z;
  27459. };
  27460. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  27461. GroundMesh.prototype._getFacetAt = function (x, z) {
  27462. // retrieve col and row from x, z coordinates in the ground local system
  27463. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27464. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27465. var quad = this._heightQuads[row * this._subdivisions + col];
  27466. var facet;
  27467. if (z < quad.slope.x * x + quad.slope.y) {
  27468. facet = quad.facet1;
  27469. }
  27470. else {
  27471. facet = quad.facet2;
  27472. }
  27473. return facet;
  27474. };
  27475. // Populates the heightMap array with "facet" elements :
  27476. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  27477. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  27478. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  27479. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  27480. GroundMesh.prototype._computeHeightQuads = function () {
  27481. this._heightQuads = new Array();
  27482. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27483. var v1 = BABYLON.Vector3.Zero();
  27484. var v2 = BABYLON.Vector3.Zero();
  27485. var v3 = BABYLON.Vector3.Zero();
  27486. var v4 = BABYLON.Vector3.Zero();
  27487. var v1v2 = BABYLON.Vector3.Zero();
  27488. var v1v3 = BABYLON.Vector3.Zero();
  27489. var v1v4 = BABYLON.Vector3.Zero();
  27490. var norm1 = BABYLON.Vector3.Zero();
  27491. var norm2 = BABYLON.Vector3.Zero();
  27492. var i = 0;
  27493. var j = 0;
  27494. var k = 0;
  27495. var cd = 0; // 2D slope coefficient : z = cd * x + h
  27496. var h = 0;
  27497. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  27498. var d2 = 0;
  27499. for (var row = 0; row < this._subdivisions; row++) {
  27500. for (var col = 0; col < this._subdivisions; col++) {
  27501. i = col * 3;
  27502. j = row * (this._subdivisions + 1) * 3;
  27503. k = (row + 1) * (this._subdivisions + 1) * 3;
  27504. v1.x = positions[j + i];
  27505. v1.y = positions[j + i + 1];
  27506. v1.z = positions[j + i + 2];
  27507. v2.x = positions[j + i + 3];
  27508. v2.y = positions[j + i + 4];
  27509. v2.z = positions[j + i + 5];
  27510. v3.x = positions[k + i];
  27511. v3.y = positions[k + i + 1];
  27512. v3.z = positions[k + i + 2];
  27513. v4.x = positions[k + i + 3];
  27514. v4.y = positions[k + i + 4];
  27515. v4.z = positions[k + i + 5];
  27516. // 2D slope V1V4
  27517. cd = (v4.z - v1.z) / (v4.x - v1.x);
  27518. h = v1.z - cd * v1.x; // v1 belongs to the slope
  27519. var slope = new BABYLON.Vector2(cd, h);
  27520. // facet equations :
  27521. // we compute each facet normal vector
  27522. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  27523. // we compute the value d by applying the equation to v1 which belongs to the plane
  27524. // then we store the facet equation in a Vector4
  27525. v2.subtractToRef(v1, v1v2);
  27526. v3.subtractToRef(v1, v1v3);
  27527. v4.subtractToRef(v1, v1v4);
  27528. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  27529. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  27530. norm1.normalize();
  27531. norm2.normalize();
  27532. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  27533. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  27534. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  27535. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  27536. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  27537. this._heightQuads.push(quad);
  27538. }
  27539. }
  27540. };
  27541. return GroundMesh;
  27542. })(BABYLON.Mesh);
  27543. BABYLON.GroundMesh = GroundMesh;
  27544. })(BABYLON || (BABYLON = {}));
  27545. var BABYLON;
  27546. (function (BABYLON) {
  27547. var LinesMesh = (function (_super) {
  27548. __extends(LinesMesh, _super);
  27549. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27550. if (parent === void 0) { parent = null; }
  27551. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27552. this.color = new BABYLON.Color3(1, 1, 1);
  27553. this.alpha = 1;
  27554. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27555. attributes: ["position"],
  27556. uniforms: ["worldViewProjection", "color"],
  27557. needAlphaBlending: true
  27558. });
  27559. }
  27560. Object.defineProperty(LinesMesh.prototype, "material", {
  27561. get: function () {
  27562. return this._colorShader;
  27563. },
  27564. enumerable: true,
  27565. configurable: true
  27566. });
  27567. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27568. get: function () {
  27569. return false;
  27570. },
  27571. enumerable: true,
  27572. configurable: true
  27573. });
  27574. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27575. get: function () {
  27576. return false;
  27577. },
  27578. enumerable: true,
  27579. configurable: true
  27580. });
  27581. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27582. var engine = this.getScene().getEngine();
  27583. var indexToBind = this._geometry.getIndexBuffer();
  27584. // VBOs
  27585. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27586. // Color
  27587. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27588. };
  27589. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27590. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27591. return;
  27592. }
  27593. var engine = this.getScene().getEngine();
  27594. // Draw order
  27595. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27596. };
  27597. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27598. return null;
  27599. };
  27600. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27601. this._colorShader.dispose();
  27602. _super.prototype.dispose.call(this, doNotRecurse);
  27603. };
  27604. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27605. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27606. };
  27607. return LinesMesh;
  27608. })(BABYLON.Mesh);
  27609. BABYLON.LinesMesh = LinesMesh;
  27610. })(BABYLON || (BABYLON = {}));
  27611. var BABYLON;
  27612. (function (BABYLON) {
  27613. var DebugLayer = (function () {
  27614. function DebugLayer(scene) {
  27615. var _this = this;
  27616. this._transformationMatrix = BABYLON.Matrix.Identity();
  27617. this._enabled = false;
  27618. this._labelsEnabled = false;
  27619. this._displayStatistics = true;
  27620. this._displayTree = false;
  27621. this._displayLogs = false;
  27622. this._identityMatrix = BABYLON.Matrix.Identity();
  27623. this.axisRatio = 0.02;
  27624. this.accentColor = "orange";
  27625. this._scene = scene;
  27626. this._syncPositions = function () {
  27627. var engine = _this._scene.getEngine();
  27628. var canvasRect = engine.getRenderingCanvasClientRect();
  27629. if (_this._showUI) {
  27630. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27631. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27632. _this._statsDiv.style.width = "400px";
  27633. _this._statsDiv.style.height = "auto";
  27634. _this._statsSubsetDiv.style.maxHeight = "240px";
  27635. _this._optionsDiv.style.left = "0px";
  27636. _this._optionsDiv.style.top = "10px";
  27637. _this._optionsDiv.style.width = "200px";
  27638. _this._optionsDiv.style.height = "auto";
  27639. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27640. _this._logDiv.style.left = "0px";
  27641. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27642. _this._logDiv.style.width = "600px";
  27643. _this._logDiv.style.height = "160px";
  27644. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27645. _this._treeDiv.style.top = "10px";
  27646. _this._treeDiv.style.width = "300px";
  27647. _this._treeDiv.style.height = "auto";
  27648. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27649. }
  27650. _this._globalDiv.style.left = canvasRect.left + "px";
  27651. _this._globalDiv.style.top = canvasRect.top + "px";
  27652. _this._drawingCanvas.style.left = "0px";
  27653. _this._drawingCanvas.style.top = "0px";
  27654. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27655. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27656. var devicePixelRatio = window.devicePixelRatio || 1;
  27657. var context = _this._drawingContext;
  27658. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27659. context.mozBackingStorePixelRatio ||
  27660. context.msBackingStorePixelRatio ||
  27661. context.oBackingStorePixelRatio ||
  27662. context.backingStorePixelRatio || 1;
  27663. _this._ratio = devicePixelRatio / backingStoreRatio;
  27664. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27665. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27666. };
  27667. this._onCanvasClick = function (evt) {
  27668. _this._clickPosition = {
  27669. x: evt.clientX * _this._ratio,
  27670. y: evt.clientY * _this._ratio
  27671. };
  27672. };
  27673. this._syncUI = function () {
  27674. if (_this._showUI) {
  27675. if (_this._displayStatistics) {
  27676. _this._displayStats();
  27677. _this._statsDiv.style.display = "";
  27678. }
  27679. else {
  27680. _this._statsDiv.style.display = "none";
  27681. }
  27682. if (_this._displayLogs) {
  27683. _this._logDiv.style.display = "";
  27684. }
  27685. else {
  27686. _this._logDiv.style.display = "none";
  27687. }
  27688. if (_this._displayTree) {
  27689. _this._treeDiv.style.display = "";
  27690. if (_this._needToRefreshMeshesTree) {
  27691. _this._needToRefreshMeshesTree = false;
  27692. _this._refreshMeshesTreeContent();
  27693. }
  27694. }
  27695. else {
  27696. _this._treeDiv.style.display = "none";
  27697. }
  27698. }
  27699. };
  27700. this._syncData = function () {
  27701. if (_this._labelsEnabled || !_this._showUI) {
  27702. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27703. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27704. var engine = _this._scene.getEngine();
  27705. var viewport = _this._camera.viewport;
  27706. var globalViewport = viewport.toGlobal(engine);
  27707. // Meshes
  27708. var meshes = _this._camera.getActiveMeshes();
  27709. var index;
  27710. var projectedPosition;
  27711. for (index = 0; index < meshes.length; index++) {
  27712. var mesh = meshes.data[index];
  27713. var position = mesh.getBoundingInfo().boundingSphere.center;
  27714. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27715. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27716. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27717. }
  27718. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27719. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27720. }
  27721. }
  27722. // Cameras
  27723. var cameras = _this._scene.cameras;
  27724. for (index = 0; index < cameras.length; index++) {
  27725. var camera = cameras[index];
  27726. if (camera === _this._camera) {
  27727. continue;
  27728. }
  27729. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27730. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27731. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27732. _this._camera.detachControl(engine.getRenderingCanvas());
  27733. _this._camera = camera;
  27734. _this._camera.attachControl(engine.getRenderingCanvas());
  27735. }, function () { return "purple"; });
  27736. }
  27737. }
  27738. // Lights
  27739. var lights = _this._scene.lights;
  27740. for (index = 0; index < lights.length; index++) {
  27741. var light = lights[index];
  27742. if (light.position) {
  27743. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27744. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27745. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27746. light.setEnabled(!light.isEnabled());
  27747. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27748. }
  27749. }
  27750. }
  27751. }
  27752. _this._clickPosition = undefined;
  27753. };
  27754. }
  27755. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27756. while (this._treeSubsetDiv.hasChildNodes()) {
  27757. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27758. }
  27759. // Add meshes
  27760. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27761. sortedArray.sort(function (a, b) {
  27762. if (a.name === b.name) {
  27763. return 0;
  27764. }
  27765. return (a.name > b.name) ? 1 : -1;
  27766. });
  27767. for (var index = 0; index < sortedArray.length; index++) {
  27768. var mesh = sortedArray[index];
  27769. if (!mesh.isEnabled()) {
  27770. continue;
  27771. }
  27772. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27773. m.isVisible = element.checked;
  27774. }, mesh);
  27775. }
  27776. };
  27777. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27778. this._drawingContext.beginPath();
  27779. this._drawingContext.moveTo(zero.x, zero.y);
  27780. this._drawingContext.lineTo(unit.x, unit.y);
  27781. this._drawingContext.strokeStyle = color;
  27782. this._drawingContext.lineWidth = 4;
  27783. this._drawingContext.stroke();
  27784. this._drawingContext.font = "normal 14px Segoe UI";
  27785. this._drawingContext.fillStyle = color;
  27786. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27787. };
  27788. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27789. var position = mesh.getBoundingInfo().boundingSphere.center;
  27790. var worldMatrix = mesh.getWorldMatrix();
  27791. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27792. var unit = (unprojectedVector.subtract(position)).length();
  27793. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27794. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27795. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27796. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27797. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27798. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27799. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27800. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27801. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27802. };
  27803. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27804. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27805. this._drawingContext.font = "normal 12px Segoe UI";
  27806. var textMetrics = this._drawingContext.measureText(text);
  27807. var centerX = projectedPosition.x - textMetrics.width / 2;
  27808. var centerY = projectedPosition.y;
  27809. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27810. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27811. onClick();
  27812. }
  27813. this._drawingContext.beginPath();
  27814. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27815. this._drawingContext.fillStyle = getFillStyle();
  27816. this._drawingContext.globalAlpha = 0.5;
  27817. this._drawingContext.fill();
  27818. this._drawingContext.globalAlpha = 1.0;
  27819. this._drawingContext.strokeStyle = '#FFFFFF';
  27820. this._drawingContext.lineWidth = 1;
  27821. this._drawingContext.stroke();
  27822. this._drawingContext.fillStyle = "#FFFFFF";
  27823. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27824. this._drawingContext.beginPath();
  27825. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27826. this._drawingContext.fill();
  27827. }
  27828. };
  27829. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27830. if (!this._clickPosition) {
  27831. return false;
  27832. }
  27833. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27834. return false;
  27835. }
  27836. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27837. return false;
  27838. }
  27839. return true;
  27840. };
  27841. DebugLayer.prototype.isVisible = function () {
  27842. return this._enabled;
  27843. };
  27844. DebugLayer.prototype.hide = function () {
  27845. if (!this._enabled) {
  27846. return;
  27847. }
  27848. this._enabled = false;
  27849. var engine = this._scene.getEngine();
  27850. this._scene.unregisterBeforeRender(this._syncData);
  27851. this._scene.unregisterAfterRender(this._syncUI);
  27852. this._rootElement.removeChild(this._globalDiv);
  27853. this._scene.forceShowBoundingBoxes = false;
  27854. this._scene.forceWireframe = false;
  27855. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27856. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27857. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27858. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27859. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27860. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27861. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27862. BABYLON.StandardMaterial.LightmapEnabled = true;
  27863. this._scene.shadowsEnabled = true;
  27864. this._scene.particlesEnabled = true;
  27865. this._scene.postProcessesEnabled = true;
  27866. this._scene.collisionsEnabled = true;
  27867. this._scene.lightsEnabled = true;
  27868. this._scene.texturesEnabled = true;
  27869. this._scene.lensFlaresEnabled = true;
  27870. this._scene.proceduralTexturesEnabled = true;
  27871. this._scene.renderTargetsEnabled = true;
  27872. this._scene.probesEnabled = true;
  27873. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27874. };
  27875. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27876. if (showUI === void 0) { showUI = true; }
  27877. if (camera === void 0) { camera = null; }
  27878. if (rootElement === void 0) { rootElement = null; }
  27879. if (this._enabled) {
  27880. return;
  27881. }
  27882. this._enabled = true;
  27883. if (camera) {
  27884. this._camera = camera;
  27885. }
  27886. else {
  27887. this._camera = this._scene.activeCamera;
  27888. }
  27889. this._showUI = showUI;
  27890. var engine = this._scene.getEngine();
  27891. this._globalDiv = document.createElement("div");
  27892. this._rootElement = rootElement || document.body;
  27893. this._rootElement.appendChild(this._globalDiv);
  27894. this._generateDOMelements();
  27895. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27896. this._syncPositions();
  27897. this._scene.registerBeforeRender(this._syncData);
  27898. this._scene.registerAfterRender(this._syncUI);
  27899. };
  27900. DebugLayer.prototype._clearLabels = function () {
  27901. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27902. for (var index = 0; index < this._scene.meshes.length; index++) {
  27903. var mesh = this._scene.meshes[index];
  27904. mesh.renderOverlay = false;
  27905. }
  27906. };
  27907. DebugLayer.prototype._generateheader = function (root, text) {
  27908. var header = document.createElement("div");
  27909. header.innerHTML = text + "&nbsp;";
  27910. header.style.textAlign = "right";
  27911. header.style.width = "100%";
  27912. header.style.color = "white";
  27913. header.style.backgroundColor = "Black";
  27914. header.style.padding = "5px 5px 4px 0px";
  27915. header.style.marginLeft = "-5px";
  27916. header.style.fontWeight = "bold";
  27917. root.appendChild(header);
  27918. };
  27919. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27920. var label = document.createElement("label");
  27921. label.innerHTML = title;
  27922. label.style.color = color;
  27923. root.appendChild(label);
  27924. root.appendChild(document.createElement("br"));
  27925. };
  27926. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27927. if (tag === void 0) { tag = null; }
  27928. var label = document.createElement("label");
  27929. var boundingBoxesCheckbox = document.createElement("input");
  27930. boundingBoxesCheckbox.type = "checkbox";
  27931. boundingBoxesCheckbox.checked = initialState;
  27932. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27933. task(evt.target, tag);
  27934. });
  27935. label.appendChild(boundingBoxesCheckbox);
  27936. var container = document.createElement("span");
  27937. var leftPart = document.createElement("span");
  27938. var rightPart = document.createElement("span");
  27939. rightPart.style.cssFloat = "right";
  27940. leftPart.innerHTML = leftTitle;
  27941. rightPart.innerHTML = rightTitle;
  27942. rightPart.style.fontSize = "12px";
  27943. rightPart.style.maxWidth = "200px";
  27944. container.appendChild(leftPart);
  27945. container.appendChild(rightPart);
  27946. label.appendChild(container);
  27947. root.appendChild(label);
  27948. root.appendChild(document.createElement("br"));
  27949. };
  27950. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27951. if (tag === void 0) { tag = null; }
  27952. var label = document.createElement("label");
  27953. var checkBox = document.createElement("input");
  27954. checkBox.type = "checkbox";
  27955. checkBox.checked = initialState;
  27956. checkBox.addEventListener("change", function (evt) {
  27957. task(evt.target, tag);
  27958. });
  27959. label.appendChild(checkBox);
  27960. label.appendChild(document.createTextNode(title));
  27961. root.appendChild(label);
  27962. root.appendChild(document.createElement("br"));
  27963. };
  27964. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27965. if (tag === void 0) { tag = null; }
  27966. var button = document.createElement("button");
  27967. button.innerHTML = title;
  27968. button.style.height = "24px";
  27969. button.style.width = "150px";
  27970. button.style.marginBottom = "5px";
  27971. button.style.color = "#444444";
  27972. button.style.border = "1px solid white";
  27973. button.className = "debugLayerButton";
  27974. button.addEventListener("click", function (evt) {
  27975. task(evt.target, tag);
  27976. });
  27977. root.appendChild(button);
  27978. root.appendChild(document.createElement("br"));
  27979. };
  27980. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27981. if (tag === void 0) { tag = null; }
  27982. var label = document.createElement("label");
  27983. var boundingBoxesRadio = document.createElement("input");
  27984. boundingBoxesRadio.type = "radio";
  27985. boundingBoxesRadio.name = name;
  27986. boundingBoxesRadio.checked = initialState;
  27987. boundingBoxesRadio.addEventListener("change", function (evt) {
  27988. task(evt.target, tag);
  27989. });
  27990. label.appendChild(boundingBoxesRadio);
  27991. label.appendChild(document.createTextNode(title));
  27992. root.appendChild(label);
  27993. root.appendChild(document.createElement("br"));
  27994. };
  27995. DebugLayer.prototype._generateDOMelements = function () {
  27996. var _this = this;
  27997. this._globalDiv.id = "DebugLayer";
  27998. this._globalDiv.style.position = "absolute";
  27999. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28000. this._globalDiv.style.fontSize = "14px";
  28001. this._globalDiv.style.color = "white";
  28002. // Drawing canvas
  28003. this._drawingCanvas = document.createElement("canvas");
  28004. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28005. this._drawingCanvas.style.position = "absolute";
  28006. this._drawingCanvas.style.pointerEvents = "none";
  28007. this._drawingCanvas.style.backgroundColor = "transparent";
  28008. this._drawingContext = this._drawingCanvas.getContext("2d");
  28009. this._globalDiv.appendChild(this._drawingCanvas);
  28010. if (this._showUI) {
  28011. var background = "rgba(128, 128, 128, 0.4)";
  28012. var border = "rgb(180, 180, 180) solid 1px";
  28013. // Stats
  28014. this._statsDiv = document.createElement("div");
  28015. this._statsDiv.id = "DebugLayerStats";
  28016. this._statsDiv.style.border = border;
  28017. this._statsDiv.style.position = "absolute";
  28018. this._statsDiv.style.background = background;
  28019. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28020. this._generateheader(this._statsDiv, "STATISTICS");
  28021. this._statsSubsetDiv = document.createElement("div");
  28022. this._statsSubsetDiv.style.paddingTop = "5px";
  28023. this._statsSubsetDiv.style.paddingBottom = "5px";
  28024. this._statsSubsetDiv.style.overflowY = "auto";
  28025. this._statsDiv.appendChild(this._statsSubsetDiv);
  28026. // Tree
  28027. this._treeDiv = document.createElement("div");
  28028. this._treeDiv.id = "DebugLayerTree";
  28029. this._treeDiv.style.border = border;
  28030. this._treeDiv.style.position = "absolute";
  28031. this._treeDiv.style.background = background;
  28032. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28033. this._treeDiv.style.display = "none";
  28034. this._generateheader(this._treeDiv, "MESHES TREE");
  28035. this._treeSubsetDiv = document.createElement("div");
  28036. this._treeSubsetDiv.style.paddingTop = "5px";
  28037. this._treeSubsetDiv.style.paddingRight = "5px";
  28038. this._treeSubsetDiv.style.overflowY = "auto";
  28039. this._treeSubsetDiv.style.maxHeight = "300px";
  28040. this._treeDiv.appendChild(this._treeSubsetDiv);
  28041. this._needToRefreshMeshesTree = true;
  28042. // Logs
  28043. this._logDiv = document.createElement("div");
  28044. this._logDiv.style.border = border;
  28045. this._logDiv.id = "DebugLayerLogs";
  28046. this._logDiv.style.position = "absolute";
  28047. this._logDiv.style.background = background;
  28048. this._logDiv.style.padding = "0px 0px 0px 5px";
  28049. this._logDiv.style.display = "none";
  28050. this._generateheader(this._logDiv, "LOGS");
  28051. this._logSubsetDiv = document.createElement("div");
  28052. this._logSubsetDiv.style.height = "127px";
  28053. this._logSubsetDiv.style.paddingTop = "5px";
  28054. this._logSubsetDiv.style.overflowY = "auto";
  28055. this._logSubsetDiv.style.fontSize = "12px";
  28056. this._logSubsetDiv.style.fontFamily = "consolas";
  28057. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28058. this._logDiv.appendChild(this._logSubsetDiv);
  28059. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28060. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28061. };
  28062. // Options
  28063. this._optionsDiv = document.createElement("div");
  28064. this._optionsDiv.id = "DebugLayerOptions";
  28065. this._optionsDiv.style.border = border;
  28066. this._optionsDiv.style.position = "absolute";
  28067. this._optionsDiv.style.background = background;
  28068. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28069. this._optionsDiv.style.overflowY = "auto";
  28070. this._generateheader(this._optionsDiv, "OPTIONS");
  28071. this._optionsSubsetDiv = document.createElement("div");
  28072. this._optionsSubsetDiv.style.paddingTop = "5px";
  28073. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28074. this._optionsSubsetDiv.style.overflowY = "auto";
  28075. this._optionsSubsetDiv.style.maxHeight = "200px";
  28076. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28077. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28078. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28079. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28080. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28081. _this._displayTree = element.checked;
  28082. _this._needToRefreshMeshesTree = true;
  28083. });
  28084. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28085. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28086. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28087. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28088. _this._labelsEnabled = element.checked;
  28089. if (!_this._labelsEnabled) {
  28090. _this._clearLabels();
  28091. }
  28092. });
  28093. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28094. if (element.checked) {
  28095. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28096. }
  28097. else {
  28098. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28099. }
  28100. });
  28101. ;
  28102. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28103. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28104. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28105. if (element.checked) {
  28106. _this._scene.forceWireframe = false;
  28107. _this._scene.forcePointsCloud = false;
  28108. }
  28109. });
  28110. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28111. if (element.checked) {
  28112. _this._scene.forceWireframe = true;
  28113. _this._scene.forcePointsCloud = false;
  28114. }
  28115. });
  28116. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28117. if (element.checked) {
  28118. _this._scene.forceWireframe = false;
  28119. _this._scene.forcePointsCloud = true;
  28120. }
  28121. });
  28122. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28123. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28124. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28125. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28126. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28127. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28128. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28129. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28130. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28131. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28132. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  28133. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28134. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28135. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28136. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28137. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28138. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28139. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28140. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28141. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28142. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28143. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28144. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28145. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28146. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28147. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28148. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28149. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28150. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28151. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28152. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28153. if (element.checked) {
  28154. _this._scene.headphone = true;
  28155. }
  28156. });
  28157. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28158. if (element.checked) {
  28159. _this._scene.headphone = false;
  28160. }
  28161. });
  28162. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28163. _this._scene.audioEnabled = !element.checked;
  28164. });
  28165. }
  28166. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28167. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28168. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28169. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28170. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28171. if (_this._camera) {
  28172. console.log(_this._camera);
  28173. }
  28174. else {
  28175. console.warn("No camera defined, or debug layer created before camera creation!");
  28176. }
  28177. });
  28178. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28179. this._globalDiv.appendChild(this._statsDiv);
  28180. this._globalDiv.appendChild(this._logDiv);
  28181. this._globalDiv.appendChild(this._optionsDiv);
  28182. this._globalDiv.appendChild(this._treeDiv);
  28183. }
  28184. };
  28185. DebugLayer.prototype._displayStats = function () {
  28186. var scene = this._scene;
  28187. var engine = scene.getEngine();
  28188. var glInfo = engine.getGlInfo();
  28189. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28190. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28191. + "<b>Count</b><br>"
  28192. + "Total meshes: " + scene.meshes.length + "<br>"
  28193. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28194. + "Total materials: " + scene.materials.length + "<br>"
  28195. + "Total textures: " + scene.textures.length + "<br>"
  28196. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28197. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28198. + "Active bones: " + scene.getActiveBones() + "<br>"
  28199. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28200. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  28201. + "<b>Duration</b><br>"
  28202. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28203. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28204. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28205. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28206. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28207. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28208. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  28209. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  28210. + "</div>"
  28211. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28212. + "<b>Extensions</b><br>"
  28213. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28214. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28215. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28216. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  28217. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28218. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28219. + "<b>Caps.</b><br>"
  28220. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28221. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28222. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  28223. + "</div><br>"
  28224. + "<b>Info</b><br>"
  28225. + glInfo.version + "<br>"
  28226. + glInfo.renderer + "<br>";
  28227. if (this.customStatsFunction) {
  28228. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28229. }
  28230. };
  28231. return DebugLayer;
  28232. })();
  28233. BABYLON.DebugLayer = DebugLayer;
  28234. })(BABYLON || (BABYLON = {}));
  28235. var BABYLON;
  28236. (function (BABYLON) {
  28237. var DefaultLoadingScreen = (function () {
  28238. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28239. var _this = this;
  28240. if (_loadingText === void 0) { _loadingText = ""; }
  28241. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28242. this._renderingCanvas = _renderingCanvas;
  28243. this._loadingText = _loadingText;
  28244. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28245. // Resize
  28246. this._resizeLoadingUI = function () {
  28247. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28248. _this._loadingDiv.style.position = "absolute";
  28249. _this._loadingDiv.style.left = canvasRect.left + "px";
  28250. _this._loadingDiv.style.top = canvasRect.top + "px";
  28251. _this._loadingDiv.style.width = canvasRect.width + "px";
  28252. _this._loadingDiv.style.height = canvasRect.height + "px";
  28253. };
  28254. }
  28255. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28256. var _this = this;
  28257. this._loadingDiv = document.createElement("div");
  28258. this._loadingDiv.id = "babylonjsLoadingDiv";
  28259. this._loadingDiv.style.opacity = "0";
  28260. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28261. // Loading text
  28262. this._loadingTextDiv = document.createElement("div");
  28263. this._loadingTextDiv.style.position = "absolute";
  28264. this._loadingTextDiv.style.left = "0";
  28265. this._loadingTextDiv.style.top = "50%";
  28266. this._loadingTextDiv.style.marginTop = "80px";
  28267. this._loadingTextDiv.style.width = "100%";
  28268. this._loadingTextDiv.style.height = "20px";
  28269. this._loadingTextDiv.style.fontFamily = "Arial";
  28270. this._loadingTextDiv.style.fontSize = "14px";
  28271. this._loadingTextDiv.style.color = "white";
  28272. this._loadingTextDiv.style.textAlign = "center";
  28273. this._loadingTextDiv.innerHTML = "Loading";
  28274. this._loadingDiv.appendChild(this._loadingTextDiv);
  28275. //set the predefined text
  28276. this._loadingTextDiv.innerHTML = this._loadingText;
  28277. // Loading img
  28278. var imgBack = new Image();
  28279. 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==";
  28280. imgBack.style.position = "absolute";
  28281. imgBack.style.left = "50%";
  28282. imgBack.style.top = "50%";
  28283. imgBack.style.marginLeft = "-50px";
  28284. imgBack.style.marginTop = "-50px";
  28285. imgBack.style.transition = "transform 1.0s ease";
  28286. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28287. var deg = 360;
  28288. var onTransitionEnd = function () {
  28289. deg += 360;
  28290. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28291. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28292. };
  28293. imgBack.addEventListener("transitionend", onTransitionEnd);
  28294. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28295. this._loadingDiv.appendChild(imgBack);
  28296. // front image
  28297. var imgFront = new Image();
  28298. 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=";
  28299. imgFront.style.position = "absolute";
  28300. imgFront.style.left = "50%";
  28301. imgFront.style.top = "50%";
  28302. imgFront.style.marginLeft = "-50px";
  28303. imgFront.style.marginTop = "-50px";
  28304. this._loadingDiv.appendChild(imgFront);
  28305. this._resizeLoadingUI();
  28306. window.addEventListener("resize", this._resizeLoadingUI);
  28307. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28308. document.body.appendChild(this._loadingDiv);
  28309. setTimeout(function () {
  28310. _this._loadingDiv.style.opacity = "1";
  28311. imgBack.style.transform = "rotateZ(360deg)";
  28312. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28313. }, 0);
  28314. };
  28315. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28316. var _this = this;
  28317. if (!this._loadingDiv) {
  28318. return;
  28319. }
  28320. var onTransitionEnd = function () {
  28321. if (!_this._loadingDiv) {
  28322. return;
  28323. }
  28324. document.body.removeChild(_this._loadingDiv);
  28325. window.removeEventListener("resize", _this._resizeLoadingUI);
  28326. _this._loadingDiv = null;
  28327. };
  28328. this._loadingDiv.style.opacity = "0";
  28329. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28330. };
  28331. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28332. set: function (text) {
  28333. this._loadingText = text;
  28334. if (this._loadingTextDiv) {
  28335. this._loadingTextDiv.innerHTML = this._loadingText;
  28336. }
  28337. },
  28338. enumerable: true,
  28339. configurable: true
  28340. });
  28341. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28342. get: function () {
  28343. return this._loadingDivBackgroundColor;
  28344. },
  28345. set: function (color) {
  28346. this._loadingDivBackgroundColor = color;
  28347. if (!this._loadingDiv) {
  28348. return;
  28349. }
  28350. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28351. },
  28352. enumerable: true,
  28353. configurable: true
  28354. });
  28355. return DefaultLoadingScreen;
  28356. })();
  28357. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28358. })(BABYLON || (BABYLON = {}));
  28359. var BABYLON;
  28360. (function (BABYLON) {
  28361. var SIMDVector3 = (function () {
  28362. function SIMDVector3() {
  28363. }
  28364. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  28365. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  28366. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28367. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28368. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28369. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28370. 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));
  28371. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28372. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28373. };
  28374. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  28375. var v0 = SIMD.float32x4.splat(x);
  28376. var v1 = SIMD.float32x4.splat(y);
  28377. var v2 = SIMD.float32x4.splat(z);
  28378. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28379. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28380. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28381. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28382. 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));
  28383. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28384. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28385. };
  28386. return SIMDVector3;
  28387. })();
  28388. BABYLON.SIMDVector3 = SIMDVector3;
  28389. var SIMDMatrix = (function () {
  28390. function SIMDMatrix() {
  28391. }
  28392. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28393. if (offset === void 0) { offset = 0; }
  28394. var tm = this.m;
  28395. var om = other.m;
  28396. var om0 = SIMD.float32x4.load(om, 0);
  28397. var om1 = SIMD.float32x4.load(om, 4);
  28398. var om2 = SIMD.float32x4.load(om, 8);
  28399. var om3 = SIMD.float32x4.load(om, 12);
  28400. var tm0 = SIMD.float32x4.load(tm, 0);
  28401. 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)))));
  28402. var tm1 = SIMD.float32x4.load(tm, 4);
  28403. 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)))));
  28404. var tm2 = SIMD.float32x4.load(tm, 8);
  28405. 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)))));
  28406. var tm3 = SIMD.float32x4.load(tm, 12);
  28407. 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)))));
  28408. };
  28409. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28410. var src = this.m;
  28411. var dest = other.m;
  28412. var row0, row1, row2, row3;
  28413. var tmp1;
  28414. var minor0, minor1, minor2, minor3;
  28415. var det;
  28416. // Load the 4 rows
  28417. var src0 = SIMD.float32x4.load(src, 0);
  28418. var src1 = SIMD.float32x4.load(src, 4);
  28419. var src2 = SIMD.float32x4.load(src, 8);
  28420. var src3 = SIMD.float32x4.load(src, 12);
  28421. // Transpose the source matrix. Sort of. Not a true transpose operation
  28422. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28423. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28424. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28425. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28426. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28427. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28428. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28429. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28430. // This is a true transposition, but it will lead to an incorrect result
  28431. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28432. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28433. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28434. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28435. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28436. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28437. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28438. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28439. // ----
  28440. tmp1 = SIMD.float32x4.mul(row2, row3);
  28441. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28442. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28443. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28444. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28445. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28446. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28447. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28448. // ----
  28449. tmp1 = SIMD.float32x4.mul(row1, row2);
  28450. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28451. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28452. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28453. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28454. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28455. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28456. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28457. // ----
  28458. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28459. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28460. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28461. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28462. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28463. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28464. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28465. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28466. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28467. // ----
  28468. tmp1 = SIMD.float32x4.mul(row0, row1);
  28469. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28470. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  28471. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  28472. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28473. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  28474. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  28475. // ----
  28476. tmp1 = SIMD.float32x4.mul(row0, row3);
  28477. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28478. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  28479. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  28480. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28481. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  28482. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  28483. // ----
  28484. tmp1 = SIMD.float32x4.mul(row0, row2);
  28485. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28486. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  28487. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  28488. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28489. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  28490. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  28491. // Compute determinant
  28492. det = SIMD.float32x4.mul(row0, minor0);
  28493. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  28494. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  28495. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  28496. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  28497. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  28498. // These shuffles aren't necessary if the faulty transposition is done
  28499. // up at the top of this function.
  28500. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  28501. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  28502. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  28503. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  28504. // Compute final values by multiplying with 1/det
  28505. minor0 = SIMD.float32x4.mul(det, minor0);
  28506. minor1 = SIMD.float32x4.mul(det, minor1);
  28507. minor2 = SIMD.float32x4.mul(det, minor2);
  28508. minor3 = SIMD.float32x4.mul(det, minor3);
  28509. SIMD.float32x4.store(dest, 0, minor0);
  28510. SIMD.float32x4.store(dest, 4, minor1);
  28511. SIMD.float32x4.store(dest, 8, minor2);
  28512. SIMD.float32x4.store(dest, 12, minor3);
  28513. return this;
  28514. };
  28515. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  28516. var out = result.m;
  28517. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  28518. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  28519. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  28520. // cc.kmVec3Subtract(f, pCenter, pEye);
  28521. var f = SIMD.float32x4.sub(center, eye);
  28522. // cc.kmVec3Normalize(f, f);
  28523. var tmp = SIMD.float32x4.mul(f, f);
  28524. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28525. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28526. // cc.kmVec3Assign(up, pUp);
  28527. // cc.kmVec3Normalize(up, up);
  28528. tmp = SIMD.float32x4.mul(up, up);
  28529. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28530. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28531. // cc.kmVec3Cross(s, f, up);
  28532. 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)));
  28533. // cc.kmVec3Normalize(s, s);
  28534. tmp = SIMD.float32x4.mul(s, s);
  28535. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28536. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28537. // cc.kmVec3Cross(u, s, f);
  28538. 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)));
  28539. // cc.kmVec3Normalize(s, s);
  28540. tmp = SIMD.float32x4.mul(s, s);
  28541. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28542. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28543. var zero = SIMD.float32x4.splat(0.0);
  28544. s = SIMD.float32x4.neg(s);
  28545. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28546. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28547. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28548. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28549. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28550. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28551. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28552. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28553. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28554. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28555. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28556. var b3 = SIMD.float32x4.neg(eye);
  28557. b3 = SIMD.float32x4.withW(b3, 1.0);
  28558. 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)))));
  28559. 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)))));
  28560. 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)))));
  28561. 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)))));
  28562. };
  28563. return SIMDMatrix;
  28564. })();
  28565. BABYLON.SIMDMatrix = SIMDMatrix;
  28566. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28567. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28568. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28569. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28570. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28571. var SIMDHelper = (function () {
  28572. function SIMDHelper() {
  28573. }
  28574. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28575. get: function () {
  28576. return SIMDHelper._isEnabled;
  28577. },
  28578. enumerable: true,
  28579. configurable: true
  28580. });
  28581. SIMDHelper.DisableSIMD = function () {
  28582. // Replace functions
  28583. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28584. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28585. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28586. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28587. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28588. SIMDHelper._isEnabled = false;
  28589. };
  28590. SIMDHelper.EnableSIMD = function () {
  28591. if (window.SIMD === undefined) {
  28592. return;
  28593. }
  28594. // Replace functions
  28595. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28596. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28597. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28598. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28599. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28600. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28601. get: function () { return this._data[0]; },
  28602. set: function (value) {
  28603. if (!this._data) {
  28604. this._data = new Float32Array(3);
  28605. }
  28606. this._data[0] = value;
  28607. }
  28608. });
  28609. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28610. get: function () { return this._data[1]; },
  28611. set: function (value) {
  28612. this._data[1] = value;
  28613. }
  28614. });
  28615. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28616. get: function () { return this._data[2]; },
  28617. set: function (value) {
  28618. this._data[2] = value;
  28619. }
  28620. });
  28621. SIMDHelper._isEnabled = true;
  28622. };
  28623. SIMDHelper._isEnabled = false;
  28624. return SIMDHelper;
  28625. })();
  28626. BABYLON.SIMDHelper = SIMDHelper;
  28627. })(BABYLON || (BABYLON = {}));
  28628. var BABYLON;
  28629. (function (BABYLON) {
  28630. var ShaderMaterial = (function (_super) {
  28631. __extends(ShaderMaterial, _super);
  28632. function ShaderMaterial(name, scene, shaderPath, options) {
  28633. _super.call(this, name, scene);
  28634. this._textures = {};
  28635. this._floats = {};
  28636. this._floatsArrays = {};
  28637. this._colors3 = {};
  28638. this._colors4 = {};
  28639. this._vectors2 = {};
  28640. this._vectors3 = {};
  28641. this._vectors4 = {};
  28642. this._matrices = {};
  28643. this._matrices3x3 = {};
  28644. this._matrices2x2 = {};
  28645. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28646. this._shaderPath = shaderPath;
  28647. options.needAlphaBlending = options.needAlphaBlending || false;
  28648. options.needAlphaTesting = options.needAlphaTesting || false;
  28649. options.attributes = options.attributes || ["position", "normal", "uv"];
  28650. options.uniforms = options.uniforms || ["worldViewProjection"];
  28651. options.samplers = options.samplers || [];
  28652. options.defines = options.defines || [];
  28653. this._options = options;
  28654. }
  28655. ShaderMaterial.prototype.needAlphaBlending = function () {
  28656. return this._options.needAlphaBlending;
  28657. };
  28658. ShaderMaterial.prototype.needAlphaTesting = function () {
  28659. return this._options.needAlphaTesting;
  28660. };
  28661. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28662. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28663. this._options.uniforms.push(uniformName);
  28664. }
  28665. };
  28666. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28667. if (this._options.samplers.indexOf(name) === -1) {
  28668. this._options.samplers.push(name);
  28669. }
  28670. this._textures[name] = texture;
  28671. return this;
  28672. };
  28673. ShaderMaterial.prototype.setFloat = function (name, value) {
  28674. this._checkUniform(name);
  28675. this._floats[name] = value;
  28676. return this;
  28677. };
  28678. ShaderMaterial.prototype.setFloats = function (name, value) {
  28679. this._checkUniform(name);
  28680. this._floatsArrays[name] = value;
  28681. return this;
  28682. };
  28683. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28684. this._checkUniform(name);
  28685. this._colors3[name] = value;
  28686. return this;
  28687. };
  28688. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28689. this._checkUniform(name);
  28690. this._colors4[name] = value;
  28691. return this;
  28692. };
  28693. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28694. this._checkUniform(name);
  28695. this._vectors2[name] = value;
  28696. return this;
  28697. };
  28698. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28699. this._checkUniform(name);
  28700. this._vectors3[name] = value;
  28701. return this;
  28702. };
  28703. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28704. this._checkUniform(name);
  28705. this._vectors4[name] = value;
  28706. return this;
  28707. };
  28708. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28709. this._checkUniform(name);
  28710. this._matrices[name] = value;
  28711. return this;
  28712. };
  28713. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28714. this._checkUniform(name);
  28715. this._matrices3x3[name] = value;
  28716. return this;
  28717. };
  28718. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28719. this._checkUniform(name);
  28720. this._matrices2x2[name] = value;
  28721. return this;
  28722. };
  28723. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28724. var scene = this.getScene();
  28725. var engine = scene.getEngine();
  28726. if (!this.checkReadyOnEveryCall) {
  28727. if (this._renderId === scene.getRenderId()) {
  28728. return true;
  28729. }
  28730. }
  28731. // Instances
  28732. var defines = [];
  28733. var fallbacks = new BABYLON.EffectFallbacks();
  28734. if (useInstances) {
  28735. defines.push("#define INSTANCES");
  28736. }
  28737. for (var index = 0; index < this._options.defines.length; index++) {
  28738. defines.push(this._options.defines[index]);
  28739. }
  28740. // Bones
  28741. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28742. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28743. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28744. fallbacks.addCPUSkinningFallback(0, mesh);
  28745. }
  28746. // Alpha test
  28747. if (engine.getAlphaTesting()) {
  28748. defines.push("#define ALPHATEST");
  28749. }
  28750. var previousEffect = this._effect;
  28751. var join = defines.join("\n");
  28752. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28753. if (!this._effect.isReady()) {
  28754. return false;
  28755. }
  28756. if (previousEffect !== this._effect) {
  28757. scene.resetCachedMaterial();
  28758. }
  28759. this._renderId = scene.getRenderId();
  28760. return true;
  28761. };
  28762. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28763. var scene = this.getScene();
  28764. if (this._options.uniforms.indexOf("world") !== -1) {
  28765. this._effect.setMatrix("world", world);
  28766. }
  28767. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28768. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28769. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28770. }
  28771. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28772. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28773. }
  28774. };
  28775. ShaderMaterial.prototype.bind = function (world, mesh) {
  28776. // Std values
  28777. this.bindOnlyWorldMatrix(world);
  28778. if (this.getScene().getCachedMaterial() !== this) {
  28779. if (this._options.uniforms.indexOf("view") !== -1) {
  28780. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28781. }
  28782. if (this._options.uniforms.indexOf("projection") !== -1) {
  28783. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28784. }
  28785. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28786. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28787. }
  28788. // Bones
  28789. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28790. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28791. }
  28792. // Texture
  28793. for (var name in this._textures) {
  28794. this._effect.setTexture(name, this._textures[name]);
  28795. }
  28796. // Float
  28797. for (name in this._floats) {
  28798. this._effect.setFloat(name, this._floats[name]);
  28799. }
  28800. // Float s
  28801. for (name in this._floatsArrays) {
  28802. this._effect.setArray(name, this._floatsArrays[name]);
  28803. }
  28804. // Color3
  28805. for (name in this._colors3) {
  28806. this._effect.setColor3(name, this._colors3[name]);
  28807. }
  28808. // Color4
  28809. for (name in this._colors4) {
  28810. var color = this._colors4[name];
  28811. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28812. }
  28813. // Vector2
  28814. for (name in this._vectors2) {
  28815. this._effect.setVector2(name, this._vectors2[name]);
  28816. }
  28817. // Vector3
  28818. for (name in this._vectors3) {
  28819. this._effect.setVector3(name, this._vectors3[name]);
  28820. }
  28821. // Vector4
  28822. for (name in this._vectors4) {
  28823. this._effect.setVector4(name, this._vectors4[name]);
  28824. }
  28825. // Matrix
  28826. for (name in this._matrices) {
  28827. this._effect.setMatrix(name, this._matrices[name]);
  28828. }
  28829. // Matrix 3x3
  28830. for (name in this._matrices3x3) {
  28831. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28832. }
  28833. // Matrix 2x2
  28834. for (name in this._matrices2x2) {
  28835. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28836. }
  28837. }
  28838. _super.prototype.bind.call(this, world, mesh);
  28839. };
  28840. ShaderMaterial.prototype.clone = function (name) {
  28841. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28842. return newShaderMaterial;
  28843. };
  28844. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28845. for (var name in this._textures) {
  28846. this._textures[name].dispose();
  28847. }
  28848. this._textures = {};
  28849. _super.prototype.dispose.call(this, forceDisposeEffect);
  28850. };
  28851. ShaderMaterial.prototype.serialize = function () {
  28852. var serializationObject = _super.prototype.serialize.call(this);
  28853. serializationObject.options = this._options;
  28854. serializationObject.shaderPath = this._shaderPath;
  28855. serializationObject.customType = "BABYLON.ShaderMaterial";
  28856. // Texture
  28857. serializationObject.textures = {};
  28858. for (var name in this._textures) {
  28859. serializationObject.textures[name] = this._textures[name].serialize();
  28860. }
  28861. // Float
  28862. serializationObject.floats = {};
  28863. for (name in this._floats) {
  28864. serializationObject.floats[name] = this._floats[name];
  28865. }
  28866. // Float s
  28867. serializationObject.floatArrays = {};
  28868. for (name in this._floatsArrays) {
  28869. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28870. }
  28871. // Color3
  28872. serializationObject.colors3 = {};
  28873. for (name in this._colors3) {
  28874. serializationObject.colors3[name] = this._colors3[name].asArray();
  28875. }
  28876. // Color4
  28877. serializationObject.colors4 = {};
  28878. for (name in this._colors4) {
  28879. serializationObject.colors4[name] = this._colors4[name].asArray();
  28880. }
  28881. // Vector2
  28882. serializationObject.vectors2 = {};
  28883. for (name in this._vectors2) {
  28884. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28885. }
  28886. // Vector3
  28887. serializationObject.vectors3 = {};
  28888. for (name in this._vectors3) {
  28889. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28890. }
  28891. // Vector4
  28892. serializationObject.vectors4 = {};
  28893. for (name in this._vectors4) {
  28894. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28895. }
  28896. // Matrix
  28897. serializationObject.matrices = {};
  28898. for (name in this._matrices) {
  28899. serializationObject.matrices[name] = this._matrices[name].asArray();
  28900. }
  28901. // Matrix 3x3
  28902. serializationObject.matrices3x3 = {};
  28903. for (name in this._matrices3x3) {
  28904. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28905. }
  28906. // Matrix 2x2
  28907. serializationObject.matrices2x2 = {};
  28908. for (name in this._matrices2x2) {
  28909. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28910. }
  28911. return serializationObject;
  28912. };
  28913. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28914. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  28915. // Texture
  28916. for (var name in source.textures) {
  28917. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28918. }
  28919. // Float
  28920. for (name in source.floats) {
  28921. material.setFloat(name, source.floats[name]);
  28922. }
  28923. // Float s
  28924. for (name in source.floatsArrays) {
  28925. material.setFloats(name, source.floatsArrays[name]);
  28926. }
  28927. // Color3
  28928. for (name in source.colors3) {
  28929. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28930. }
  28931. // Color4
  28932. for (name in source.colors4) {
  28933. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28934. }
  28935. // Vector2
  28936. for (name in source.vectors2) {
  28937. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28938. }
  28939. // Vector3
  28940. for (name in source.vectors3) {
  28941. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28942. }
  28943. // Vector4
  28944. for (name in source.vectors4) {
  28945. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28946. }
  28947. // Matrix
  28948. for (name in source.matrices) {
  28949. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28950. }
  28951. // Matrix 3x3
  28952. for (name in source.matrices3x3) {
  28953. material.setMatrix3x3(name, source.matrices3x3[name]);
  28954. }
  28955. // Matrix 2x2
  28956. for (name in source.matrices2x2) {
  28957. material.setMatrix2x2(name, source.matrices2x2[name]);
  28958. }
  28959. return material;
  28960. };
  28961. return ShaderMaterial;
  28962. })(BABYLON.Material);
  28963. BABYLON.ShaderMaterial = ShaderMaterial;
  28964. })(BABYLON || (BABYLON = {}));
  28965. var BABYLON;
  28966. (function (BABYLON) {
  28967. var Internals;
  28968. (function (Internals) {
  28969. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28970. // All values and structures referenced from:
  28971. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28972. var DDS_MAGIC = 0x20534444;
  28973. 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;
  28974. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28975. 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;
  28976. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28977. function FourCCToInt32(value) {
  28978. return value.charCodeAt(0) +
  28979. (value.charCodeAt(1) << 8) +
  28980. (value.charCodeAt(2) << 16) +
  28981. (value.charCodeAt(3) << 24);
  28982. }
  28983. function Int32ToFourCC(value) {
  28984. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28985. }
  28986. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28987. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28988. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28989. var headerLengthInt = 31; // The header length in 32 bit ints
  28990. // Offsets into the header array
  28991. var off_magic = 0;
  28992. var off_size = 1;
  28993. var off_flags = 2;
  28994. var off_height = 3;
  28995. var off_width = 4;
  28996. var off_mipmapCount = 7;
  28997. var off_pfFlags = 20;
  28998. var off_pfFourCC = 21;
  28999. var off_RGBbpp = 22;
  29000. var off_RMask = 23;
  29001. var off_GMask = 24;
  29002. var off_BMask = 25;
  29003. var off_AMask = 26;
  29004. var off_caps1 = 27;
  29005. var off_caps2 = 28;
  29006. ;
  29007. var DDSTools = (function () {
  29008. function DDSTools() {
  29009. }
  29010. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29011. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29012. var mipmapCount = 1;
  29013. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29014. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29015. }
  29016. return {
  29017. width: header[off_width],
  29018. height: header[off_height],
  29019. mipmapCount: mipmapCount,
  29020. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29021. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29022. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29023. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29024. };
  29025. };
  29026. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29027. var byteArray = new Uint8Array(dataLength);
  29028. var srcData = new Uint8Array(arrayBuffer);
  29029. var index = 0;
  29030. for (var y = height - 1; y >= 0; y--) {
  29031. for (var x = 0; x < width; x++) {
  29032. var srcPos = dataOffset + (x + y * width) * 4;
  29033. byteArray[index + 2] = srcData[srcPos];
  29034. byteArray[index + 1] = srcData[srcPos + 1];
  29035. byteArray[index] = srcData[srcPos + 2];
  29036. byteArray[index + 3] = srcData[srcPos + 3];
  29037. index += 4;
  29038. }
  29039. }
  29040. return byteArray;
  29041. };
  29042. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29043. var byteArray = new Uint8Array(dataLength);
  29044. var srcData = new Uint8Array(arrayBuffer);
  29045. var index = 0;
  29046. for (var y = height - 1; y >= 0; y--) {
  29047. for (var x = 0; x < width; x++) {
  29048. var srcPos = dataOffset + (x + y * width) * 3;
  29049. byteArray[index + 2] = srcData[srcPos];
  29050. byteArray[index + 1] = srcData[srcPos + 1];
  29051. byteArray[index] = srcData[srcPos + 2];
  29052. index += 3;
  29053. }
  29054. }
  29055. return byteArray;
  29056. };
  29057. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29058. var byteArray = new Uint8Array(dataLength);
  29059. var srcData = new Uint8Array(arrayBuffer);
  29060. var index = 0;
  29061. for (var y = height - 1; y >= 0; y--) {
  29062. for (var x = 0; x < width; x++) {
  29063. var srcPos = dataOffset + (x + y * width);
  29064. byteArray[index] = srcData[srcPos];
  29065. index++;
  29066. }
  29067. }
  29068. return byteArray;
  29069. };
  29070. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29071. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29072. if (header[off_magic] != DDS_MAGIC) {
  29073. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29074. return;
  29075. }
  29076. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29077. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29078. return;
  29079. }
  29080. if (info.isFourCC) {
  29081. fourCC = header[off_pfFourCC];
  29082. switch (fourCC) {
  29083. case FOURCC_DXT1:
  29084. blockBytes = 8;
  29085. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29086. break;
  29087. case FOURCC_DXT3:
  29088. blockBytes = 16;
  29089. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29090. break;
  29091. case FOURCC_DXT5:
  29092. blockBytes = 16;
  29093. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29094. break;
  29095. default:
  29096. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29097. return;
  29098. }
  29099. }
  29100. mipmapCount = 1;
  29101. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29102. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29103. }
  29104. var bpp = header[off_RGBbpp];
  29105. for (var face = 0; face < faces; face++) {
  29106. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29107. width = header[off_width];
  29108. height = header[off_height];
  29109. dataOffset = header[off_size] + 4;
  29110. for (i = 0; i < mipmapCount; ++i) {
  29111. if (info.isRGB) {
  29112. if (bpp === 24) {
  29113. dataLength = width * height * 3;
  29114. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29115. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29116. }
  29117. else {
  29118. dataLength = width * height * 4;
  29119. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29120. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29121. }
  29122. }
  29123. else if (info.isLuminance) {
  29124. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29125. var unpaddedRowSize = width;
  29126. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29127. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29128. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29129. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29130. }
  29131. else {
  29132. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29133. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29134. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29135. }
  29136. dataOffset += dataLength;
  29137. width *= 0.5;
  29138. height *= 0.5;
  29139. width = Math.max(1.0, width);
  29140. height = Math.max(1.0, height);
  29141. }
  29142. }
  29143. };
  29144. return DDSTools;
  29145. })();
  29146. Internals.DDSTools = DDSTools;
  29147. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29148. })(BABYLON || (BABYLON = {}));
  29149. var BABYLON;
  29150. (function (BABYLON) {
  29151. var CannonJSPlugin = (function () {
  29152. function CannonJSPlugin() {
  29153. this._registeredMeshes = [];
  29154. this._physicsMaterials = [];
  29155. this.name = "cannon";
  29156. this.updateBodyPosition = function (mesh) {
  29157. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29158. var registeredMesh = this._registeredMeshes[index];
  29159. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29160. var body = registeredMesh.body;
  29161. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29162. body.quaternion.copy(mesh.rotationQuaternion);
  29163. if (registeredMesh.deltaRotation) {
  29164. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29165. body.quaternion = body.quaternion.mult(tmpQ);
  29166. }
  29167. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29168. //calculate the correct body position:
  29169. var rotationQuaternion = mesh.rotationQuaternion;
  29170. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29171. mesh.computeWorldMatrix(true);
  29172. //get original center with no rotation
  29173. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29174. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29175. //rotation is back
  29176. mesh.rotationQuaternion = rotationQuaternion;
  29177. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29178. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29179. mesh.setPivotMatrix(p);
  29180. mesh.computeWorldMatrix(true);
  29181. //calculate the translation
  29182. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29183. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29184. //add it inverted to the delta
  29185. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29186. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29187. mesh.setPivotMatrix(oldPivot);
  29188. mesh.computeWorldMatrix(true);
  29189. }
  29190. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29191. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29192. }
  29193. body.position.set(center.x, center.y, center.z);
  29194. return;
  29195. }
  29196. }
  29197. };
  29198. }
  29199. CannonJSPlugin.prototype.initialize = function (iterations) {
  29200. if (iterations === void 0) { iterations = 10; }
  29201. this._world = new CANNON.World();
  29202. this._world.broadphase = new CANNON.NaiveBroadphase();
  29203. this._world.solver.iterations = iterations;
  29204. };
  29205. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29206. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29207. };
  29208. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29209. var _this = this;
  29210. this._world.step(delta);
  29211. this._registeredMeshes.forEach(function (registeredMesh) {
  29212. // Body position
  29213. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29214. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29215. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29216. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29217. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29218. if (registeredMesh.deltaRotation) {
  29219. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29220. }
  29221. //is the physics collision callback is set?
  29222. if (registeredMesh.mesh.onPhysicsCollide) {
  29223. if (!registeredMesh.collisionFunction) {
  29224. registeredMesh.collisionFunction = function (e) {
  29225. //find the mesh that collided with the registered mesh
  29226. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29227. if (_this._registeredMeshes[idx].body == e.body) {
  29228. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29229. }
  29230. }
  29231. };
  29232. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29233. }
  29234. }
  29235. else {
  29236. //unregister, in case the function was removed for some reason
  29237. if (registeredMesh.collisionFunction) {
  29238. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29239. }
  29240. }
  29241. });
  29242. };
  29243. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29244. this._gravity = gravity;
  29245. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29246. };
  29247. CannonJSPlugin.prototype.getGravity = function () {
  29248. return this._gravity;
  29249. };
  29250. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29251. this.unregisterMesh(mesh);
  29252. if (!mesh.rotationQuaternion) {
  29253. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29254. }
  29255. mesh.computeWorldMatrix(true);
  29256. var shape = this._createShape(mesh, impostor);
  29257. return this._createRigidBodyFromShape(shape, mesh, options);
  29258. };
  29259. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29260. //get the correct bounding box
  29261. var oldQuaternion = mesh.rotationQuaternion;
  29262. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29263. mesh.computeWorldMatrix(true);
  29264. var returnValue;
  29265. switch (impostor) {
  29266. case BABYLON.PhysicsEngine.SphereImpostor:
  29267. var bbox = mesh.getBoundingInfo().boundingBox;
  29268. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29269. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29270. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29271. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29272. break;
  29273. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29274. case BABYLON.PhysicsEngine.CylinderImpostor:
  29275. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29276. case BABYLON.PhysicsEngine.BoxImpostor:
  29277. bbox = mesh.getBoundingInfo().boundingBox;
  29278. var min = bbox.minimumWorld;
  29279. var max = bbox.maximumWorld;
  29280. var box = max.subtract(min).scale(0.5);
  29281. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29282. break;
  29283. case BABYLON.PhysicsEngine.PlaneImpostor:
  29284. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29285. returnValue = new CANNON.Plane();
  29286. break;
  29287. case BABYLON.PhysicsEngine.MeshImpostor:
  29288. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29289. var rawFaces = mesh.getIndices();
  29290. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29291. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29292. break;
  29293. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29294. returnValue = this._createHeightmap(mesh);
  29295. break;
  29296. }
  29297. mesh.rotationQuaternion = oldQuaternion;
  29298. return returnValue;
  29299. };
  29300. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29301. var verts = [], faces = [];
  29302. mesh.computeWorldMatrix(true);
  29303. //reuse this variable
  29304. var transformed = BABYLON.Vector3.Zero();
  29305. // Get vertices
  29306. for (var i = 0; i < rawVerts.length; i += 3) {
  29307. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29308. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29309. }
  29310. // Get faces
  29311. for (var j = 0; j < rawFaces.length; j += 3) {
  29312. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  29313. }
  29314. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  29315. return shape;
  29316. };
  29317. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  29318. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29319. var matrix = [];
  29320. //For now pointDepth will not be used and will be automatically calculated.
  29321. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  29322. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  29323. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  29324. var elementSize = dim * 2 / arraySize;
  29325. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  29326. for (var i = 0; i < pos.length; i = i + 3) {
  29327. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  29328. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  29329. var y = pos[i + 1] + minY;
  29330. if (!matrix[x]) {
  29331. matrix[x] = [];
  29332. }
  29333. if (!matrix[x][z]) {
  29334. matrix[x][z] = y;
  29335. }
  29336. matrix[x][z] = Math.max(y, matrix[x][z]);
  29337. }
  29338. for (var x = 0; x <= arraySize; ++x) {
  29339. if (!matrix[x]) {
  29340. var loc = 1;
  29341. while (!matrix[(x + loc) % arraySize]) {
  29342. loc++;
  29343. }
  29344. matrix[x] = matrix[(x + loc) % arraySize].slice();
  29345. }
  29346. for (var z = 0; z <= arraySize; ++z) {
  29347. if (!matrix[x][z]) {
  29348. var loc = 1;
  29349. var newValue;
  29350. while (newValue === undefined) {
  29351. newValue = matrix[x][(z + loc++) % arraySize];
  29352. }
  29353. matrix[x][z] = newValue;
  29354. }
  29355. }
  29356. }
  29357. var shape = new CANNON.Heightfield(matrix, {
  29358. elementSize: elementSize
  29359. });
  29360. //For future reference, needed for body transformation
  29361. shape.minY = minY;
  29362. return shape;
  29363. };
  29364. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  29365. var index;
  29366. var mat;
  29367. for (index = 0; index < this._physicsMaterials.length; index++) {
  29368. mat = this._physicsMaterials[index];
  29369. if (mat.friction === friction && mat.restitution === restitution) {
  29370. return mat;
  29371. }
  29372. }
  29373. var currentMat = new CANNON.Material("mat");
  29374. this._physicsMaterials.push(currentMat);
  29375. for (index = 0; index < this._physicsMaterials.length; index++) {
  29376. mat = this._physicsMaterials[index];
  29377. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  29378. this._world.addContactMaterial(contactMaterial);
  29379. }
  29380. return currentMat;
  29381. };
  29382. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  29383. if (!mesh.rotationQuaternion) {
  29384. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29385. }
  29386. // The delta between the mesh position and the mesh bounding box center
  29387. var bbox = mesh.getBoundingInfo().boundingBox;
  29388. var deltaPosition = mesh.position.subtract(bbox.center);
  29389. var deltaRotation;
  29390. var material = this._addMaterial(options.friction, options.restitution);
  29391. var body = new CANNON.Body({
  29392. mass: options.mass,
  29393. material: material,
  29394. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29395. });
  29396. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29397. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29398. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29399. //-90 DEG in X, precalculated
  29400. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29401. body.quaternion = body.quaternion.mult(tmpQ);
  29402. //Invert! (Precalculated, 90 deg in X)
  29403. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29404. }
  29405. //If it is a heightfield, if should be centered.
  29406. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29407. //calculate the correct body position:
  29408. var rotationQuaternion = mesh.rotationQuaternion;
  29409. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29410. mesh.computeWorldMatrix(true);
  29411. //get original center with no rotation
  29412. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29413. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29414. //rotation is back
  29415. mesh.rotationQuaternion = rotationQuaternion;
  29416. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29417. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29418. mesh.setPivotMatrix(p);
  29419. mesh.computeWorldMatrix(true);
  29420. //calculate the translation
  29421. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29422. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29423. //add it inverted to the delta
  29424. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29425. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29426. mesh.setPivotMatrix(oldPivot);
  29427. mesh.computeWorldMatrix(true);
  29428. }
  29429. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29430. deltaPosition = BABYLON.Vector3.Zero();
  29431. }
  29432. //add the shape
  29433. body.addShape(shape);
  29434. this._world.add(body);
  29435. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29436. return body;
  29437. };
  29438. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29439. var initialMesh = parts[0].mesh;
  29440. this.unregisterMesh(initialMesh);
  29441. initialMesh.computeWorldMatrix(true);
  29442. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29443. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29444. for (var index = 1; index < parts.length; index++) {
  29445. var mesh = parts[index].mesh;
  29446. mesh.computeWorldMatrix(true);
  29447. var shape = this._createShape(mesh, parts[index].impostor);
  29448. var localPosition = mesh.position;
  29449. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29450. }
  29451. return body;
  29452. };
  29453. CannonJSPlugin.prototype._unbindBody = function (body) {
  29454. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29455. var registeredMesh = this._registeredMeshes[index];
  29456. if (registeredMesh.body === body) {
  29457. this._world.remove(registeredMesh.body);
  29458. registeredMesh.body = null;
  29459. registeredMesh.delta = null;
  29460. registeredMesh.deltaRotation = null;
  29461. }
  29462. }
  29463. };
  29464. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  29465. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29466. var registeredMesh = this._registeredMeshes[index];
  29467. if (registeredMesh.mesh === mesh) {
  29468. // Remove body
  29469. if (registeredMesh.body) {
  29470. this._unbindBody(registeredMesh.body);
  29471. }
  29472. this._registeredMeshes.splice(index, 1);
  29473. return;
  29474. }
  29475. }
  29476. };
  29477. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29478. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  29479. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  29480. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29481. var registeredMesh = this._registeredMeshes[index];
  29482. if (registeredMesh.mesh === mesh) {
  29483. registeredMesh.body.applyImpulse(impulse, worldPoint);
  29484. return;
  29485. }
  29486. }
  29487. };
  29488. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  29489. var body1 = null, body2 = null;
  29490. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29491. var registeredMesh = this._registeredMeshes[index];
  29492. if (registeredMesh.mesh === mesh1) {
  29493. body1 = registeredMesh.body;
  29494. }
  29495. else if (registeredMesh.mesh === mesh2) {
  29496. body2 = registeredMesh.body;
  29497. }
  29498. }
  29499. if (!body1 || !body2) {
  29500. return false;
  29501. }
  29502. 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));
  29503. this._world.addConstraint(constraint);
  29504. return true;
  29505. };
  29506. CannonJSPlugin.prototype.dispose = function () {
  29507. while (this._registeredMeshes.length) {
  29508. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29509. }
  29510. };
  29511. CannonJSPlugin.prototype.isSupported = function () {
  29512. return window.CANNON !== undefined;
  29513. };
  29514. CannonJSPlugin.prototype.getWorldObject = function () {
  29515. return this._world;
  29516. };
  29517. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29518. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29519. var registeredMesh = this._registeredMeshes[index];
  29520. if (registeredMesh.mesh === mesh) {
  29521. return registeredMesh.body;
  29522. }
  29523. }
  29524. return null;
  29525. };
  29526. return CannonJSPlugin;
  29527. })();
  29528. BABYLON.CannonJSPlugin = CannonJSPlugin;
  29529. })(BABYLON || (BABYLON = {}));
  29530. var BABYLON;
  29531. (function (BABYLON) {
  29532. var OimoJSPlugin = (function () {
  29533. function OimoJSPlugin() {
  29534. this._registeredMeshes = [];
  29535. this.name = "oimo";
  29536. /**
  29537. * Update the body position according to the mesh position
  29538. * @param mesh
  29539. */
  29540. this.updateBodyPosition = function (mesh) {
  29541. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29542. var registeredMesh = this._registeredMeshes[index];
  29543. var body = registeredMesh.body.body;
  29544. var updated = false;
  29545. var newPosition;
  29546. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29547. mesh.computeWorldMatrix(true);
  29548. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29549. updated = true;
  29550. }
  29551. else if (registeredMesh.mesh.parent === mesh) {
  29552. mesh.computeWorldMatrix(true);
  29553. registeredMesh.mesh.computeWorldMatrix(true);
  29554. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29555. updated = true;
  29556. }
  29557. if (updated) {
  29558. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29559. body.setQuaternion(mesh.rotationQuaternion);
  29560. body.sleeping = false;
  29561. //force Oimo to update the body's position
  29562. body.updatePosition(1);
  29563. }
  29564. }
  29565. };
  29566. }
  29567. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29568. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29569. };
  29570. OimoJSPlugin.prototype.initialize = function (iterations) {
  29571. this._world = new OIMO.World(null, null, iterations);
  29572. this._world.clear();
  29573. };
  29574. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29575. this._gravity = this._world.gravity = gravity;
  29576. };
  29577. OimoJSPlugin.prototype.getGravity = function () {
  29578. return this._gravity;
  29579. };
  29580. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29581. this.unregisterMesh(mesh);
  29582. if (!mesh.rotationQuaternion) {
  29583. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29584. }
  29585. mesh.computeWorldMatrix(true);
  29586. var bbox = mesh.getBoundingInfo().boundingBox;
  29587. // The delta between the mesh position and the mesh bounding box center
  29588. var deltaPosition = mesh.position.subtract(bbox.center);
  29589. //calculate rotation to fit Oimo's needs (Euler...)
  29590. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29591. //get the correct bounding box
  29592. var oldQuaternion = mesh.rotationQuaternion;
  29593. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29594. mesh.computeWorldMatrix(true);
  29595. var bodyConfig = {
  29596. name: mesh.uniqueId,
  29597. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29598. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29599. move: options.mass != 0,
  29600. config: [options.mass, options.friction, options.restitution],
  29601. world: this._world
  29602. };
  29603. // register mesh
  29604. switch (impostor) {
  29605. case BABYLON.PhysicsEngine.SphereImpostor:
  29606. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29607. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29608. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29609. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29610. bodyConfig.type = 'sphere';
  29611. bodyConfig.size = [size];
  29612. break;
  29613. case BABYLON.PhysicsEngine.PlaneImpostor:
  29614. //Oimo "fakes" a cylinder as a box, so why don't we!
  29615. case BABYLON.PhysicsEngine.CylinderImpostor:
  29616. case BABYLON.PhysicsEngine.BoxImpostor:
  29617. var min = bbox.minimumWorld;
  29618. var max = bbox.maximumWorld;
  29619. var box = max.subtract(min);
  29620. var sizeX = this._checkWithEpsilon(box.x);
  29621. var sizeY = this._checkWithEpsilon(box.y);
  29622. var sizeZ = this._checkWithEpsilon(box.z);
  29623. bodyConfig.type = 'box';
  29624. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29625. break;
  29626. }
  29627. var body = new OIMO.Body(bodyConfig);
  29628. //We have to access the rigid body's properties to set the quaternion.
  29629. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29630. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29631. //TEST
  29632. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29633. //update the internal rotation matrix
  29634. //body.body.syncShapes();
  29635. this._registeredMeshes.push({
  29636. mesh: mesh,
  29637. body: body,
  29638. delta: deltaPosition
  29639. });
  29640. //for the sake of consistency.
  29641. mesh.rotationQuaternion = oldQuaternion;
  29642. return body;
  29643. };
  29644. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29645. var types = [], sizes = [], positions = [], rotations = [];
  29646. var initialMesh = parts[0].mesh;
  29647. for (var index = 0; index < parts.length; index++) {
  29648. var part = parts[index];
  29649. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29650. types.push(bodyParameters.type);
  29651. sizes.push.apply(sizes, bodyParameters.size);
  29652. positions.push.apply(positions, bodyParameters.pos);
  29653. rotations.push.apply(rotations, bodyParameters.rot);
  29654. }
  29655. var body = new OIMO.Body({
  29656. name: initialMesh.uniqueId,
  29657. type: types,
  29658. size: sizes,
  29659. pos: positions,
  29660. rot: rotations,
  29661. move: options.mass != 0,
  29662. config: [options.mass, options.friction, options.restitution],
  29663. world: this._world
  29664. });
  29665. //Reset the body's rotation to be of the initial mesh's.
  29666. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29667. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29668. this._registeredMeshes.push({
  29669. mesh: initialMesh,
  29670. body: body
  29671. });
  29672. return body;
  29673. };
  29674. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29675. var mesh = part.mesh;
  29676. if (!mesh.rotationQuaternion) {
  29677. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29678. }
  29679. // We need the bounding box/sphere info to compute the physics body
  29680. mesh.computeWorldMatrix(true);
  29681. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29682. var bodyParameters = {
  29683. name: mesh.uniqueId,
  29684. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29685. //A bug in Oimo (Body class) prevents us from using rot directly.
  29686. rot: [0, 0, 0],
  29687. //For future reference, if the bug will ever be fixed.
  29688. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29689. };
  29690. var oldQuaternion = mesh.rotationQuaternion;
  29691. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29692. mesh.computeWorldMatrix(true);
  29693. switch (part.impostor) {
  29694. case BABYLON.PhysicsEngine.SphereImpostor:
  29695. var bbox = mesh.getBoundingInfo().boundingBox;
  29696. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29697. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29698. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29699. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29700. bodyParameters.type = 'sphere';
  29701. bodyParameters.size = [size, size, size];
  29702. break;
  29703. case BABYLON.PhysicsEngine.PlaneImpostor:
  29704. case BABYLON.PhysicsEngine.CylinderImpostor:
  29705. case BABYLON.PhysicsEngine.BoxImpostor:
  29706. bbox = mesh.getBoundingInfo().boundingBox;
  29707. var min = bbox.minimumWorld;
  29708. var max = bbox.maximumWorld;
  29709. var box = max.subtract(min);
  29710. var sizeX = this._checkWithEpsilon(box.x);
  29711. var sizeY = this._checkWithEpsilon(box.y);
  29712. var sizeZ = this._checkWithEpsilon(box.z);
  29713. bodyParameters.type = 'box';
  29714. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29715. break;
  29716. }
  29717. mesh.rotationQuaternion = oldQuaternion;
  29718. return bodyParameters;
  29719. };
  29720. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29721. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29722. var registeredMesh = this._registeredMeshes[index];
  29723. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29724. if (registeredMesh.body) {
  29725. this._world.removeRigidBody(registeredMesh.body.body);
  29726. this._unbindBody(registeredMesh.body);
  29727. }
  29728. this._registeredMeshes.splice(index, 1);
  29729. return;
  29730. }
  29731. }
  29732. };
  29733. OimoJSPlugin.prototype._unbindBody = function (body) {
  29734. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29735. var registeredMesh = this._registeredMeshes[index];
  29736. if (registeredMesh.body === body) {
  29737. registeredMesh.body = null;
  29738. }
  29739. }
  29740. };
  29741. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29742. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29743. var registeredMesh = this._registeredMeshes[index];
  29744. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29745. // Get object mass to have a behaviour similar to cannon.js
  29746. var mass = registeredMesh.body.body.massInfo.mass;
  29747. // The force is scaled with the mass of object
  29748. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29749. return;
  29750. }
  29751. }
  29752. };
  29753. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29754. var body1 = null, body2 = null;
  29755. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29756. var registeredMesh = this._registeredMeshes[index];
  29757. if (registeredMesh.mesh === mesh1) {
  29758. body1 = registeredMesh.body.body;
  29759. }
  29760. else if (registeredMesh.mesh === mesh2) {
  29761. body2 = registeredMesh.body.body;
  29762. }
  29763. }
  29764. if (!body1 || !body2) {
  29765. return false;
  29766. }
  29767. if (!options) {
  29768. options = {};
  29769. }
  29770. new OIMO.Link({
  29771. type: options.type,
  29772. body1: body1,
  29773. body2: body2,
  29774. min: options.min,
  29775. max: options.max,
  29776. axe1: options.axe1,
  29777. axe2: options.axe2,
  29778. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29779. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29780. collision: options.collision,
  29781. spring: options.spring,
  29782. world: this._world
  29783. });
  29784. return true;
  29785. };
  29786. OimoJSPlugin.prototype.dispose = function () {
  29787. this._world.clear();
  29788. while (this._registeredMeshes.length) {
  29789. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29790. }
  29791. };
  29792. OimoJSPlugin.prototype.isSupported = function () {
  29793. return OIMO !== undefined;
  29794. };
  29795. OimoJSPlugin.prototype.getWorldObject = function () {
  29796. return this._world;
  29797. };
  29798. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29799. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29800. var registeredMesh = this._registeredMeshes[index];
  29801. if (registeredMesh.mesh === mesh) {
  29802. return registeredMesh.body;
  29803. }
  29804. }
  29805. return null;
  29806. };
  29807. OimoJSPlugin.prototype._getLastShape = function (body) {
  29808. var lastShape = body.shapes;
  29809. while (lastShape.next) {
  29810. lastShape = lastShape.next;
  29811. }
  29812. return lastShape;
  29813. };
  29814. OimoJSPlugin.prototype.runOneStep = function (time) {
  29815. this._world.step();
  29816. // Update the position of all registered meshes
  29817. var i = this._registeredMeshes.length;
  29818. var m;
  29819. while (i--) {
  29820. var body = this._registeredMeshes[i].body.body;
  29821. var mesh = this._registeredMeshes[i].mesh;
  29822. if (!this._registeredMeshes[i].delta) {
  29823. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29824. }
  29825. if (!body.sleeping) {
  29826. //TODO check that
  29827. if (body.shapes.next) {
  29828. var parentShape = this._getLastShape(body);
  29829. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29830. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29831. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29832. }
  29833. else {
  29834. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29835. }
  29836. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29837. mesh.computeWorldMatrix();
  29838. }
  29839. //check if the collide callback is set.
  29840. if (mesh.onPhysicsCollide) {
  29841. var meshUniqueName = mesh.uniqueId;
  29842. var contact = this._world.contacts;
  29843. while (contact !== null) {
  29844. //is this body colliding with any other?
  29845. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29846. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29847. //get the mesh and execute the callback
  29848. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29849. if (otherMesh)
  29850. mesh.onPhysicsCollide(otherMesh, contact);
  29851. }
  29852. contact = contact.next;
  29853. }
  29854. }
  29855. }
  29856. };
  29857. return OimoJSPlugin;
  29858. })();
  29859. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29860. })(BABYLON || (BABYLON = {}));
  29861. var BABYLON;
  29862. (function (BABYLON) {
  29863. var DisplayPassPostProcess = (function (_super) {
  29864. __extends(DisplayPassPostProcess, _super);
  29865. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29866. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29867. }
  29868. return DisplayPassPostProcess;
  29869. })(BABYLON.PostProcess);
  29870. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29871. })(BABYLON || (BABYLON = {}));
  29872. var BABYLON;
  29873. (function (BABYLON) {
  29874. var SimplificationSettings = (function () {
  29875. function SimplificationSettings(quality, distance, optimizeMesh) {
  29876. this.quality = quality;
  29877. this.distance = distance;
  29878. this.optimizeMesh = optimizeMesh;
  29879. }
  29880. return SimplificationSettings;
  29881. })();
  29882. BABYLON.SimplificationSettings = SimplificationSettings;
  29883. var SimplificationQueue = (function () {
  29884. function SimplificationQueue() {
  29885. this.running = false;
  29886. this._simplificationArray = [];
  29887. }
  29888. SimplificationQueue.prototype.addTask = function (task) {
  29889. this._simplificationArray.push(task);
  29890. };
  29891. SimplificationQueue.prototype.executeNext = function () {
  29892. var task = this._simplificationArray.pop();
  29893. if (task) {
  29894. this.running = true;
  29895. this.runSimplification(task);
  29896. }
  29897. else {
  29898. this.running = false;
  29899. }
  29900. };
  29901. SimplificationQueue.prototype.runSimplification = function (task) {
  29902. var _this = this;
  29903. if (task.parallelProcessing) {
  29904. //parallel simplifier
  29905. task.settings.forEach(function (setting) {
  29906. var simplifier = _this.getSimplifier(task);
  29907. simplifier.simplify(setting, function (newMesh) {
  29908. task.mesh.addLODLevel(setting.distance, newMesh);
  29909. newMesh.isVisible = true;
  29910. //check if it is the last
  29911. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29912. //all done, run the success callback.
  29913. task.successCallback();
  29914. }
  29915. _this.executeNext();
  29916. });
  29917. });
  29918. }
  29919. else {
  29920. //single simplifier.
  29921. var simplifier = this.getSimplifier(task);
  29922. var runDecimation = function (setting, callback) {
  29923. simplifier.simplify(setting, function (newMesh) {
  29924. task.mesh.addLODLevel(setting.distance, newMesh);
  29925. newMesh.isVisible = true;
  29926. //run the next quality level
  29927. callback();
  29928. });
  29929. };
  29930. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29931. runDecimation(task.settings[loop.index], function () {
  29932. loop.executeNext();
  29933. });
  29934. }, function () {
  29935. //execution ended, run the success callback.
  29936. if (task.successCallback) {
  29937. task.successCallback();
  29938. }
  29939. _this.executeNext();
  29940. });
  29941. }
  29942. };
  29943. SimplificationQueue.prototype.getSimplifier = function (task) {
  29944. switch (task.simplificationType) {
  29945. case SimplificationType.QUADRATIC:
  29946. default:
  29947. return new QuadraticErrorSimplification(task.mesh);
  29948. }
  29949. };
  29950. return SimplificationQueue;
  29951. })();
  29952. BABYLON.SimplificationQueue = SimplificationQueue;
  29953. /**
  29954. * The implemented types of simplification.
  29955. * At the moment only Quadratic Error Decimation is implemented.
  29956. */
  29957. (function (SimplificationType) {
  29958. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29959. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29960. var SimplificationType = BABYLON.SimplificationType;
  29961. var DecimationTriangle = (function () {
  29962. function DecimationTriangle(vertices) {
  29963. this.vertices = vertices;
  29964. this.error = new Array(4);
  29965. this.deleted = false;
  29966. this.isDirty = false;
  29967. this.deletePending = false;
  29968. this.borderFactor = 0;
  29969. }
  29970. return DecimationTriangle;
  29971. })();
  29972. BABYLON.DecimationTriangle = DecimationTriangle;
  29973. var DecimationVertex = (function () {
  29974. function DecimationVertex(position, id) {
  29975. this.position = position;
  29976. this.id = id;
  29977. this.isBorder = true;
  29978. this.q = new QuadraticMatrix();
  29979. this.triangleCount = 0;
  29980. this.triangleStart = 0;
  29981. this.originalOffsets = [];
  29982. }
  29983. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29984. this.position.copyFrom(newPosition);
  29985. };
  29986. return DecimationVertex;
  29987. })();
  29988. BABYLON.DecimationVertex = DecimationVertex;
  29989. var QuadraticMatrix = (function () {
  29990. function QuadraticMatrix(data) {
  29991. this.data = new Array(10);
  29992. for (var i = 0; i < 10; ++i) {
  29993. if (data && data[i]) {
  29994. this.data[i] = data[i];
  29995. }
  29996. else {
  29997. this.data[i] = 0;
  29998. }
  29999. }
  30000. }
  30001. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30002. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30003. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30004. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30005. return det;
  30006. };
  30007. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30008. for (var i = 0; i < 10; ++i) {
  30009. this.data[i] += matrix.data[i];
  30010. }
  30011. };
  30012. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30013. for (var i = 0; i < 10; ++i) {
  30014. this.data[i] += data[i];
  30015. }
  30016. };
  30017. QuadraticMatrix.prototype.add = function (matrix) {
  30018. var m = new QuadraticMatrix();
  30019. for (var i = 0; i < 10; ++i) {
  30020. m.data[i] = this.data[i] + matrix.data[i];
  30021. }
  30022. return m;
  30023. };
  30024. QuadraticMatrix.FromData = function (a, b, c, d) {
  30025. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30026. };
  30027. //returning an array to avoid garbage collection
  30028. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30029. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30030. };
  30031. return QuadraticMatrix;
  30032. })();
  30033. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30034. var Reference = (function () {
  30035. function Reference(vertexId, triangleId) {
  30036. this.vertexId = vertexId;
  30037. this.triangleId = triangleId;
  30038. }
  30039. return Reference;
  30040. })();
  30041. BABYLON.Reference = Reference;
  30042. /**
  30043. * An implementation of the Quadratic Error simplification algorithm.
  30044. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30045. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30046. * @author RaananW
  30047. */
  30048. var QuadraticErrorSimplification = (function () {
  30049. function QuadraticErrorSimplification(_mesh) {
  30050. this._mesh = _mesh;
  30051. this.initialized = false;
  30052. this.syncIterations = 5000;
  30053. this.aggressiveness = 7;
  30054. this.decimationIterations = 100;
  30055. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30056. }
  30057. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30058. var _this = this;
  30059. this.initDecimatedMesh();
  30060. //iterating through the submeshes array, one after the other.
  30061. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30062. _this.initWithMesh(loop.index, function () {
  30063. _this.runDecimation(settings, loop.index, function () {
  30064. loop.executeNext();
  30065. });
  30066. }, settings.optimizeMesh);
  30067. }, function () {
  30068. setTimeout(function () {
  30069. successCallback(_this._reconstructedMesh);
  30070. }, 0);
  30071. });
  30072. };
  30073. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30074. var _this = this;
  30075. var gCount = 0;
  30076. triangle.vertices.forEach(function (vertex) {
  30077. var count = 0;
  30078. var vPos = vertex.position;
  30079. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30080. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30081. ++count;
  30082. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30083. ++count;
  30084. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30085. ++count;
  30086. if (count > 1) {
  30087. ++gCount;
  30088. }
  30089. ;
  30090. });
  30091. if (gCount > 1) {
  30092. console.log(triangle, gCount);
  30093. }
  30094. return gCount > 1;
  30095. };
  30096. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30097. var _this = this;
  30098. var targetCount = ~~(this.triangles.length * settings.quality);
  30099. var deletedTriangles = 0;
  30100. var triangleCount = this.triangles.length;
  30101. var iterationFunction = function (iteration, callback) {
  30102. setTimeout(function () {
  30103. if (iteration % 5 === 0) {
  30104. _this.updateMesh(iteration === 0);
  30105. }
  30106. for (var i = 0; i < _this.triangles.length; ++i) {
  30107. _this.triangles[i].isDirty = false;
  30108. }
  30109. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30110. var trianglesIterator = function (i) {
  30111. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30112. var t = _this.triangles[tIdx];
  30113. if (!t)
  30114. return;
  30115. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30116. return;
  30117. }
  30118. for (var j = 0; j < 3; ++j) {
  30119. if (t.error[j] < threshold) {
  30120. var deleted0 = [];
  30121. var deleted1 = [];
  30122. var v0 = t.vertices[j];
  30123. var v1 = t.vertices[(j + 1) % 3];
  30124. if (v0.isBorder !== v1.isBorder)
  30125. continue;
  30126. var p = BABYLON.Vector3.Zero();
  30127. var n = BABYLON.Vector3.Zero();
  30128. var uv = BABYLON.Vector2.Zero();
  30129. var color = new BABYLON.Color4(0, 0, 0, 1);
  30130. _this.calculateError(v0, v1, p, n, uv, color);
  30131. var delTr = [];
  30132. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30133. continue;
  30134. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30135. continue;
  30136. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30137. continue;
  30138. var uniqueArray = [];
  30139. delTr.forEach(function (deletedT) {
  30140. if (uniqueArray.indexOf(deletedT) === -1) {
  30141. deletedT.deletePending = true;
  30142. uniqueArray.push(deletedT);
  30143. }
  30144. });
  30145. if (uniqueArray.length % 2 !== 0) {
  30146. continue;
  30147. }
  30148. v0.q = v1.q.add(v0.q);
  30149. v0.updatePosition(p);
  30150. var tStart = _this.references.length;
  30151. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30152. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30153. var tCount = _this.references.length - tStart;
  30154. if (tCount <= v0.triangleCount) {
  30155. if (tCount) {
  30156. for (var c = 0; c < tCount; c++) {
  30157. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30158. }
  30159. }
  30160. }
  30161. else {
  30162. v0.triangleStart = tStart;
  30163. }
  30164. v0.triangleCount = tCount;
  30165. break;
  30166. }
  30167. }
  30168. };
  30169. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30170. }, 0);
  30171. };
  30172. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30173. if (triangleCount - deletedTriangles <= targetCount)
  30174. loop.breakLoop();
  30175. else {
  30176. iterationFunction(loop.index, function () {
  30177. loop.executeNext();
  30178. });
  30179. }
  30180. }, function () {
  30181. setTimeout(function () {
  30182. //reconstruct this part of the mesh
  30183. _this.reconstructMesh(submeshIndex);
  30184. successCallback();
  30185. }, 0);
  30186. });
  30187. };
  30188. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30189. var _this = this;
  30190. this.vertices = [];
  30191. this.triangles = [];
  30192. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30193. var indices = this._mesh.getIndices();
  30194. var submesh = this._mesh.subMeshes[submeshIndex];
  30195. var findInVertices = function (positionToSearch) {
  30196. if (optimizeMesh) {
  30197. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30198. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30199. return _this.vertices[ii];
  30200. }
  30201. }
  30202. }
  30203. return null;
  30204. };
  30205. var vertexReferences = [];
  30206. var vertexInit = function (i) {
  30207. var offset = i + submesh.verticesStart;
  30208. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30209. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30210. vertex.originalOffsets.push(offset);
  30211. if (vertex.id === _this.vertices.length) {
  30212. _this.vertices.push(vertex);
  30213. }
  30214. vertexReferences.push(vertex.id);
  30215. };
  30216. //var totalVertices = mesh.getTotalVertices();
  30217. var totalVertices = submesh.verticesCount;
  30218. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30219. var indicesInit = function (i) {
  30220. var offset = (submesh.indexStart / 3) + i;
  30221. var pos = (offset * 3);
  30222. var i0 = indices[pos + 0];
  30223. var i1 = indices[pos + 1];
  30224. var i2 = indices[pos + 2];
  30225. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30226. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30227. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30228. var triangle = new DecimationTriangle([v0, v1, v2]);
  30229. triangle.originalOffset = pos;
  30230. _this.triangles.push(triangle);
  30231. };
  30232. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30233. _this.init(callback);
  30234. });
  30235. });
  30236. };
  30237. QuadraticErrorSimplification.prototype.init = function (callback) {
  30238. var _this = this;
  30239. var triangleInit1 = function (i) {
  30240. var t = _this.triangles[i];
  30241. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30242. for (var j = 0; j < 3; j++) {
  30243. 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))));
  30244. }
  30245. };
  30246. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30247. var triangleInit2 = function (i) {
  30248. var t = _this.triangles[i];
  30249. for (var j = 0; j < 3; ++j) {
  30250. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30251. }
  30252. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30253. };
  30254. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30255. _this.initialized = true;
  30256. callback();
  30257. });
  30258. });
  30259. };
  30260. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30261. var newTriangles = [];
  30262. var i;
  30263. for (i = 0; i < this.vertices.length; ++i) {
  30264. this.vertices[i].triangleCount = 0;
  30265. }
  30266. var t;
  30267. var j;
  30268. for (i = 0; i < this.triangles.length; ++i) {
  30269. if (!this.triangles[i].deleted) {
  30270. t = this.triangles[i];
  30271. for (j = 0; j < 3; ++j) {
  30272. t.vertices[j].triangleCount = 1;
  30273. }
  30274. newTriangles.push(t);
  30275. }
  30276. }
  30277. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30278. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30279. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30280. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30281. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30282. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30283. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30284. var vertexCount = 0;
  30285. for (i = 0; i < this.vertices.length; ++i) {
  30286. var vertex = this.vertices[i];
  30287. vertex.id = vertexCount;
  30288. if (vertex.triangleCount) {
  30289. vertex.originalOffsets.forEach(function (originalOffset) {
  30290. newPositionData.push(vertex.position.x);
  30291. newPositionData.push(vertex.position.y);
  30292. newPositionData.push(vertex.position.z);
  30293. newNormalData.push(normalData[originalOffset * 3]);
  30294. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30295. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30296. if (uvs && uvs.length) {
  30297. newUVsData.push(uvs[(originalOffset * 2)]);
  30298. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30299. }
  30300. else if (colorsData && colorsData.length) {
  30301. newColorsData.push(colorsData[(originalOffset * 4)]);
  30302. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30303. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30304. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30305. }
  30306. ++vertexCount;
  30307. });
  30308. }
  30309. }
  30310. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30311. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30312. var submeshesArray = this._reconstructedMesh.subMeshes;
  30313. this._reconstructedMesh.subMeshes = [];
  30314. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30315. var originalIndices = this._mesh.getIndices();
  30316. for (i = 0; i < newTriangles.length; ++i) {
  30317. t = newTriangles[i]; //now get the new referencing point for each vertex
  30318. [0, 1, 2].forEach(function (idx) {
  30319. var id = originalIndices[t.originalOffset + idx];
  30320. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30321. if (offset < 0)
  30322. offset = 0;
  30323. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30324. });
  30325. }
  30326. //overwriting the old vertex buffers and indices.
  30327. this._reconstructedMesh.setIndices(newIndicesArray);
  30328. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30329. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30330. if (newUVsData.length > 0)
  30331. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30332. if (newColorsData.length > 0)
  30333. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30334. //create submesh
  30335. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30336. if (submeshIndex > 0) {
  30337. this._reconstructedMesh.subMeshes = [];
  30338. submeshesArray.forEach(function (submesh) {
  30339. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30340. });
  30341. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30342. }
  30343. };
  30344. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30345. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30346. this._reconstructedMesh.material = this._mesh.material;
  30347. this._reconstructedMesh.parent = this._mesh.parent;
  30348. this._reconstructedMesh.isVisible = false;
  30349. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  30350. };
  30351. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30352. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30353. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30354. if (t.deleted)
  30355. continue;
  30356. var s = this.references[vertex1.triangleStart + i].vertexId;
  30357. var v1 = t.vertices[(s + 1) % 3];
  30358. var v2 = t.vertices[(s + 2) % 3];
  30359. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30360. deletedArray[i] = true;
  30361. delTr.push(t);
  30362. continue;
  30363. }
  30364. var d1 = v1.position.subtract(point);
  30365. d1 = d1.normalize();
  30366. var d2 = v2.position.subtract(point);
  30367. d2 = d2.normalize();
  30368. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30369. return true;
  30370. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30371. deletedArray[i] = false;
  30372. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30373. return true;
  30374. }
  30375. return false;
  30376. };
  30377. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30378. var newDeleted = deletedTriangles;
  30379. for (var i = 0; i < vertex.triangleCount; ++i) {
  30380. var ref = this.references[vertex.triangleStart + i];
  30381. var t = this.triangles[ref.triangleId];
  30382. if (t.deleted)
  30383. continue;
  30384. if (deletedArray[i] && t.deletePending) {
  30385. t.deleted = true;
  30386. newDeleted++;
  30387. continue;
  30388. }
  30389. t.vertices[ref.vertexId] = origVertex;
  30390. t.isDirty = true;
  30391. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30392. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30393. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30394. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30395. this.references.push(ref);
  30396. }
  30397. return newDeleted;
  30398. };
  30399. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30400. for (var i = 0; i < this.vertices.length; ++i) {
  30401. var vCount = [];
  30402. var vId = [];
  30403. var v = this.vertices[i];
  30404. var j;
  30405. for (j = 0; j < v.triangleCount; ++j) {
  30406. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30407. for (var ii = 0; ii < 3; ii++) {
  30408. var ofs = 0;
  30409. var vv = triangle.vertices[ii];
  30410. while (ofs < vCount.length) {
  30411. if (vId[ofs] === vv.id)
  30412. break;
  30413. ++ofs;
  30414. }
  30415. if (ofs === vCount.length) {
  30416. vCount.push(1);
  30417. vId.push(vv.id);
  30418. }
  30419. else {
  30420. vCount[ofs]++;
  30421. }
  30422. }
  30423. }
  30424. for (j = 0; j < vCount.length; ++j) {
  30425. if (vCount[j] === 1) {
  30426. this.vertices[vId[j]].isBorder = true;
  30427. }
  30428. else {
  30429. this.vertices[vId[j]].isBorder = false;
  30430. }
  30431. }
  30432. }
  30433. };
  30434. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30435. if (identifyBorders === void 0) { identifyBorders = false; }
  30436. var i;
  30437. if (!identifyBorders) {
  30438. var newTrianglesVector = [];
  30439. for (i = 0; i < this.triangles.length; ++i) {
  30440. if (!this.triangles[i].deleted) {
  30441. newTrianglesVector.push(this.triangles[i]);
  30442. }
  30443. }
  30444. this.triangles = newTrianglesVector;
  30445. }
  30446. for (i = 0; i < this.vertices.length; ++i) {
  30447. this.vertices[i].triangleCount = 0;
  30448. this.vertices[i].triangleStart = 0;
  30449. }
  30450. var t;
  30451. var j;
  30452. var v;
  30453. for (i = 0; i < this.triangles.length; ++i) {
  30454. t = this.triangles[i];
  30455. for (j = 0; j < 3; ++j) {
  30456. v = t.vertices[j];
  30457. v.triangleCount++;
  30458. }
  30459. }
  30460. var tStart = 0;
  30461. for (i = 0; i < this.vertices.length; ++i) {
  30462. this.vertices[i].triangleStart = tStart;
  30463. tStart += this.vertices[i].triangleCount;
  30464. this.vertices[i].triangleCount = 0;
  30465. }
  30466. var newReferences = new Array(this.triangles.length * 3);
  30467. for (i = 0; i < this.triangles.length; ++i) {
  30468. t = this.triangles[i];
  30469. for (j = 0; j < 3; ++j) {
  30470. v = t.vertices[j];
  30471. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30472. v.triangleCount++;
  30473. }
  30474. }
  30475. this.references = newReferences;
  30476. if (identifyBorders) {
  30477. this.identifyBorder();
  30478. }
  30479. };
  30480. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30481. var x = point.x;
  30482. var y = point.y;
  30483. var z = point.z;
  30484. 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
  30485. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30486. };
  30487. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30488. var q = vertex1.q.add(vertex2.q);
  30489. var border = vertex1.isBorder && vertex2.isBorder;
  30490. var error = 0;
  30491. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30492. if (qDet !== 0 && !border) {
  30493. if (!pointResult) {
  30494. pointResult = BABYLON.Vector3.Zero();
  30495. }
  30496. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30497. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30498. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30499. error = this.vertexError(q, pointResult);
  30500. }
  30501. else {
  30502. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30503. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30504. var error1 = this.vertexError(q, vertex1.position);
  30505. var error2 = this.vertexError(q, vertex2.position);
  30506. var error3 = this.vertexError(q, p3);
  30507. error = Math.min(error1, error2, error3);
  30508. if (error === error1) {
  30509. if (pointResult) {
  30510. pointResult.copyFrom(vertex1.position);
  30511. }
  30512. }
  30513. else if (error === error2) {
  30514. if (pointResult) {
  30515. pointResult.copyFrom(vertex2.position);
  30516. }
  30517. }
  30518. else {
  30519. if (pointResult) {
  30520. pointResult.copyFrom(p3);
  30521. }
  30522. }
  30523. }
  30524. return error;
  30525. };
  30526. return QuadraticErrorSimplification;
  30527. })();
  30528. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30529. })(BABYLON || (BABYLON = {}));
  30530. var BABYLON;
  30531. (function (BABYLON) {
  30532. var serializedGeometries = [];
  30533. var serializeGeometry = function (geometry, serializationGeometries) {
  30534. if (serializedGeometries[geometry.id]) {
  30535. return;
  30536. }
  30537. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  30538. serializationGeometries.boxes.push(geometry.serialize());
  30539. }
  30540. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  30541. serializationGeometries.spheres.push(geometry.serialize());
  30542. }
  30543. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30544. serializationGeometries.cylinders.push(geometry.serialize());
  30545. }
  30546. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30547. serializationGeometries.toruses.push(geometry.serialize());
  30548. }
  30549. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30550. serializationGeometries.grounds.push(geometry.serialize());
  30551. }
  30552. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30553. serializationGeometries.planes.push(geometry.serialize());
  30554. }
  30555. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30556. serializationGeometries.torusKnots.push(geometry.serialize());
  30557. }
  30558. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30559. throw new Error("Unknown primitive type");
  30560. }
  30561. else {
  30562. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30563. }
  30564. serializedGeometries[geometry.id] = true;
  30565. };
  30566. var serializeMesh = function (mesh, serializationScene) {
  30567. var serializationObject = {};
  30568. serializationObject.name = mesh.name;
  30569. serializationObject.id = mesh.id;
  30570. if (BABYLON.Tags.HasTags(mesh)) {
  30571. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30572. }
  30573. serializationObject.position = mesh.position.asArray();
  30574. if (mesh.rotationQuaternion) {
  30575. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30576. }
  30577. else if (mesh.rotation) {
  30578. serializationObject.rotation = mesh.rotation.asArray();
  30579. }
  30580. serializationObject.scaling = mesh.scaling.asArray();
  30581. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30582. serializationObject.isEnabled = mesh.isEnabled();
  30583. serializationObject.isVisible = mesh.isVisible;
  30584. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30585. serializationObject.pickable = mesh.isPickable;
  30586. serializationObject.receiveShadows = mesh.receiveShadows;
  30587. serializationObject.billboardMode = mesh.billboardMode;
  30588. serializationObject.visibility = mesh.visibility;
  30589. serializationObject.checkCollisions = mesh.checkCollisions;
  30590. // Parent
  30591. if (mesh.parent) {
  30592. serializationObject.parentId = mesh.parent.id;
  30593. }
  30594. // Geometry
  30595. var geometry = mesh._geometry;
  30596. if (geometry) {
  30597. var geometryId = geometry.id;
  30598. serializationObject.geometryId = geometryId;
  30599. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30600. // 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
  30601. serializeGeometry(geometry, serializationScene.geometries);
  30602. }
  30603. // SubMeshes
  30604. serializationObject.subMeshes = [];
  30605. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30606. var subMesh = mesh.subMeshes[subIndex];
  30607. serializationObject.subMeshes.push({
  30608. materialIndex: subMesh.materialIndex,
  30609. verticesStart: subMesh.verticesStart,
  30610. verticesCount: subMesh.verticesCount,
  30611. indexStart: subMesh.indexStart,
  30612. indexCount: subMesh.indexCount
  30613. });
  30614. }
  30615. }
  30616. // Material
  30617. if (mesh.material) {
  30618. serializationObject.materialId = mesh.material.id;
  30619. }
  30620. else {
  30621. mesh.material = null;
  30622. }
  30623. // Skeleton
  30624. if (mesh.skeleton) {
  30625. serializationObject.skeletonId = mesh.skeleton.id;
  30626. }
  30627. // Physics
  30628. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30629. serializationObject.physicsMass = mesh.getPhysicsMass();
  30630. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30631. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30632. switch (mesh.getPhysicsImpostor()) {
  30633. case BABYLON.PhysicsEngine.BoxImpostor:
  30634. serializationObject.physicsImpostor = 1;
  30635. break;
  30636. case BABYLON.PhysicsEngine.SphereImpostor:
  30637. serializationObject.physicsImpostor = 2;
  30638. break;
  30639. }
  30640. }
  30641. // Instances
  30642. serializationObject.instances = [];
  30643. for (var index = 0; index < mesh.instances.length; index++) {
  30644. var instance = mesh.instances[index];
  30645. var serializationInstance = {
  30646. name: instance.name,
  30647. position: instance.position.asArray(),
  30648. scaling: instance.scaling.asArray()
  30649. };
  30650. if (instance.rotationQuaternion) {
  30651. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30652. }
  30653. else if (instance.rotation) {
  30654. serializationInstance.rotation = instance.rotation.asArray();
  30655. }
  30656. serializationObject.instances.push(serializationInstance);
  30657. // Animations
  30658. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30659. serializationInstance.ranges = instance.serializeAnimationRanges();
  30660. }
  30661. // Animations
  30662. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30663. serializationObject.ranges = mesh.serializeAnimationRanges();
  30664. // Layer mask
  30665. serializationObject.layerMask = mesh.layerMask;
  30666. return serializationObject;
  30667. };
  30668. var finalizeSingleMesh = function (mesh, serializationObject) {
  30669. //only works if the mesh is already loaded
  30670. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30671. //serialize material
  30672. if (mesh.material) {
  30673. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30674. serializationObject.materials = serializationObject.materials || [];
  30675. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30676. serializationObject.materials.push(mesh.material.serialize());
  30677. }
  30678. }
  30679. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30680. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30681. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30682. serializationObject.multiMaterials.push(mesh.material.serialize());
  30683. }
  30684. }
  30685. }
  30686. //serialize geometry
  30687. var geometry = mesh._geometry;
  30688. if (geometry) {
  30689. if (!serializationObject.geometries) {
  30690. serializationObject.geometries = {};
  30691. serializationObject.geometries.boxes = [];
  30692. serializationObject.geometries.spheres = [];
  30693. serializationObject.geometries.cylinders = [];
  30694. serializationObject.geometries.toruses = [];
  30695. serializationObject.geometries.grounds = [];
  30696. serializationObject.geometries.planes = [];
  30697. serializationObject.geometries.torusKnots = [];
  30698. serializationObject.geometries.vertexData = [];
  30699. }
  30700. serializeGeometry(geometry, serializationObject.geometries);
  30701. }
  30702. // Skeletons
  30703. if (mesh.skeleton) {
  30704. serializationObject.skeletons = serializationObject.skeletons || [];
  30705. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30706. }
  30707. //serialize the actual mesh
  30708. serializationObject.meshes = serializationObject.meshes || [];
  30709. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30710. }
  30711. };
  30712. var SceneSerializer = (function () {
  30713. function SceneSerializer() {
  30714. }
  30715. SceneSerializer.Serialize = function (scene) {
  30716. var serializationObject = {};
  30717. // Scene
  30718. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30719. serializationObject.autoClear = scene.autoClear;
  30720. serializationObject.clearColor = scene.clearColor.asArray();
  30721. serializationObject.ambientColor = scene.ambientColor.asArray();
  30722. serializationObject.gravity = scene.gravity.asArray();
  30723. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30724. serializationObject.workerCollisions = scene.workerCollisions;
  30725. // Fog
  30726. if (scene.fogMode && scene.fogMode !== 0) {
  30727. serializationObject.fogMode = scene.fogMode;
  30728. serializationObject.fogColor = scene.fogColor.asArray();
  30729. serializationObject.fogStart = scene.fogStart;
  30730. serializationObject.fogEnd = scene.fogEnd;
  30731. serializationObject.fogDensity = scene.fogDensity;
  30732. }
  30733. //Physics
  30734. if (scene.isPhysicsEnabled()) {
  30735. serializationObject.physicsEnabled = true;
  30736. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30737. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30738. }
  30739. // Lights
  30740. serializationObject.lights = [];
  30741. var index;
  30742. var light;
  30743. for (index = 0; index < scene.lights.length; index++) {
  30744. light = scene.lights[index];
  30745. serializationObject.lights.push(light.serialize());
  30746. }
  30747. // Cameras
  30748. serializationObject.cameras = [];
  30749. for (index = 0; index < scene.cameras.length; index++) {
  30750. var camera = scene.cameras[index];
  30751. serializationObject.cameras.push(camera.serialize());
  30752. }
  30753. if (scene.activeCamera) {
  30754. serializationObject.activeCameraID = scene.activeCamera.id;
  30755. }
  30756. // Materials
  30757. serializationObject.materials = [];
  30758. serializationObject.multiMaterials = [];
  30759. var material;
  30760. for (index = 0; index < scene.materials.length; index++) {
  30761. material = scene.materials[index];
  30762. serializationObject.materials.push(material.serialize());
  30763. }
  30764. // MultiMaterials
  30765. serializationObject.multiMaterials = [];
  30766. for (index = 0; index < scene.multiMaterials.length; index++) {
  30767. var multiMaterial = scene.multiMaterials[index];
  30768. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30769. }
  30770. // Skeletons
  30771. serializationObject.skeletons = [];
  30772. for (index = 0; index < scene.skeletons.length; index++) {
  30773. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30774. }
  30775. // Geometries
  30776. serializationObject.geometries = {};
  30777. serializationObject.geometries.boxes = [];
  30778. serializationObject.geometries.spheres = [];
  30779. serializationObject.geometries.cylinders = [];
  30780. serializationObject.geometries.toruses = [];
  30781. serializationObject.geometries.grounds = [];
  30782. serializationObject.geometries.planes = [];
  30783. serializationObject.geometries.torusKnots = [];
  30784. serializationObject.geometries.vertexData = [];
  30785. serializedGeometries = [];
  30786. var geometries = scene.getGeometries();
  30787. for (index = 0; index < geometries.length; index++) {
  30788. var geometry = geometries[index];
  30789. if (geometry.isReady()) {
  30790. serializeGeometry(geometry, serializationObject.geometries);
  30791. }
  30792. }
  30793. // Meshes
  30794. serializationObject.meshes = [];
  30795. for (index = 0; index < scene.meshes.length; index++) {
  30796. var abstractMesh = scene.meshes[index];
  30797. if (abstractMesh instanceof BABYLON.Mesh) {
  30798. var mesh = abstractMesh;
  30799. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30800. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30801. }
  30802. }
  30803. }
  30804. // Particles Systems
  30805. serializationObject.particleSystems = [];
  30806. for (index = 0; index < scene.particleSystems.length; index++) {
  30807. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30808. }
  30809. // Lens flares
  30810. serializationObject.lensFlareSystems = [];
  30811. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30812. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30813. }
  30814. // Shadows
  30815. serializationObject.shadowGenerators = [];
  30816. for (index = 0; index < scene.lights.length; index++) {
  30817. light = scene.lights[index];
  30818. if (light.getShadowGenerator()) {
  30819. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30820. }
  30821. }
  30822. return serializationObject;
  30823. };
  30824. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30825. if (withParents === void 0) { withParents = false; }
  30826. if (withChildren === void 0) { withChildren = false; }
  30827. var serializationObject = {};
  30828. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30829. if (withParents || withChildren) {
  30830. //deliberate for loop! not for each, appended should be processed as well.
  30831. for (var i = 0; i < toSerialize.length; ++i) {
  30832. if (withChildren) {
  30833. toSerialize[i].getDescendants().forEach(function (node) {
  30834. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30835. toSerialize.push(node);
  30836. }
  30837. });
  30838. }
  30839. //make sure the array doesn't contain the object already
  30840. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30841. toSerialize.push(toSerialize[i].parent);
  30842. }
  30843. }
  30844. }
  30845. toSerialize.forEach(function (mesh) {
  30846. finalizeSingleMesh(mesh, serializationObject);
  30847. });
  30848. return serializationObject;
  30849. };
  30850. return SceneSerializer;
  30851. })();
  30852. BABYLON.SceneSerializer = SceneSerializer;
  30853. })(BABYLON || (BABYLON = {}));
  30854. var BABYLON;
  30855. (function (BABYLON) {
  30856. // Unique ID when we import meshes from Babylon to CSG
  30857. var currentCSGMeshId = 0;
  30858. // # class Vertex
  30859. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30860. // one to provide additional features like texture coordinates and vertex
  30861. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30862. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30863. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30864. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30865. // is not used anywhere else.
  30866. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30867. var Vertex = (function () {
  30868. function Vertex(pos, normal, uv) {
  30869. this.pos = pos;
  30870. this.normal = normal;
  30871. this.uv = uv;
  30872. }
  30873. Vertex.prototype.clone = function () {
  30874. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30875. };
  30876. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30877. // orientation of a polygon is flipped.
  30878. Vertex.prototype.flip = function () {
  30879. this.normal = this.normal.scale(-1);
  30880. };
  30881. // Create a new vertex between this vertex and `other` by linearly
  30882. // interpolating all properties using a parameter of `t`. Subclasses should
  30883. // override this to interpolate additional properties.
  30884. Vertex.prototype.interpolate = function (other, t) {
  30885. 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));
  30886. };
  30887. return Vertex;
  30888. })();
  30889. // # class Plane
  30890. // Represents a plane in 3D space.
  30891. var Plane = (function () {
  30892. function Plane(normal, w) {
  30893. this.normal = normal;
  30894. this.w = w;
  30895. }
  30896. Plane.FromPoints = function (a, b, c) {
  30897. var v0 = c.subtract(a);
  30898. var v1 = b.subtract(a);
  30899. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30900. return null;
  30901. }
  30902. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30903. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30904. };
  30905. Plane.prototype.clone = function () {
  30906. return new Plane(this.normal.clone(), this.w);
  30907. };
  30908. Plane.prototype.flip = function () {
  30909. this.normal.scaleInPlace(-1);
  30910. this.w = -this.w;
  30911. };
  30912. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30913. // fragments in the appropriate lists. Coplanar polygons go into either
  30914. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30915. // respect to this plane. Polygons in front or in back of this plane go into
  30916. // either `front` or `back`.
  30917. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30918. var COPLANAR = 0;
  30919. var FRONT = 1;
  30920. var BACK = 2;
  30921. var SPANNING = 3;
  30922. // Classify each point as well as the entire polygon into one of the above
  30923. // four classes.
  30924. var polygonType = 0;
  30925. var types = [];
  30926. var i;
  30927. var t;
  30928. for (i = 0; i < polygon.vertices.length; i++) {
  30929. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30930. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30931. polygonType |= type;
  30932. types.push(type);
  30933. }
  30934. // Put the polygon in the correct list, splitting it when necessary.
  30935. switch (polygonType) {
  30936. case COPLANAR:
  30937. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30938. break;
  30939. case FRONT:
  30940. front.push(polygon);
  30941. break;
  30942. case BACK:
  30943. back.push(polygon);
  30944. break;
  30945. case SPANNING:
  30946. var f = [], b = [];
  30947. for (i = 0; i < polygon.vertices.length; i++) {
  30948. var j = (i + 1) % polygon.vertices.length;
  30949. var ti = types[i], tj = types[j];
  30950. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30951. if (ti !== BACK)
  30952. f.push(vi);
  30953. if (ti !== FRONT)
  30954. b.push(ti !== BACK ? vi.clone() : vi);
  30955. if ((ti | tj) === SPANNING) {
  30956. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30957. var v = vi.interpolate(vj, t);
  30958. f.push(v);
  30959. b.push(v.clone());
  30960. }
  30961. }
  30962. var poly;
  30963. if (f.length >= 3) {
  30964. poly = new Polygon(f, polygon.shared);
  30965. if (poly.plane)
  30966. front.push(poly);
  30967. }
  30968. if (b.length >= 3) {
  30969. poly = new Polygon(b, polygon.shared);
  30970. if (poly.plane)
  30971. back.push(poly);
  30972. }
  30973. break;
  30974. }
  30975. };
  30976. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30977. // point is on the plane.
  30978. Plane.EPSILON = 1e-5;
  30979. return Plane;
  30980. })();
  30981. // # class Polygon
  30982. // Represents a convex polygon. The vertices used to initialize a polygon must
  30983. // be coplanar and form a convex loop.
  30984. //
  30985. // Each convex polygon has a `shared` property, which is shared between all
  30986. // polygons that are clones of each other or were split from the same polygon.
  30987. // This can be used to define per-polygon properties (such as surface color).
  30988. var Polygon = (function () {
  30989. function Polygon(vertices, shared) {
  30990. this.vertices = vertices;
  30991. this.shared = shared;
  30992. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30993. }
  30994. Polygon.prototype.clone = function () {
  30995. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30996. return new Polygon(vertices, this.shared);
  30997. };
  30998. Polygon.prototype.flip = function () {
  30999. this.vertices.reverse().map(function (v) { v.flip(); });
  31000. this.plane.flip();
  31001. };
  31002. return Polygon;
  31003. })();
  31004. // # class Node
  31005. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31006. // by picking a polygon to split along. That polygon (and all other coplanar
  31007. // polygons) are added directly to that node and the other polygons are added to
  31008. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31009. // no distinction between internal and leaf nodes.
  31010. var Node = (function () {
  31011. function Node(polygons) {
  31012. this.plane = null;
  31013. this.front = null;
  31014. this.back = null;
  31015. this.polygons = [];
  31016. if (polygons) {
  31017. this.build(polygons);
  31018. }
  31019. }
  31020. Node.prototype.clone = function () {
  31021. var node = new Node();
  31022. node.plane = this.plane && this.plane.clone();
  31023. node.front = this.front && this.front.clone();
  31024. node.back = this.back && this.back.clone();
  31025. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31026. return node;
  31027. };
  31028. // Convert solid space to empty space and empty space to solid space.
  31029. Node.prototype.invert = function () {
  31030. for (var i = 0; i < this.polygons.length; i++) {
  31031. this.polygons[i].flip();
  31032. }
  31033. if (this.plane) {
  31034. this.plane.flip();
  31035. }
  31036. if (this.front) {
  31037. this.front.invert();
  31038. }
  31039. if (this.back) {
  31040. this.back.invert();
  31041. }
  31042. var temp = this.front;
  31043. this.front = this.back;
  31044. this.back = temp;
  31045. };
  31046. // Recursively remove all polygons in `polygons` that are inside this BSP
  31047. // tree.
  31048. Node.prototype.clipPolygons = function (polygons) {
  31049. if (!this.plane)
  31050. return polygons.slice();
  31051. var front = [], back = [];
  31052. for (var i = 0; i < polygons.length; i++) {
  31053. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31054. }
  31055. if (this.front) {
  31056. front = this.front.clipPolygons(front);
  31057. }
  31058. if (this.back) {
  31059. back = this.back.clipPolygons(back);
  31060. }
  31061. else {
  31062. back = [];
  31063. }
  31064. return front.concat(back);
  31065. };
  31066. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31067. // `bsp`.
  31068. Node.prototype.clipTo = function (bsp) {
  31069. this.polygons = bsp.clipPolygons(this.polygons);
  31070. if (this.front)
  31071. this.front.clipTo(bsp);
  31072. if (this.back)
  31073. this.back.clipTo(bsp);
  31074. };
  31075. // Return a list of all polygons in this BSP tree.
  31076. Node.prototype.allPolygons = function () {
  31077. var polygons = this.polygons.slice();
  31078. if (this.front)
  31079. polygons = polygons.concat(this.front.allPolygons());
  31080. if (this.back)
  31081. polygons = polygons.concat(this.back.allPolygons());
  31082. return polygons;
  31083. };
  31084. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31085. // new polygons are filtered down to the bottom of the tree and become new
  31086. // nodes there. Each set of polygons is partitioned using the first polygon
  31087. // (no heuristic is used to pick a good split).
  31088. Node.prototype.build = function (polygons) {
  31089. if (!polygons.length)
  31090. return;
  31091. if (!this.plane)
  31092. this.plane = polygons[0].plane.clone();
  31093. var front = [], back = [];
  31094. for (var i = 0; i < polygons.length; i++) {
  31095. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31096. }
  31097. if (front.length) {
  31098. if (!this.front)
  31099. this.front = new Node();
  31100. this.front.build(front);
  31101. }
  31102. if (back.length) {
  31103. if (!this.back)
  31104. this.back = new Node();
  31105. this.back.build(back);
  31106. }
  31107. };
  31108. return Node;
  31109. })();
  31110. var CSG = (function () {
  31111. function CSG() {
  31112. this.polygons = new Array();
  31113. }
  31114. // Convert BABYLON.Mesh to BABYLON.CSG
  31115. CSG.FromMesh = function (mesh) {
  31116. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31117. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31118. if (mesh instanceof BABYLON.Mesh) {
  31119. mesh.computeWorldMatrix(true);
  31120. matrix = mesh.getWorldMatrix();
  31121. meshPosition = mesh.position.clone();
  31122. meshRotation = mesh.rotation.clone();
  31123. if (mesh.rotationQuaternion) {
  31124. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31125. }
  31126. meshScaling = mesh.scaling.clone();
  31127. }
  31128. else {
  31129. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31130. }
  31131. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31132. var subMeshes = mesh.subMeshes;
  31133. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31134. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31135. vertices = [];
  31136. for (var j = 0; j < 3; j++) {
  31137. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31138. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31139. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31140. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31141. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31142. vertex = new Vertex(position, normal, uv);
  31143. vertices.push(vertex);
  31144. }
  31145. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31146. // To handle the case of degenerated triangle
  31147. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31148. if (polygon.plane)
  31149. polygons.push(polygon);
  31150. }
  31151. }
  31152. var csg = CSG.FromPolygons(polygons);
  31153. csg.matrix = matrix;
  31154. csg.position = meshPosition;
  31155. csg.rotation = meshRotation;
  31156. csg.scaling = meshScaling;
  31157. csg.rotationQuaternion = meshRotationQuaternion;
  31158. currentCSGMeshId++;
  31159. return csg;
  31160. };
  31161. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31162. CSG.FromPolygons = function (polygons) {
  31163. var csg = new CSG();
  31164. csg.polygons = polygons;
  31165. return csg;
  31166. };
  31167. CSG.prototype.clone = function () {
  31168. var csg = new CSG();
  31169. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31170. csg.copyTransformAttributes(this);
  31171. return csg;
  31172. };
  31173. CSG.prototype.toPolygons = function () {
  31174. return this.polygons;
  31175. };
  31176. CSG.prototype.union = function (csg) {
  31177. var a = new Node(this.clone().polygons);
  31178. var b = new Node(csg.clone().polygons);
  31179. a.clipTo(b);
  31180. b.clipTo(a);
  31181. b.invert();
  31182. b.clipTo(a);
  31183. b.invert();
  31184. a.build(b.allPolygons());
  31185. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31186. };
  31187. CSG.prototype.unionInPlace = function (csg) {
  31188. var a = new Node(this.polygons);
  31189. var b = new Node(csg.polygons);
  31190. a.clipTo(b);
  31191. b.clipTo(a);
  31192. b.invert();
  31193. b.clipTo(a);
  31194. b.invert();
  31195. a.build(b.allPolygons());
  31196. this.polygons = a.allPolygons();
  31197. };
  31198. CSG.prototype.subtract = function (csg) {
  31199. var a = new Node(this.clone().polygons);
  31200. var b = new Node(csg.clone().polygons);
  31201. a.invert();
  31202. a.clipTo(b);
  31203. b.clipTo(a);
  31204. b.invert();
  31205. b.clipTo(a);
  31206. b.invert();
  31207. a.build(b.allPolygons());
  31208. a.invert();
  31209. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31210. };
  31211. CSG.prototype.subtractInPlace = function (csg) {
  31212. var a = new Node(this.polygons);
  31213. var b = new Node(csg.polygons);
  31214. a.invert();
  31215. a.clipTo(b);
  31216. b.clipTo(a);
  31217. b.invert();
  31218. b.clipTo(a);
  31219. b.invert();
  31220. a.build(b.allPolygons());
  31221. a.invert();
  31222. this.polygons = a.allPolygons();
  31223. };
  31224. CSG.prototype.intersect = function (csg) {
  31225. var a = new Node(this.clone().polygons);
  31226. var b = new Node(csg.clone().polygons);
  31227. a.invert();
  31228. b.clipTo(a);
  31229. b.invert();
  31230. a.clipTo(b);
  31231. b.clipTo(a);
  31232. a.build(b.allPolygons());
  31233. a.invert();
  31234. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31235. };
  31236. CSG.prototype.intersectInPlace = function (csg) {
  31237. var a = new Node(this.polygons);
  31238. var b = new Node(csg.polygons);
  31239. a.invert();
  31240. b.clipTo(a);
  31241. b.invert();
  31242. a.clipTo(b);
  31243. b.clipTo(a);
  31244. a.build(b.allPolygons());
  31245. a.invert();
  31246. this.polygons = a.allPolygons();
  31247. };
  31248. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31249. // not modified.
  31250. CSG.prototype.inverse = function () {
  31251. var csg = this.clone();
  31252. csg.inverseInPlace();
  31253. return csg;
  31254. };
  31255. CSG.prototype.inverseInPlace = function () {
  31256. this.polygons.map(function (p) { p.flip(); });
  31257. };
  31258. // This is used to keep meshes transformations so they can be restored
  31259. // when we build back a Babylon Mesh
  31260. // NB : All CSG operations are performed in world coordinates
  31261. CSG.prototype.copyTransformAttributes = function (csg) {
  31262. this.matrix = csg.matrix;
  31263. this.position = csg.position;
  31264. this.rotation = csg.rotation;
  31265. this.scaling = csg.scaling;
  31266. this.rotationQuaternion = csg.rotationQuaternion;
  31267. return this;
  31268. };
  31269. // Build Raw mesh from CSG
  31270. // Coordinates here are in world space
  31271. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31272. var matrix = this.matrix.clone();
  31273. matrix.invert();
  31274. 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;
  31275. if (keepSubMeshes) {
  31276. // Sort Polygons, since subMeshes are indices range
  31277. polygons.sort(function (a, b) {
  31278. if (a.shared.meshId === b.shared.meshId) {
  31279. return a.shared.subMeshId - b.shared.subMeshId;
  31280. }
  31281. else {
  31282. return a.shared.meshId - b.shared.meshId;
  31283. }
  31284. });
  31285. }
  31286. for (var i = 0, il = polygons.length; i < il; i++) {
  31287. polygon = polygons[i];
  31288. // Building SubMeshes
  31289. if (!subMesh_dict[polygon.shared.meshId]) {
  31290. subMesh_dict[polygon.shared.meshId] = {};
  31291. }
  31292. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31293. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31294. indexStart: +Infinity,
  31295. indexEnd: -Infinity,
  31296. materialIndex: polygon.shared.materialIndex
  31297. };
  31298. }
  31299. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31300. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  31301. polygonIndices[0] = 0;
  31302. polygonIndices[1] = j - 1;
  31303. polygonIndices[2] = j;
  31304. for (var k = 0; k < 3; k++) {
  31305. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  31306. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  31307. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  31308. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  31309. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  31310. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  31311. // Check if 2 points can be merged
  31312. if (!(typeof vertex_idx !== 'undefined' &&
  31313. normals[vertex_idx * 3] === localNormal.x &&
  31314. normals[vertex_idx * 3 + 1] === localNormal.y &&
  31315. normals[vertex_idx * 3 + 2] === localNormal.z &&
  31316. uvs[vertex_idx * 2] === uv.x &&
  31317. uvs[vertex_idx * 2 + 1] === uv.y)) {
  31318. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  31319. uvs.push(uv.x, uv.y);
  31320. normals.push(normal.x, normal.y, normal.z);
  31321. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  31322. }
  31323. indices.push(vertex_idx);
  31324. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  31325. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  31326. currentIndex++;
  31327. }
  31328. }
  31329. }
  31330. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  31331. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31332. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  31333. mesh.setIndices(indices);
  31334. if (keepSubMeshes) {
  31335. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  31336. var materialIndexOffset = 0, materialMaxIndex;
  31337. mesh.subMeshes = new Array();
  31338. for (var m in subMesh_dict) {
  31339. materialMaxIndex = -1;
  31340. for (var sm in subMesh_dict[m]) {
  31341. subMesh_obj = subMesh_dict[m][sm];
  31342. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  31343. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  31344. }
  31345. materialIndexOffset += ++materialMaxIndex;
  31346. }
  31347. }
  31348. return mesh;
  31349. };
  31350. // Build Mesh from CSG taking material and transforms into account
  31351. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  31352. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  31353. mesh.material = material;
  31354. mesh.position.copyFrom(this.position);
  31355. mesh.rotation.copyFrom(this.rotation);
  31356. if (this.rotationQuaternion) {
  31357. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  31358. }
  31359. mesh.scaling.copyFrom(this.scaling);
  31360. mesh.computeWorldMatrix(true);
  31361. return mesh;
  31362. };
  31363. return CSG;
  31364. })();
  31365. BABYLON.CSG = CSG;
  31366. })(BABYLON || (BABYLON = {}));
  31367. var BABYLON;
  31368. (function (BABYLON) {
  31369. var VRDistortionCorrectionPostProcess = (function (_super) {
  31370. __extends(VRDistortionCorrectionPostProcess, _super);
  31371. //ANY
  31372. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  31373. var _this = this;
  31374. _super.call(this, name, "vrDistortionCorrection", [
  31375. 'LensCenter',
  31376. 'Scale',
  31377. 'ScaleIn',
  31378. 'HmdWarpParam'
  31379. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  31380. this._isRightEye = isRightEye;
  31381. this._distortionFactors = vrMetrics.distortionK;
  31382. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  31383. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  31384. this.onSizeChanged = function () {
  31385. _this.aspectRatio = _this.width * .5 / _this.height;
  31386. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  31387. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31388. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31389. };
  31390. this.onApply = function (effect) {
  31391. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31392. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31393. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31394. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31395. };
  31396. }
  31397. return VRDistortionCorrectionPostProcess;
  31398. })(BABYLON.PostProcess);
  31399. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31400. })(BABYLON || (BABYLON = {}));
  31401. // Mainly based on these 2 articles :
  31402. // 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
  31403. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31404. var BABYLON;
  31405. (function (BABYLON) {
  31406. (function (JoystickAxis) {
  31407. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31408. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31409. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31410. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31411. var JoystickAxis = BABYLON.JoystickAxis;
  31412. var VirtualJoystick = (function () {
  31413. function VirtualJoystick(leftJoystick) {
  31414. var _this = this;
  31415. if (leftJoystick) {
  31416. this._leftJoystick = true;
  31417. }
  31418. else {
  31419. this._leftJoystick = false;
  31420. }
  31421. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31422. VirtualJoystick._globalJoystickIndex++;
  31423. // By default left & right arrow keys are moving the X
  31424. // and up & down keys are moving the Y
  31425. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31426. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31427. this.reverseLeftRight = false;
  31428. this.reverseUpDown = false;
  31429. // collections of pointers
  31430. this._touches = new BABYLON.SmartCollection();
  31431. this.deltaPosition = BABYLON.Vector3.Zero();
  31432. this._joystickSensibility = 25;
  31433. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31434. this._rotationSpeed = 25;
  31435. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31436. this._rotateOnAxisRelativeToMesh = false;
  31437. this._onResize = function (evt) {
  31438. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31439. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31440. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31441. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31442. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31443. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31444. };
  31445. // injecting a canvas element on top of the canvas 3D game
  31446. if (!VirtualJoystick.vjCanvas) {
  31447. window.addEventListener("resize", this._onResize, false);
  31448. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31449. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31450. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31451. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31452. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31453. VirtualJoystick.vjCanvas.style.width = "100%";
  31454. VirtualJoystick.vjCanvas.style.height = "100%";
  31455. VirtualJoystick.vjCanvas.style.position = "absolute";
  31456. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31457. VirtualJoystick.vjCanvas.style.top = "0px";
  31458. VirtualJoystick.vjCanvas.style.left = "0px";
  31459. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31460. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31461. // Support for jQuery PEP polyfill
  31462. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31463. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31464. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31465. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31466. document.body.appendChild(VirtualJoystick.vjCanvas);
  31467. }
  31468. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31469. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31470. this.pressed = false;
  31471. // default joystick color
  31472. this._joystickColor = "cyan";
  31473. this._joystickPointerID = -1;
  31474. // current joystick position
  31475. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31476. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31477. // origin joystick position
  31478. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31479. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31480. this._onPointerDownHandlerRef = function (evt) {
  31481. _this._onPointerDown(evt);
  31482. };
  31483. this._onPointerMoveHandlerRef = function (evt) {
  31484. _this._onPointerMove(evt);
  31485. };
  31486. this._onPointerOutHandlerRef = function (evt) {
  31487. _this._onPointerUp(evt);
  31488. };
  31489. this._onPointerUpHandlerRef = function (evt) {
  31490. _this._onPointerUp(evt);
  31491. };
  31492. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31493. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31494. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31495. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31496. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31497. evt.preventDefault(); // Disables system menu
  31498. }, false);
  31499. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31500. }
  31501. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31502. this._joystickSensibility = newJoystickSensibility;
  31503. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31504. };
  31505. VirtualJoystick.prototype._onPointerDown = function (e) {
  31506. var positionOnScreenCondition;
  31507. e.preventDefault();
  31508. if (this._leftJoystick === true) {
  31509. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31510. }
  31511. else {
  31512. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31513. }
  31514. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31515. // First contact will be dedicated to the virtual joystick
  31516. this._joystickPointerID = e.pointerId;
  31517. this._joystickPointerStartPos.x = e.clientX;
  31518. this._joystickPointerStartPos.y = e.clientY;
  31519. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31520. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31521. this._deltaJoystickVector.x = 0;
  31522. this._deltaJoystickVector.y = 0;
  31523. this.pressed = true;
  31524. this._touches.add(e.pointerId.toString(), e);
  31525. }
  31526. else {
  31527. // You can only trigger the action buttons with a joystick declared
  31528. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31529. this._action();
  31530. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31531. }
  31532. }
  31533. };
  31534. VirtualJoystick.prototype._onPointerMove = function (e) {
  31535. // If the current pointer is the one associated to the joystick (first touch contact)
  31536. if (this._joystickPointerID == e.pointerId) {
  31537. this._joystickPointerPos.x = e.clientX;
  31538. this._joystickPointerPos.y = e.clientY;
  31539. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31540. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31541. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31542. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31543. switch (this._axisTargetedByLeftAndRight) {
  31544. case JoystickAxis.X:
  31545. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31546. break;
  31547. case JoystickAxis.Y:
  31548. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31549. break;
  31550. case JoystickAxis.Z:
  31551. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31552. break;
  31553. }
  31554. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31555. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31556. switch (this._axisTargetedByUpAndDown) {
  31557. case JoystickAxis.X:
  31558. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31559. break;
  31560. case JoystickAxis.Y:
  31561. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31562. break;
  31563. case JoystickAxis.Z:
  31564. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31565. break;
  31566. }
  31567. }
  31568. else {
  31569. if (this._touches.item(e.pointerId.toString())) {
  31570. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31571. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31572. }
  31573. }
  31574. };
  31575. VirtualJoystick.prototype._onPointerUp = function (e) {
  31576. if (this._joystickPointerID == e.pointerId) {
  31577. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31578. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31579. this._joystickPointerID = -1;
  31580. this.pressed = false;
  31581. }
  31582. else {
  31583. var touch = this._touches.item(e.pointerId.toString());
  31584. if (touch) {
  31585. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31586. }
  31587. }
  31588. this._deltaJoystickVector.x = 0;
  31589. this._deltaJoystickVector.y = 0;
  31590. this._touches.remove(e.pointerId.toString());
  31591. };
  31592. /**
  31593. * Change the color of the virtual joystick
  31594. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31595. */
  31596. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31597. this._joystickColor = newColor;
  31598. };
  31599. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31600. this._action = action;
  31601. };
  31602. // Define which axis you'd like to control for left & right
  31603. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31604. switch (axis) {
  31605. case JoystickAxis.X:
  31606. case JoystickAxis.Y:
  31607. case JoystickAxis.Z:
  31608. this._axisTargetedByLeftAndRight = axis;
  31609. break;
  31610. default:
  31611. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31612. break;
  31613. }
  31614. };
  31615. // Define which axis you'd like to control for up & down
  31616. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31617. switch (axis) {
  31618. case JoystickAxis.X:
  31619. case JoystickAxis.Y:
  31620. case JoystickAxis.Z:
  31621. this._axisTargetedByUpAndDown = axis;
  31622. break;
  31623. default:
  31624. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31625. break;
  31626. }
  31627. };
  31628. VirtualJoystick.prototype._clearCanvas = function () {
  31629. if (this._leftJoystick) {
  31630. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31631. }
  31632. else {
  31633. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31634. }
  31635. };
  31636. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31637. var _this = this;
  31638. if (this.pressed) {
  31639. this._touches.forEach(function (touch) {
  31640. if (touch.pointerId === _this._joystickPointerID) {
  31641. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31642. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31643. VirtualJoystick.vjCanvasContext.beginPath();
  31644. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31645. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31646. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31647. VirtualJoystick.vjCanvasContext.stroke();
  31648. VirtualJoystick.vjCanvasContext.closePath();
  31649. VirtualJoystick.vjCanvasContext.beginPath();
  31650. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31651. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31652. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31653. VirtualJoystick.vjCanvasContext.stroke();
  31654. VirtualJoystick.vjCanvasContext.closePath();
  31655. VirtualJoystick.vjCanvasContext.beginPath();
  31656. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31657. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31658. VirtualJoystick.vjCanvasContext.stroke();
  31659. VirtualJoystick.vjCanvasContext.closePath();
  31660. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31661. }
  31662. else {
  31663. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31664. VirtualJoystick.vjCanvasContext.beginPath();
  31665. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31666. VirtualJoystick.vjCanvasContext.beginPath();
  31667. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31668. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31669. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31670. VirtualJoystick.vjCanvasContext.stroke();
  31671. VirtualJoystick.vjCanvasContext.closePath();
  31672. touch.prevX = touch.x;
  31673. touch.prevY = touch.y;
  31674. }
  31675. ;
  31676. });
  31677. }
  31678. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31679. };
  31680. VirtualJoystick.prototype.releaseCanvas = function () {
  31681. if (VirtualJoystick.vjCanvas) {
  31682. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31683. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31684. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31685. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31686. window.removeEventListener("resize", this._onResize);
  31687. document.body.removeChild(VirtualJoystick.vjCanvas);
  31688. VirtualJoystick.vjCanvas = null;
  31689. }
  31690. };
  31691. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31692. VirtualJoystick._globalJoystickIndex = 0;
  31693. return VirtualJoystick;
  31694. })();
  31695. BABYLON.VirtualJoystick = VirtualJoystick;
  31696. })(BABYLON || (BABYLON = {}));
  31697. var BABYLON;
  31698. (function (BABYLON) {
  31699. // We're mainly based on the logic defined into the FreeCamera code
  31700. var VirtualJoysticksCamera = (function (_super) {
  31701. __extends(VirtualJoysticksCamera, _super);
  31702. function VirtualJoysticksCamera(name, position, scene) {
  31703. _super.call(this, name, position, scene);
  31704. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31705. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31706. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31707. this._leftjoystick.setJoystickSensibility(0.15);
  31708. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31709. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31710. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31711. this._rightjoystick.reverseUpDown = true;
  31712. this._rightjoystick.setJoystickSensibility(0.05);
  31713. this._rightjoystick.setJoystickColor("yellow");
  31714. }
  31715. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31716. return this._leftjoystick;
  31717. };
  31718. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31719. return this._rightjoystick;
  31720. };
  31721. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31722. var speed = this._computeLocalCameraSpeed() * 50;
  31723. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31724. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31725. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31726. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31727. if (!this._leftjoystick.pressed) {
  31728. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31729. }
  31730. if (!this._rightjoystick.pressed) {
  31731. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31732. }
  31733. _super.prototype._checkInputs.call(this);
  31734. };
  31735. VirtualJoysticksCamera.prototype.dispose = function () {
  31736. this._leftjoystick.releaseCanvas();
  31737. _super.prototype.dispose.call(this);
  31738. };
  31739. return VirtualJoysticksCamera;
  31740. })(BABYLON.FreeCamera);
  31741. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31742. })(BABYLON || (BABYLON = {}));
  31743. var BABYLON;
  31744. (function (BABYLON) {
  31745. var AnaglyphPostProcess = (function (_super) {
  31746. __extends(AnaglyphPostProcess, _super);
  31747. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31748. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31749. }
  31750. return AnaglyphPostProcess;
  31751. })(BABYLON.PostProcess);
  31752. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31753. })(BABYLON || (BABYLON = {}));
  31754. var BABYLON;
  31755. (function (BABYLON) {
  31756. var OutlineRenderer = (function () {
  31757. function OutlineRenderer(scene) {
  31758. this._scene = scene;
  31759. }
  31760. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31761. var _this = this;
  31762. if (useOverlay === void 0) { useOverlay = false; }
  31763. var scene = this._scene;
  31764. var engine = this._scene.getEngine();
  31765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31766. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31767. return;
  31768. }
  31769. var mesh = subMesh.getRenderingMesh();
  31770. var material = subMesh.getMaterial();
  31771. engine.enableEffect(this._effect);
  31772. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31773. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31774. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31775. // Bones
  31776. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31777. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31778. }
  31779. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31780. // Alpha test
  31781. if (material && material.needAlphaTesting()) {
  31782. var alphaTexture = material.getAlphaTestTexture();
  31783. this._effect.setTexture("diffuseSampler", alphaTexture);
  31784. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31785. }
  31786. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31787. };
  31788. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31789. var defines = [];
  31790. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31791. var mesh = subMesh.getMesh();
  31792. var material = subMesh.getMaterial();
  31793. // Alpha test
  31794. if (material && material.needAlphaTesting()) {
  31795. defines.push("#define ALPHATEST");
  31796. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31797. attribs.push(BABYLON.VertexBuffer.UVKind);
  31798. defines.push("#define UV1");
  31799. }
  31800. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31801. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31802. defines.push("#define UV2");
  31803. }
  31804. }
  31805. // Bones
  31806. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31807. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31808. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31809. if (mesh.numBoneInfluencers > 4) {
  31810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31812. }
  31813. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31814. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31815. }
  31816. else {
  31817. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31818. }
  31819. // Instances
  31820. if (useInstances) {
  31821. defines.push("#define INSTANCES");
  31822. attribs.push("world0");
  31823. attribs.push("world1");
  31824. attribs.push("world2");
  31825. attribs.push("world3");
  31826. }
  31827. // Get correct effect
  31828. var join = defines.join("\n");
  31829. if (this._cachedDefines !== join) {
  31830. this._cachedDefines = join;
  31831. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31832. }
  31833. return this._effect.isReady();
  31834. };
  31835. return OutlineRenderer;
  31836. })();
  31837. BABYLON.OutlineRenderer = OutlineRenderer;
  31838. })(BABYLON || (BABYLON = {}));
  31839. var BABYLON;
  31840. (function (BABYLON) {
  31841. var MeshAssetTask = (function () {
  31842. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31843. this.name = name;
  31844. this.meshesNames = meshesNames;
  31845. this.rootUrl = rootUrl;
  31846. this.sceneFilename = sceneFilename;
  31847. this.isCompleted = false;
  31848. }
  31849. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31850. var _this = this;
  31851. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31852. _this.loadedMeshes = meshes;
  31853. _this.loadedParticleSystems = particleSystems;
  31854. _this.loadedSkeletons = skeletons;
  31855. _this.isCompleted = true;
  31856. if (_this.onSuccess) {
  31857. _this.onSuccess(_this);
  31858. }
  31859. onSuccess();
  31860. }, null, function () {
  31861. if (_this.onError) {
  31862. _this.onError(_this);
  31863. }
  31864. onError();
  31865. });
  31866. };
  31867. return MeshAssetTask;
  31868. })();
  31869. BABYLON.MeshAssetTask = MeshAssetTask;
  31870. var TextFileAssetTask = (function () {
  31871. function TextFileAssetTask(name, url) {
  31872. this.name = name;
  31873. this.url = url;
  31874. this.isCompleted = false;
  31875. }
  31876. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31877. var _this = this;
  31878. BABYLON.Tools.LoadFile(this.url, function (data) {
  31879. _this.text = data;
  31880. _this.isCompleted = true;
  31881. if (_this.onSuccess) {
  31882. _this.onSuccess(_this);
  31883. }
  31884. onSuccess();
  31885. }, null, scene.database, false, function () {
  31886. if (_this.onError) {
  31887. _this.onError(_this);
  31888. }
  31889. onError();
  31890. });
  31891. };
  31892. return TextFileAssetTask;
  31893. })();
  31894. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31895. var BinaryFileAssetTask = (function () {
  31896. function BinaryFileAssetTask(name, url) {
  31897. this.name = name;
  31898. this.url = url;
  31899. this.isCompleted = false;
  31900. }
  31901. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31902. var _this = this;
  31903. BABYLON.Tools.LoadFile(this.url, function (data) {
  31904. _this.data = data;
  31905. _this.isCompleted = true;
  31906. if (_this.onSuccess) {
  31907. _this.onSuccess(_this);
  31908. }
  31909. onSuccess();
  31910. }, null, scene.database, true, function () {
  31911. if (_this.onError) {
  31912. _this.onError(_this);
  31913. }
  31914. onError();
  31915. });
  31916. };
  31917. return BinaryFileAssetTask;
  31918. })();
  31919. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31920. var ImageAssetTask = (function () {
  31921. function ImageAssetTask(name, url) {
  31922. this.name = name;
  31923. this.url = url;
  31924. this.isCompleted = false;
  31925. }
  31926. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31927. var _this = this;
  31928. var img = new Image();
  31929. img.onload = function () {
  31930. _this.image = img;
  31931. _this.isCompleted = true;
  31932. if (_this.onSuccess) {
  31933. _this.onSuccess(_this);
  31934. }
  31935. onSuccess();
  31936. };
  31937. img.onerror = function () {
  31938. if (_this.onError) {
  31939. _this.onError(_this);
  31940. }
  31941. onError();
  31942. };
  31943. img.src = this.url;
  31944. };
  31945. return ImageAssetTask;
  31946. })();
  31947. BABYLON.ImageAssetTask = ImageAssetTask;
  31948. var TextureAssetTask = (function () {
  31949. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31951. this.name = name;
  31952. this.url = url;
  31953. this.noMipmap = noMipmap;
  31954. this.invertY = invertY;
  31955. this.samplingMode = samplingMode;
  31956. this.isCompleted = false;
  31957. }
  31958. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31959. var _this = this;
  31960. var onload = function () {
  31961. _this.isCompleted = true;
  31962. if (_this.onSuccess) {
  31963. _this.onSuccess(_this);
  31964. }
  31965. onSuccess();
  31966. };
  31967. var onerror = function () {
  31968. if (_this.onError) {
  31969. _this.onError(_this);
  31970. }
  31971. onError();
  31972. };
  31973. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31974. };
  31975. return TextureAssetTask;
  31976. })();
  31977. BABYLON.TextureAssetTask = TextureAssetTask;
  31978. var AssetsManager = (function () {
  31979. function AssetsManager(scene) {
  31980. this._tasks = new Array();
  31981. this._waitingTasksCount = 0;
  31982. this.useDefaultLoadingScreen = true;
  31983. this._scene = scene;
  31984. }
  31985. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31986. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31987. this._tasks.push(task);
  31988. return task;
  31989. };
  31990. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31991. var task = new TextFileAssetTask(taskName, url);
  31992. this._tasks.push(task);
  31993. return task;
  31994. };
  31995. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31996. var task = new BinaryFileAssetTask(taskName, url);
  31997. this._tasks.push(task);
  31998. return task;
  31999. };
  32000. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32001. var task = new ImageAssetTask(taskName, url);
  32002. this._tasks.push(task);
  32003. return task;
  32004. };
  32005. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32007. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32008. this._tasks.push(task);
  32009. return task;
  32010. };
  32011. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32012. this._waitingTasksCount--;
  32013. if (this._waitingTasksCount === 0) {
  32014. if (this.onFinish) {
  32015. this.onFinish(this._tasks);
  32016. }
  32017. this._scene.getEngine().hideLoadingUI();
  32018. }
  32019. };
  32020. AssetsManager.prototype._runTask = function (task) {
  32021. var _this = this;
  32022. task.run(this._scene, function () {
  32023. if (_this.onTaskSuccess) {
  32024. _this.onTaskSuccess(task);
  32025. }
  32026. _this._decreaseWaitingTasksCount();
  32027. }, function () {
  32028. if (_this.onTaskError) {
  32029. _this.onTaskError(task);
  32030. }
  32031. _this._decreaseWaitingTasksCount();
  32032. });
  32033. };
  32034. AssetsManager.prototype.reset = function () {
  32035. this._tasks = new Array();
  32036. return this;
  32037. };
  32038. AssetsManager.prototype.load = function () {
  32039. this._waitingTasksCount = this._tasks.length;
  32040. if (this._waitingTasksCount === 0) {
  32041. if (this.onFinish) {
  32042. this.onFinish(this._tasks);
  32043. }
  32044. return this;
  32045. }
  32046. if (this.useDefaultLoadingScreen) {
  32047. this._scene.getEngine().displayLoadingUI();
  32048. }
  32049. for (var index = 0; index < this._tasks.length; index++) {
  32050. var task = this._tasks[index];
  32051. this._runTask(task);
  32052. }
  32053. return this;
  32054. };
  32055. return AssetsManager;
  32056. })();
  32057. BABYLON.AssetsManager = AssetsManager;
  32058. })(BABYLON || (BABYLON = {}));
  32059. var BABYLON;
  32060. (function (BABYLON) {
  32061. var VRDeviceOrientationFreeCamera = (function (_super) {
  32062. __extends(VRDeviceOrientationFreeCamera, _super);
  32063. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32064. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32065. _super.call(this, name, position, scene);
  32066. this._alpha = 0;
  32067. this._beta = 0;
  32068. this._gamma = 0;
  32069. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32070. metrics.compensateDistortion = compensateDistortion;
  32071. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32072. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32073. }
  32074. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32075. this._alpha = +evt.alpha | 0;
  32076. this._beta = +evt.beta | 0;
  32077. this._gamma = +evt.gamma | 0;
  32078. if (this._gamma < 0) {
  32079. this._gamma = 90 + this._gamma;
  32080. }
  32081. else {
  32082. // Incline it in the correct angle.
  32083. this._gamma = 270 - this._gamma;
  32084. }
  32085. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32086. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32087. this.rotation.z = this._beta / 180.0 * Math.PI;
  32088. };
  32089. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32090. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32091. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32092. };
  32093. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32094. _super.prototype.detachControl.call(this, element);
  32095. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32096. };
  32097. return VRDeviceOrientationFreeCamera;
  32098. })(BABYLON.FreeCamera);
  32099. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32100. })(BABYLON || (BABYLON = {}));
  32101. var BABYLON;
  32102. (function (BABYLON) {
  32103. var WebVRFreeCamera = (function (_super) {
  32104. __extends(WebVRFreeCamera, _super);
  32105. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32106. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32107. _super.call(this, name, position, scene);
  32108. this._hmdDevice = null;
  32109. this._sensorDevice = null;
  32110. this._cacheState = null;
  32111. this._cacheQuaternion = new BABYLON.Quaternion();
  32112. this._cacheRotation = BABYLON.Vector3.Zero();
  32113. this._vrEnabled = false;
  32114. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32115. metrics.compensateDistortion = compensateDistortion;
  32116. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32117. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32118. }
  32119. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32120. var size = devices.length;
  32121. var i = 0;
  32122. // Reset devices.
  32123. this._sensorDevice = null;
  32124. this._hmdDevice = null;
  32125. // Search for a HmdDevice.
  32126. while (i < size && this._hmdDevice === null) {
  32127. if (devices[i] instanceof HMDVRDevice) {
  32128. this._hmdDevice = devices[i];
  32129. }
  32130. i++;
  32131. }
  32132. i = 0;
  32133. while (i < size && this._sensorDevice === null) {
  32134. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32135. this._sensorDevice = devices[i];
  32136. }
  32137. i++;
  32138. }
  32139. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32140. };
  32141. WebVRFreeCamera.prototype._checkInputs = function () {
  32142. if (this._vrEnabled) {
  32143. this._cacheState = this._sensorDevice.getState();
  32144. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32145. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32146. this.rotation.x = -this._cacheRotation.z;
  32147. this.rotation.y = -this._cacheRotation.y;
  32148. this.rotation.z = this._cacheRotation.x;
  32149. }
  32150. _super.prototype._checkInputs.call(this);
  32151. };
  32152. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32153. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32154. if (navigator.getVRDevices) {
  32155. navigator.getVRDevices().then(this._getWebVRDevices);
  32156. }
  32157. else if (navigator.mozGetVRDevices) {
  32158. navigator.mozGetVRDevices(this._getWebVRDevices);
  32159. }
  32160. };
  32161. WebVRFreeCamera.prototype.detachControl = function (element) {
  32162. _super.prototype.detachControl.call(this, element);
  32163. this._vrEnabled = false;
  32164. };
  32165. return WebVRFreeCamera;
  32166. })(BABYLON.FreeCamera);
  32167. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32168. })(BABYLON || (BABYLON = {}));
  32169. var BABYLON;
  32170. (function (BABYLON) {
  32171. // Standard optimizations
  32172. var SceneOptimization = (function () {
  32173. function SceneOptimization(priority) {
  32174. if (priority === void 0) { priority = 0; }
  32175. this.priority = priority;
  32176. this.apply = function (scene) {
  32177. return true; // Return true if everything that can be done was applied
  32178. };
  32179. }
  32180. return SceneOptimization;
  32181. })();
  32182. BABYLON.SceneOptimization = SceneOptimization;
  32183. var TextureOptimization = (function (_super) {
  32184. __extends(TextureOptimization, _super);
  32185. function TextureOptimization(priority, maximumSize) {
  32186. var _this = this;
  32187. if (priority === void 0) { priority = 0; }
  32188. if (maximumSize === void 0) { maximumSize = 1024; }
  32189. _super.call(this, priority);
  32190. this.priority = priority;
  32191. this.maximumSize = maximumSize;
  32192. this.apply = function (scene) {
  32193. var allDone = true;
  32194. for (var index = 0; index < scene.textures.length; index++) {
  32195. var texture = scene.textures[index];
  32196. if (!texture.canRescale) {
  32197. continue;
  32198. }
  32199. var currentSize = texture.getSize();
  32200. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32201. if (maxDimension > _this.maximumSize) {
  32202. texture.scale(0.5);
  32203. allDone = false;
  32204. }
  32205. }
  32206. return allDone;
  32207. };
  32208. }
  32209. return TextureOptimization;
  32210. })(SceneOptimization);
  32211. BABYLON.TextureOptimization = TextureOptimization;
  32212. var HardwareScalingOptimization = (function (_super) {
  32213. __extends(HardwareScalingOptimization, _super);
  32214. function HardwareScalingOptimization(priority, maximumScale) {
  32215. var _this = this;
  32216. if (priority === void 0) { priority = 0; }
  32217. if (maximumScale === void 0) { maximumScale = 2; }
  32218. _super.call(this, priority);
  32219. this.priority = priority;
  32220. this.maximumScale = maximumScale;
  32221. this._currentScale = 1;
  32222. this.apply = function (scene) {
  32223. _this._currentScale++;
  32224. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32225. return _this._currentScale >= _this.maximumScale;
  32226. };
  32227. }
  32228. return HardwareScalingOptimization;
  32229. })(SceneOptimization);
  32230. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32231. var ShadowsOptimization = (function (_super) {
  32232. __extends(ShadowsOptimization, _super);
  32233. function ShadowsOptimization() {
  32234. _super.apply(this, arguments);
  32235. this.apply = function (scene) {
  32236. scene.shadowsEnabled = false;
  32237. return true;
  32238. };
  32239. }
  32240. return ShadowsOptimization;
  32241. })(SceneOptimization);
  32242. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32243. var PostProcessesOptimization = (function (_super) {
  32244. __extends(PostProcessesOptimization, _super);
  32245. function PostProcessesOptimization() {
  32246. _super.apply(this, arguments);
  32247. this.apply = function (scene) {
  32248. scene.postProcessesEnabled = false;
  32249. return true;
  32250. };
  32251. }
  32252. return PostProcessesOptimization;
  32253. })(SceneOptimization);
  32254. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32255. var LensFlaresOptimization = (function (_super) {
  32256. __extends(LensFlaresOptimization, _super);
  32257. function LensFlaresOptimization() {
  32258. _super.apply(this, arguments);
  32259. this.apply = function (scene) {
  32260. scene.lensFlaresEnabled = false;
  32261. return true;
  32262. };
  32263. }
  32264. return LensFlaresOptimization;
  32265. })(SceneOptimization);
  32266. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32267. var ParticlesOptimization = (function (_super) {
  32268. __extends(ParticlesOptimization, _super);
  32269. function ParticlesOptimization() {
  32270. _super.apply(this, arguments);
  32271. this.apply = function (scene) {
  32272. scene.particlesEnabled = false;
  32273. return true;
  32274. };
  32275. }
  32276. return ParticlesOptimization;
  32277. })(SceneOptimization);
  32278. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32279. var RenderTargetsOptimization = (function (_super) {
  32280. __extends(RenderTargetsOptimization, _super);
  32281. function RenderTargetsOptimization() {
  32282. _super.apply(this, arguments);
  32283. this.apply = function (scene) {
  32284. scene.renderTargetsEnabled = false;
  32285. return true;
  32286. };
  32287. }
  32288. return RenderTargetsOptimization;
  32289. })(SceneOptimization);
  32290. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32291. var MergeMeshesOptimization = (function (_super) {
  32292. __extends(MergeMeshesOptimization, _super);
  32293. function MergeMeshesOptimization() {
  32294. var _this = this;
  32295. _super.apply(this, arguments);
  32296. this._canBeMerged = function (abstractMesh) {
  32297. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32298. return false;
  32299. }
  32300. var mesh = abstractMesh;
  32301. if (!mesh.isVisible || !mesh.isEnabled()) {
  32302. return false;
  32303. }
  32304. if (mesh.instances.length > 0) {
  32305. return false;
  32306. }
  32307. if (mesh.skeleton || mesh.hasLODLevels) {
  32308. return false;
  32309. }
  32310. if (mesh.parent) {
  32311. return false;
  32312. }
  32313. return true;
  32314. };
  32315. this.apply = function (scene, updateSelectionTree) {
  32316. var globalPool = scene.meshes.slice(0);
  32317. var globalLength = globalPool.length;
  32318. for (var index = 0; index < globalLength; index++) {
  32319. var currentPool = new Array();
  32320. var current = globalPool[index];
  32321. // Checks
  32322. if (!_this._canBeMerged(current)) {
  32323. continue;
  32324. }
  32325. currentPool.push(current);
  32326. // Find compatible meshes
  32327. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  32328. var otherMesh = globalPool[subIndex];
  32329. if (!_this._canBeMerged(otherMesh)) {
  32330. continue;
  32331. }
  32332. if (otherMesh.material !== current.material) {
  32333. continue;
  32334. }
  32335. if (otherMesh.checkCollisions !== current.checkCollisions) {
  32336. continue;
  32337. }
  32338. currentPool.push(otherMesh);
  32339. globalLength--;
  32340. globalPool.splice(subIndex, 1);
  32341. subIndex--;
  32342. }
  32343. if (currentPool.length < 2) {
  32344. continue;
  32345. }
  32346. // Merge meshes
  32347. BABYLON.Mesh.MergeMeshes(currentPool);
  32348. }
  32349. if (updateSelectionTree != undefined) {
  32350. if (updateSelectionTree) {
  32351. scene.createOrUpdateSelectionOctree();
  32352. }
  32353. }
  32354. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  32355. scene.createOrUpdateSelectionOctree();
  32356. }
  32357. return true;
  32358. };
  32359. }
  32360. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  32361. get: function () {
  32362. return MergeMeshesOptimization._UpdateSelectionTree;
  32363. },
  32364. set: function (value) {
  32365. MergeMeshesOptimization._UpdateSelectionTree = value;
  32366. },
  32367. enumerable: true,
  32368. configurable: true
  32369. });
  32370. MergeMeshesOptimization._UpdateSelectionTree = false;
  32371. return MergeMeshesOptimization;
  32372. })(SceneOptimization);
  32373. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  32374. // Options
  32375. var SceneOptimizerOptions = (function () {
  32376. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  32377. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  32378. if (trackerDuration === void 0) { trackerDuration = 2000; }
  32379. this.targetFrameRate = targetFrameRate;
  32380. this.trackerDuration = trackerDuration;
  32381. this.optimizations = new Array();
  32382. }
  32383. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  32384. var result = new SceneOptimizerOptions(targetFrameRate);
  32385. var priority = 0;
  32386. result.optimizations.push(new MergeMeshesOptimization(priority));
  32387. result.optimizations.push(new ShadowsOptimization(priority));
  32388. result.optimizations.push(new LensFlaresOptimization(priority));
  32389. // Next priority
  32390. priority++;
  32391. result.optimizations.push(new PostProcessesOptimization(priority));
  32392. result.optimizations.push(new ParticlesOptimization(priority));
  32393. // Next priority
  32394. priority++;
  32395. result.optimizations.push(new TextureOptimization(priority, 1024));
  32396. return result;
  32397. };
  32398. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32399. var result = new SceneOptimizerOptions(targetFrameRate);
  32400. var priority = 0;
  32401. result.optimizations.push(new MergeMeshesOptimization(priority));
  32402. result.optimizations.push(new ShadowsOptimization(priority));
  32403. result.optimizations.push(new LensFlaresOptimization(priority));
  32404. // Next priority
  32405. priority++;
  32406. result.optimizations.push(new PostProcessesOptimization(priority));
  32407. result.optimizations.push(new ParticlesOptimization(priority));
  32408. // Next priority
  32409. priority++;
  32410. result.optimizations.push(new TextureOptimization(priority, 512));
  32411. // Next priority
  32412. priority++;
  32413. result.optimizations.push(new RenderTargetsOptimization(priority));
  32414. // Next priority
  32415. priority++;
  32416. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32417. return result;
  32418. };
  32419. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32420. var result = new SceneOptimizerOptions(targetFrameRate);
  32421. var priority = 0;
  32422. result.optimizations.push(new MergeMeshesOptimization(priority));
  32423. result.optimizations.push(new ShadowsOptimization(priority));
  32424. result.optimizations.push(new LensFlaresOptimization(priority));
  32425. // Next priority
  32426. priority++;
  32427. result.optimizations.push(new PostProcessesOptimization(priority));
  32428. result.optimizations.push(new ParticlesOptimization(priority));
  32429. // Next priority
  32430. priority++;
  32431. result.optimizations.push(new TextureOptimization(priority, 256));
  32432. // Next priority
  32433. priority++;
  32434. result.optimizations.push(new RenderTargetsOptimization(priority));
  32435. // Next priority
  32436. priority++;
  32437. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32438. return result;
  32439. };
  32440. return SceneOptimizerOptions;
  32441. })();
  32442. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32443. // Scene optimizer tool
  32444. var SceneOptimizer = (function () {
  32445. function SceneOptimizer() {
  32446. }
  32447. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32448. // TODO: add an epsilon
  32449. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32450. if (onSuccess) {
  32451. onSuccess();
  32452. }
  32453. return;
  32454. }
  32455. // Apply current level of optimizations
  32456. var allDone = true;
  32457. var noOptimizationApplied = true;
  32458. for (var index = 0; index < options.optimizations.length; index++) {
  32459. var optimization = options.optimizations[index];
  32460. if (optimization.priority === currentPriorityLevel) {
  32461. noOptimizationApplied = false;
  32462. allDone = allDone && optimization.apply(scene);
  32463. }
  32464. }
  32465. // If no optimization was applied, this is a failure :(
  32466. if (noOptimizationApplied) {
  32467. if (onFailure) {
  32468. onFailure();
  32469. }
  32470. return;
  32471. }
  32472. // If all optimizations were done, move to next level
  32473. if (allDone) {
  32474. currentPriorityLevel++;
  32475. }
  32476. // Let's the system running for a specific amount of time before checking FPS
  32477. scene.executeWhenReady(function () {
  32478. setTimeout(function () {
  32479. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32480. }, options.trackerDuration);
  32481. });
  32482. };
  32483. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32484. if (!options) {
  32485. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32486. }
  32487. // Let's the system running for a specific amount of time before checking FPS
  32488. scene.executeWhenReady(function () {
  32489. setTimeout(function () {
  32490. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32491. }, options.trackerDuration);
  32492. });
  32493. };
  32494. return SceneOptimizer;
  32495. })();
  32496. BABYLON.SceneOptimizer = SceneOptimizer;
  32497. })(BABYLON || (BABYLON = {}));
  32498. var BABYLON;
  32499. (function (BABYLON) {
  32500. var Internals;
  32501. (function (Internals) {
  32502. var MeshLODLevel = (function () {
  32503. function MeshLODLevel(distance, mesh) {
  32504. this.distance = distance;
  32505. this.mesh = mesh;
  32506. }
  32507. return MeshLODLevel;
  32508. })();
  32509. Internals.MeshLODLevel = MeshLODLevel;
  32510. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32511. })(BABYLON || (BABYLON = {}));
  32512. var BABYLON;
  32513. (function (BABYLON) {
  32514. var RawTexture = (function (_super) {
  32515. __extends(RawTexture, _super);
  32516. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32517. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32518. if (invertY === void 0) { invertY = false; }
  32519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32520. _super.call(this, null, scene, !generateMipMaps, invertY);
  32521. this.format = format;
  32522. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32523. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32524. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32525. }
  32526. RawTexture.prototype.update = function (data) {
  32527. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32528. };
  32529. // Statics
  32530. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32531. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32532. if (invertY === void 0) { invertY = false; }
  32533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32534. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32535. };
  32536. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32538. if (invertY === void 0) { invertY = false; }
  32539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32540. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32541. };
  32542. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32544. if (invertY === void 0) { invertY = false; }
  32545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32546. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32547. };
  32548. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32549. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32550. if (invertY === void 0) { invertY = false; }
  32551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32552. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32553. };
  32554. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32555. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32556. if (invertY === void 0) { invertY = false; }
  32557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32558. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32559. };
  32560. return RawTexture;
  32561. })(BABYLON.Texture);
  32562. BABYLON.RawTexture = RawTexture;
  32563. })(BABYLON || (BABYLON = {}));
  32564. var BABYLON;
  32565. (function (BABYLON) {
  32566. var IndexedVector2 = (function (_super) {
  32567. __extends(IndexedVector2, _super);
  32568. function IndexedVector2(original, index) {
  32569. _super.call(this, original.x, original.y);
  32570. this.index = index;
  32571. }
  32572. return IndexedVector2;
  32573. })(BABYLON.Vector2);
  32574. var PolygonPoints = (function () {
  32575. function PolygonPoints() {
  32576. this.elements = new Array();
  32577. }
  32578. PolygonPoints.prototype.add = function (originalPoints) {
  32579. var _this = this;
  32580. var result = new Array();
  32581. originalPoints.forEach(function (point) {
  32582. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32583. var newPoint = new IndexedVector2(point, _this.elements.length);
  32584. result.push(newPoint);
  32585. _this.elements.push(newPoint);
  32586. }
  32587. });
  32588. return result;
  32589. };
  32590. PolygonPoints.prototype.computeBounds = function () {
  32591. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32592. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32593. this.elements.forEach(function (point) {
  32594. // x
  32595. if (point.x < lmin.x) {
  32596. lmin.x = point.x;
  32597. }
  32598. else if (point.x > lmax.x) {
  32599. lmax.x = point.x;
  32600. }
  32601. // y
  32602. if (point.y < lmin.y) {
  32603. lmin.y = point.y;
  32604. }
  32605. else if (point.y > lmax.y) {
  32606. lmax.y = point.y;
  32607. }
  32608. });
  32609. return {
  32610. min: lmin,
  32611. max: lmax,
  32612. width: lmax.x - lmin.x,
  32613. height: lmax.y - lmin.y
  32614. };
  32615. };
  32616. return PolygonPoints;
  32617. })();
  32618. var Polygon = (function () {
  32619. function Polygon() {
  32620. }
  32621. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32622. return [
  32623. new BABYLON.Vector2(xmin, ymin),
  32624. new BABYLON.Vector2(xmax, ymin),
  32625. new BABYLON.Vector2(xmax, ymax),
  32626. new BABYLON.Vector2(xmin, ymax)
  32627. ];
  32628. };
  32629. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32630. if (cx === void 0) { cx = 0; }
  32631. if (cy === void 0) { cy = 0; }
  32632. if (numberOfSides === void 0) { numberOfSides = 32; }
  32633. var result = new Array();
  32634. var angle = 0;
  32635. var increment = (Math.PI * 2) / numberOfSides;
  32636. for (var i = 0; i < numberOfSides; i++) {
  32637. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32638. angle -= increment;
  32639. }
  32640. return result;
  32641. };
  32642. Polygon.Parse = function (input) {
  32643. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32644. var i, result = [];
  32645. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32646. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32647. }
  32648. return result;
  32649. };
  32650. Polygon.StartingAt = function (x, y) {
  32651. return BABYLON.Path2.StartingAt(x, y);
  32652. };
  32653. return Polygon;
  32654. })();
  32655. BABYLON.Polygon = Polygon;
  32656. var PolygonMeshBuilder = (function () {
  32657. function PolygonMeshBuilder(name, contours, scene) {
  32658. this._points = new PolygonPoints();
  32659. this._outlinepoints = new PolygonPoints();
  32660. this._holes = [];
  32661. if (!("poly2tri" in window)) {
  32662. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32663. }
  32664. this._name = name;
  32665. this._scene = scene;
  32666. var points;
  32667. if (contours instanceof BABYLON.Path2) {
  32668. points = contours.getPoints();
  32669. }
  32670. else {
  32671. points = contours;
  32672. }
  32673. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32674. this._outlinepoints.add(points);
  32675. }
  32676. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32677. this._swctx.addHole(this._points.add(hole));
  32678. var holepoints = new PolygonPoints();
  32679. holepoints.add(hole);
  32680. this._holes.push(holepoints);
  32681. return this;
  32682. };
  32683. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32684. var _this = this;
  32685. if (updatable === void 0) { updatable = false; }
  32686. var result = new BABYLON.Mesh(this._name, this._scene);
  32687. var normals = [];
  32688. var positions = [];
  32689. var uvs = [];
  32690. var bounds = this._points.computeBounds();
  32691. this._points.elements.forEach(function (p) {
  32692. normals.push(0, 1.0, 0);
  32693. positions.push(p.x, 0, p.y);
  32694. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32695. });
  32696. var indices = [];
  32697. this._swctx.triangulate();
  32698. this._swctx.getTriangles().forEach(function (triangle) {
  32699. triangle.getPoints().forEach(function (point) {
  32700. indices.push(point.index);
  32701. });
  32702. });
  32703. if (depth > 0) {
  32704. var positionscount = (positions.length / 3); //get the current pointcount
  32705. this._points.elements.forEach(function (p) {
  32706. normals.push(0, -1.0, 0);
  32707. positions.push(p.x, -depth, p.y);
  32708. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32709. });
  32710. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32711. var p2;
  32712. var poscounter = 0;
  32713. this._swctx.getTriangles().forEach(function (triangle) {
  32714. triangle.getPoints().forEach(function (point) {
  32715. switch (poscounter) {
  32716. case 0:
  32717. p1 = point;
  32718. break;
  32719. case 1:
  32720. p2 = point;
  32721. break;
  32722. case 2:
  32723. indices.push(point.index + positionscount);
  32724. indices.push(p2.index + positionscount);
  32725. indices.push(p1.index + positionscount);
  32726. poscounter = -1;
  32727. break;
  32728. }
  32729. poscounter++;
  32730. //indices.push((<IndexedVector2>point).index + positionscount);
  32731. });
  32732. });
  32733. //Add the sides
  32734. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32735. this._holes.forEach(function (hole) {
  32736. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32737. });
  32738. }
  32739. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32740. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32741. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32742. result.setIndices(indices);
  32743. return result;
  32744. };
  32745. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32746. var StartIndex = positions.length / 3;
  32747. var ulength = 0;
  32748. for (var i = 0; i < points.elements.length; i++) {
  32749. var p = points.elements[i];
  32750. var p1;
  32751. if ((i + 1) > points.elements.length - 1) {
  32752. p1 = points.elements[0];
  32753. }
  32754. else {
  32755. p1 = points.elements[i + 1];
  32756. }
  32757. positions.push(p.x, 0, p.y);
  32758. positions.push(p.x, -depth, p.y);
  32759. positions.push(p1.x, 0, p1.y);
  32760. positions.push(p1.x, -depth, p1.y);
  32761. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32762. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32763. var v3 = v2.subtract(v1);
  32764. var v4 = new BABYLON.Vector3(0, 1, 0);
  32765. var vn = BABYLON.Vector3.Cross(v3, v4);
  32766. vn = vn.normalize();
  32767. uvs.push(ulength / bounds.width, 0);
  32768. uvs.push(ulength / bounds.width, 1);
  32769. ulength += v3.length();
  32770. uvs.push((ulength / bounds.width), 0);
  32771. uvs.push((ulength / bounds.width), 1);
  32772. if (!flip) {
  32773. normals.push(-vn.x, -vn.y, -vn.z);
  32774. normals.push(-vn.x, -vn.y, -vn.z);
  32775. normals.push(-vn.x, -vn.y, -vn.z);
  32776. normals.push(-vn.x, -vn.y, -vn.z);
  32777. indices.push(StartIndex);
  32778. indices.push(StartIndex + 1);
  32779. indices.push(StartIndex + 2);
  32780. indices.push(StartIndex + 1);
  32781. indices.push(StartIndex + 3);
  32782. indices.push(StartIndex + 2);
  32783. }
  32784. else {
  32785. normals.push(vn.x, vn.y, vn.z);
  32786. normals.push(vn.x, vn.y, vn.z);
  32787. normals.push(vn.x, vn.y, vn.z);
  32788. normals.push(vn.x, vn.y, vn.z);
  32789. indices.push(StartIndex);
  32790. indices.push(StartIndex + 2);
  32791. indices.push(StartIndex + 1);
  32792. indices.push(StartIndex + 1);
  32793. indices.push(StartIndex + 2);
  32794. indices.push(StartIndex + 3);
  32795. }
  32796. StartIndex += 4;
  32797. }
  32798. ;
  32799. };
  32800. return PolygonMeshBuilder;
  32801. })();
  32802. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32803. })(BABYLON || (BABYLON = {}));
  32804. var BABYLON;
  32805. (function (BABYLON) {
  32806. var Octree = (function () {
  32807. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32808. if (maxDepth === void 0) { maxDepth = 2; }
  32809. this.maxDepth = maxDepth;
  32810. this.dynamicContent = new Array();
  32811. this._maxBlockCapacity = maxBlockCapacity || 64;
  32812. this._selectionContent = new BABYLON.SmartArray(1024);
  32813. this._creationFunc = creationFunc;
  32814. }
  32815. // Methods
  32816. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32817. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32818. };
  32819. Octree.prototype.addMesh = function (entry) {
  32820. for (var index = 0; index < this.blocks.length; index++) {
  32821. var block = this.blocks[index];
  32822. block.addEntry(entry);
  32823. }
  32824. };
  32825. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32826. this._selectionContent.reset();
  32827. for (var index = 0; index < this.blocks.length; index++) {
  32828. var block = this.blocks[index];
  32829. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32830. }
  32831. if (allowDuplicate) {
  32832. this._selectionContent.concat(this.dynamicContent);
  32833. }
  32834. else {
  32835. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32836. }
  32837. return this._selectionContent;
  32838. };
  32839. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32840. this._selectionContent.reset();
  32841. for (var index = 0; index < this.blocks.length; index++) {
  32842. var block = this.blocks[index];
  32843. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32844. }
  32845. if (allowDuplicate) {
  32846. this._selectionContent.concat(this.dynamicContent);
  32847. }
  32848. else {
  32849. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32850. }
  32851. return this._selectionContent;
  32852. };
  32853. Octree.prototype.intersectsRay = function (ray) {
  32854. this._selectionContent.reset();
  32855. for (var index = 0; index < this.blocks.length; index++) {
  32856. var block = this.blocks[index];
  32857. block.intersectsRay(ray, this._selectionContent);
  32858. }
  32859. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32860. return this._selectionContent;
  32861. };
  32862. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32863. target.blocks = new Array();
  32864. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32865. // Segmenting space
  32866. for (var x = 0; x < 2; x++) {
  32867. for (var y = 0; y < 2; y++) {
  32868. for (var z = 0; z < 2; z++) {
  32869. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32870. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32871. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32872. block.addEntries(entries);
  32873. target.blocks.push(block);
  32874. }
  32875. }
  32876. }
  32877. };
  32878. Octree.CreationFuncForMeshes = function (entry, block) {
  32879. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32880. block.entries.push(entry);
  32881. }
  32882. };
  32883. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32884. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32885. block.entries.push(entry);
  32886. }
  32887. };
  32888. return Octree;
  32889. })();
  32890. BABYLON.Octree = Octree;
  32891. })(BABYLON || (BABYLON = {}));
  32892. var BABYLON;
  32893. (function (BABYLON) {
  32894. var OctreeBlock = (function () {
  32895. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32896. this.entries = new Array();
  32897. this._boundingVectors = new Array();
  32898. this._capacity = capacity;
  32899. this._depth = depth;
  32900. this._maxDepth = maxDepth;
  32901. this._creationFunc = creationFunc;
  32902. this._minPoint = minPoint;
  32903. this._maxPoint = maxPoint;
  32904. this._boundingVectors.push(minPoint.clone());
  32905. this._boundingVectors.push(maxPoint.clone());
  32906. this._boundingVectors.push(minPoint.clone());
  32907. this._boundingVectors[2].x = maxPoint.x;
  32908. this._boundingVectors.push(minPoint.clone());
  32909. this._boundingVectors[3].y = maxPoint.y;
  32910. this._boundingVectors.push(minPoint.clone());
  32911. this._boundingVectors[4].z = maxPoint.z;
  32912. this._boundingVectors.push(maxPoint.clone());
  32913. this._boundingVectors[5].z = minPoint.z;
  32914. this._boundingVectors.push(maxPoint.clone());
  32915. this._boundingVectors[6].x = minPoint.x;
  32916. this._boundingVectors.push(maxPoint.clone());
  32917. this._boundingVectors[7].y = minPoint.y;
  32918. }
  32919. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32920. // Property
  32921. get: function () {
  32922. return this._capacity;
  32923. },
  32924. enumerable: true,
  32925. configurable: true
  32926. });
  32927. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32928. get: function () {
  32929. return this._minPoint;
  32930. },
  32931. enumerable: true,
  32932. configurable: true
  32933. });
  32934. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32935. get: function () {
  32936. return this._maxPoint;
  32937. },
  32938. enumerable: true,
  32939. configurable: true
  32940. });
  32941. // Methods
  32942. OctreeBlock.prototype.addEntry = function (entry) {
  32943. if (this.blocks) {
  32944. for (var index = 0; index < this.blocks.length; index++) {
  32945. var block = this.blocks[index];
  32946. block.addEntry(entry);
  32947. }
  32948. return;
  32949. }
  32950. this._creationFunc(entry, this);
  32951. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32952. this.createInnerBlocks();
  32953. }
  32954. };
  32955. OctreeBlock.prototype.addEntries = function (entries) {
  32956. for (var index = 0; index < entries.length; index++) {
  32957. var mesh = entries[index];
  32958. this.addEntry(mesh);
  32959. }
  32960. };
  32961. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32962. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32963. if (this.blocks) {
  32964. for (var index = 0; index < this.blocks.length; index++) {
  32965. var block = this.blocks[index];
  32966. block.select(frustumPlanes, selection, allowDuplicate);
  32967. }
  32968. return;
  32969. }
  32970. if (allowDuplicate) {
  32971. selection.concat(this.entries);
  32972. }
  32973. else {
  32974. selection.concatWithNoDuplicate(this.entries);
  32975. }
  32976. }
  32977. };
  32978. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32979. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32980. if (this.blocks) {
  32981. for (var index = 0; index < this.blocks.length; index++) {
  32982. var block = this.blocks[index];
  32983. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32984. }
  32985. return;
  32986. }
  32987. if (allowDuplicate) {
  32988. selection.concat(this.entries);
  32989. }
  32990. else {
  32991. selection.concatWithNoDuplicate(this.entries);
  32992. }
  32993. }
  32994. };
  32995. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32996. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32997. if (this.blocks) {
  32998. for (var index = 0; index < this.blocks.length; index++) {
  32999. var block = this.blocks[index];
  33000. block.intersectsRay(ray, selection);
  33001. }
  33002. return;
  33003. }
  33004. selection.concatWithNoDuplicate(this.entries);
  33005. }
  33006. };
  33007. OctreeBlock.prototype.createInnerBlocks = function () {
  33008. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33009. };
  33010. return OctreeBlock;
  33011. })();
  33012. BABYLON.OctreeBlock = OctreeBlock;
  33013. })(BABYLON || (BABYLON = {}));
  33014. var BABYLON;
  33015. (function (BABYLON) {
  33016. var BlurPostProcess = (function (_super) {
  33017. __extends(BlurPostProcess, _super);
  33018. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33019. var _this = this;
  33020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33021. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33022. this.direction = direction;
  33023. this.blurWidth = blurWidth;
  33024. this.onApply = function (effect) {
  33025. effect.setFloat2("screenSize", _this.width, _this.height);
  33026. effect.setVector2("direction", _this.direction);
  33027. effect.setFloat("blurWidth", _this.blurWidth);
  33028. };
  33029. }
  33030. return BlurPostProcess;
  33031. })(BABYLON.PostProcess);
  33032. BABYLON.BlurPostProcess = BlurPostProcess;
  33033. })(BABYLON || (BABYLON = {}));
  33034. var BABYLON;
  33035. (function (BABYLON) {
  33036. var RefractionPostProcess = (function (_super) {
  33037. __extends(RefractionPostProcess, _super);
  33038. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33039. var _this = this;
  33040. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33041. this.color = color;
  33042. this.depth = depth;
  33043. this.colorLevel = colorLevel;
  33044. this.onActivate = function (cam) {
  33045. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33046. };
  33047. this.onApply = function (effect) {
  33048. effect.setColor3("baseColor", _this.color);
  33049. effect.setFloat("depth", _this.depth);
  33050. effect.setFloat("colorLevel", _this.colorLevel);
  33051. effect.setTexture("refractionSampler", _this._refRexture);
  33052. };
  33053. }
  33054. // Methods
  33055. RefractionPostProcess.prototype.dispose = function (camera) {
  33056. if (this._refRexture) {
  33057. this._refRexture.dispose();
  33058. }
  33059. _super.prototype.dispose.call(this, camera);
  33060. };
  33061. return RefractionPostProcess;
  33062. })(BABYLON.PostProcess);
  33063. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33064. })(BABYLON || (BABYLON = {}));
  33065. var BABYLON;
  33066. (function (BABYLON) {
  33067. var BlackAndWhitePostProcess = (function (_super) {
  33068. __extends(BlackAndWhitePostProcess, _super);
  33069. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33070. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33071. }
  33072. return BlackAndWhitePostProcess;
  33073. })(BABYLON.PostProcess);
  33074. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33075. })(BABYLON || (BABYLON = {}));
  33076. var BABYLON;
  33077. (function (BABYLON) {
  33078. var ConvolutionPostProcess = (function (_super) {
  33079. __extends(ConvolutionPostProcess, _super);
  33080. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33081. var _this = this;
  33082. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33083. this.kernel = kernel;
  33084. this.onApply = function (effect) {
  33085. effect.setFloat2("screenSize", _this.width, _this.height);
  33086. effect.setArray("kernel", _this.kernel);
  33087. };
  33088. }
  33089. // Statics
  33090. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33091. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33092. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33093. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33094. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33095. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33096. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33097. return ConvolutionPostProcess;
  33098. })(BABYLON.PostProcess);
  33099. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33100. })(BABYLON || (BABYLON = {}));
  33101. var BABYLON;
  33102. (function (BABYLON) {
  33103. var FilterPostProcess = (function (_super) {
  33104. __extends(FilterPostProcess, _super);
  33105. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33106. var _this = this;
  33107. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33108. this.kernelMatrix = kernelMatrix;
  33109. this.onApply = function (effect) {
  33110. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33111. };
  33112. }
  33113. return FilterPostProcess;
  33114. })(BABYLON.PostProcess);
  33115. BABYLON.FilterPostProcess = FilterPostProcess;
  33116. })(BABYLON || (BABYLON = {}));
  33117. var BABYLON;
  33118. (function (BABYLON) {
  33119. var FxaaPostProcess = (function (_super) {
  33120. __extends(FxaaPostProcess, _super);
  33121. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33122. var _this = this;
  33123. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33124. this.onSizeChanged = function () {
  33125. _this.texelWidth = 1.0 / _this.width;
  33126. _this.texelHeight = 1.0 / _this.height;
  33127. };
  33128. this.onApply = function (effect) {
  33129. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33130. };
  33131. }
  33132. return FxaaPostProcess;
  33133. })(BABYLON.PostProcess);
  33134. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33135. })(BABYLON || (BABYLON = {}));
  33136. var BABYLON;
  33137. (function (BABYLON) {
  33138. var StereoscopicInterlacePostProcess = (function (_super) {
  33139. __extends(StereoscopicInterlacePostProcess, _super);
  33140. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33141. var _this = this;
  33142. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33143. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33144. this.onSizeChanged = function () {
  33145. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33146. };
  33147. this.onApply = function (effect) {
  33148. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33149. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33150. };
  33151. }
  33152. return StereoscopicInterlacePostProcess;
  33153. })(BABYLON.PostProcess);
  33154. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33155. })(BABYLON || (BABYLON = {}));
  33156. var BABYLON;
  33157. (function (BABYLON) {
  33158. var LensFlare = (function () {
  33159. function LensFlare(size, position, color, imgUrl, system) {
  33160. this.size = size;
  33161. this.position = position;
  33162. this.dispose = function () {
  33163. if (this.texture) {
  33164. this.texture.dispose();
  33165. }
  33166. // Remove from scene
  33167. var index = this._system.lensFlares.indexOf(this);
  33168. this._system.lensFlares.splice(index, 1);
  33169. };
  33170. this.color = color || new BABYLON.Color3(1, 1, 1);
  33171. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33172. this._system = system;
  33173. system.lensFlares.push(this);
  33174. }
  33175. return LensFlare;
  33176. })();
  33177. BABYLON.LensFlare = LensFlare;
  33178. })(BABYLON || (BABYLON = {}));
  33179. var BABYLON;
  33180. (function (BABYLON) {
  33181. var LensFlareSystem = (function () {
  33182. function LensFlareSystem(name, emitter, scene) {
  33183. this.name = name;
  33184. this.lensFlares = new Array();
  33185. this.borderLimit = 300;
  33186. this.layerMask = 0x0FFFFFFF;
  33187. this._vertexDeclaration = [2];
  33188. this._vertexStrideSize = 2 * 4;
  33189. this._isEnabled = true;
  33190. this._scene = scene;
  33191. this._emitter = emitter;
  33192. scene.lensFlareSystems.push(this);
  33193. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33194. // VBO
  33195. var vertices = [];
  33196. vertices.push(1, 1);
  33197. vertices.push(-1, 1);
  33198. vertices.push(-1, -1);
  33199. vertices.push(1, -1);
  33200. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33201. // Indices
  33202. var indices = [];
  33203. indices.push(0);
  33204. indices.push(1);
  33205. indices.push(2);
  33206. indices.push(0);
  33207. indices.push(2);
  33208. indices.push(3);
  33209. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33210. // Effects
  33211. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33212. }
  33213. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33214. get: function () {
  33215. return this._isEnabled;
  33216. },
  33217. set: function (value) {
  33218. this._isEnabled = value;
  33219. },
  33220. enumerable: true,
  33221. configurable: true
  33222. });
  33223. LensFlareSystem.prototype.getScene = function () {
  33224. return this._scene;
  33225. };
  33226. LensFlareSystem.prototype.getEmitter = function () {
  33227. return this._emitter;
  33228. };
  33229. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33230. this._emitter = newEmitter;
  33231. };
  33232. LensFlareSystem.prototype.getEmitterPosition = function () {
  33233. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33234. };
  33235. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33236. var position = this.getEmitterPosition();
  33237. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33238. this._positionX = position.x;
  33239. this._positionY = position.y;
  33240. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33241. if (position.z > 0) {
  33242. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33243. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33244. return true;
  33245. }
  33246. }
  33247. return false;
  33248. };
  33249. LensFlareSystem.prototype._isVisible = function () {
  33250. if (!this._isEnabled) {
  33251. return false;
  33252. }
  33253. var emitterPosition = this.getEmitterPosition();
  33254. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33255. var distance = direction.length();
  33256. direction.normalize();
  33257. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33258. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33259. return !pickInfo.hit || pickInfo.distance > distance;
  33260. };
  33261. LensFlareSystem.prototype.render = function () {
  33262. if (!this._effect.isReady())
  33263. return false;
  33264. var engine = this._scene.getEngine();
  33265. var viewport = this._scene.activeCamera.viewport;
  33266. var globalViewport = viewport.toScreenGlobal(engine);
  33267. // Position
  33268. if (!this.computeEffectivePosition(globalViewport)) {
  33269. return false;
  33270. }
  33271. // Visibility
  33272. if (!this._isVisible()) {
  33273. return false;
  33274. }
  33275. // Intensity
  33276. var awayX;
  33277. var awayY;
  33278. if (this._positionX < this.borderLimit + globalViewport.x) {
  33279. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33280. }
  33281. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33282. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33283. }
  33284. else {
  33285. awayX = 0;
  33286. }
  33287. if (this._positionY < this.borderLimit + globalViewport.y) {
  33288. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33289. }
  33290. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33291. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33292. }
  33293. else {
  33294. awayY = 0;
  33295. }
  33296. var away = (awayX > awayY) ? awayX : awayY;
  33297. if (away > this.borderLimit) {
  33298. away = this.borderLimit;
  33299. }
  33300. var intensity = 1.0 - (away / this.borderLimit);
  33301. if (intensity < 0) {
  33302. return false;
  33303. }
  33304. if (intensity > 1.0) {
  33305. intensity = 1.0;
  33306. }
  33307. // Position
  33308. var centerX = globalViewport.x + globalViewport.width / 2;
  33309. var centerY = globalViewport.y + globalViewport.height / 2;
  33310. var distX = centerX - this._positionX;
  33311. var distY = centerY - this._positionY;
  33312. // Effects
  33313. engine.enableEffect(this._effect);
  33314. engine.setState(false);
  33315. engine.setDepthBuffer(false);
  33316. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33317. // VBOs
  33318. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  33319. // Flares
  33320. for (var index = 0; index < this.lensFlares.length; index++) {
  33321. var flare = this.lensFlares[index];
  33322. var x = centerX - (distX * flare.position);
  33323. var y = centerY - (distY * flare.position);
  33324. var cw = flare.size;
  33325. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  33326. var cx = 2 * (x / globalViewport.width) - 1.0;
  33327. var cy = 1.0 - 2 * (y / globalViewport.height);
  33328. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  33329. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  33330. // Texture
  33331. this._effect.setTexture("textureSampler", flare.texture);
  33332. // Color
  33333. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  33334. // Draw order
  33335. engine.draw(true, 0, 6);
  33336. }
  33337. engine.setDepthBuffer(true);
  33338. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33339. return true;
  33340. };
  33341. LensFlareSystem.prototype.dispose = function () {
  33342. if (this._vertexBuffer) {
  33343. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  33344. this._vertexBuffer = null;
  33345. }
  33346. if (this._indexBuffer) {
  33347. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33348. this._indexBuffer = null;
  33349. }
  33350. while (this.lensFlares.length) {
  33351. this.lensFlares[0].dispose();
  33352. }
  33353. // Remove from scene
  33354. var index = this._scene.lensFlareSystems.indexOf(this);
  33355. this._scene.lensFlareSystems.splice(index, 1);
  33356. };
  33357. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  33358. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  33359. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  33360. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  33361. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  33362. var parsedFlare = parsedLensFlareSystem.flares[index];
  33363. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  33364. }
  33365. return lensFlareSystem;
  33366. };
  33367. LensFlareSystem.prototype.serialize = function () {
  33368. var serializationObject = {};
  33369. serializationObject.emitterId = this.getEmitter().id;
  33370. serializationObject.borderLimit = this.borderLimit;
  33371. serializationObject.flares = [];
  33372. for (var index = 0; index < this.lensFlares.length; index++) {
  33373. var flare = this.lensFlares[index];
  33374. serializationObject.flares.push({
  33375. size: flare.size,
  33376. position: flare.position,
  33377. color: flare.color.asArray(),
  33378. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  33379. });
  33380. }
  33381. return serializationObject;
  33382. };
  33383. return LensFlareSystem;
  33384. })();
  33385. BABYLON.LensFlareSystem = LensFlareSystem;
  33386. })(BABYLON || (BABYLON = {}));
  33387. var BABYLON;
  33388. (function (BABYLON) {
  33389. // We're mainly based on the logic defined into the FreeCamera code
  33390. var DeviceOrientationCamera = (function (_super) {
  33391. __extends(DeviceOrientationCamera, _super);
  33392. function DeviceOrientationCamera(name, position, scene) {
  33393. var _this = this;
  33394. _super.call(this, name, position, scene);
  33395. this._offsetX = null;
  33396. this._offsetY = null;
  33397. this._orientationGamma = 0;
  33398. this._orientationBeta = 0;
  33399. this._initialOrientationGamma = 0;
  33400. this._initialOrientationBeta = 0;
  33401. this.angularSensibility = 10000.0;
  33402. this.moveSensibility = 50.0;
  33403. window.addEventListener("resize", function () {
  33404. _this._initialOrientationGamma = null;
  33405. }, false);
  33406. }
  33407. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33408. var _this = this;
  33409. if (this._attachedCanvas) {
  33410. return;
  33411. }
  33412. this._attachedCanvas = canvas;
  33413. if (!this._orientationChanged) {
  33414. this._orientationChanged = function (evt) {
  33415. if (!_this._initialOrientationGamma) {
  33416. _this._initialOrientationGamma = evt.gamma;
  33417. _this._initialOrientationBeta = evt.beta;
  33418. }
  33419. _this._orientationGamma = evt.gamma;
  33420. _this._orientationBeta = evt.beta;
  33421. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33422. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33423. };
  33424. }
  33425. window.addEventListener("deviceorientation", this._orientationChanged);
  33426. };
  33427. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33428. if (this._attachedCanvas !== canvas) {
  33429. return;
  33430. }
  33431. window.removeEventListener("deviceorientation", this._orientationChanged);
  33432. this._attachedCanvas = null;
  33433. this._orientationGamma = 0;
  33434. this._orientationBeta = 0;
  33435. this._initialOrientationGamma = 0;
  33436. this._initialOrientationBeta = 0;
  33437. };
  33438. DeviceOrientationCamera.prototype._checkInputs = function () {
  33439. if (!this._offsetX) {
  33440. return;
  33441. }
  33442. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33443. var speed = this._computeLocalCameraSpeed();
  33444. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33445. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33446. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33447. _super.prototype._checkInputs.call(this);
  33448. };
  33449. return DeviceOrientationCamera;
  33450. })(BABYLON.FreeCamera);
  33451. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33452. })(BABYLON || (BABYLON = {}));
  33453. var BABYLON;
  33454. (function (BABYLON) {
  33455. var Gamepads = (function () {
  33456. function Gamepads(ongamedpadconnected) {
  33457. var _this = this;
  33458. this.babylonGamepads = [];
  33459. this.oneGamepadConnected = false;
  33460. this.isMonitoring = false;
  33461. this.gamepadEventSupported = 'GamepadEvent' in window;
  33462. this.gamepadSupportAvailable = (navigator.getGamepads ||
  33463. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  33464. 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=";
  33465. this._callbackGamepadConnected = ongamedpadconnected;
  33466. if (this.gamepadSupportAvailable) {
  33467. // Checking if the gamepad connected event is supported (like in Firefox)
  33468. if (this.gamepadEventSupported) {
  33469. window.addEventListener('gamepadconnected', function (evt) {
  33470. _this._onGamepadConnected(evt);
  33471. }, false);
  33472. window.addEventListener('gamepaddisconnected', function (evt) {
  33473. _this._onGamepadDisconnected(evt);
  33474. }, false);
  33475. }
  33476. else {
  33477. this._startMonitoringGamepads();
  33478. }
  33479. if (!this.oneGamepadConnected) {
  33480. this._insertGamepadDOMInstructions();
  33481. }
  33482. }
  33483. else {
  33484. this._insertGamepadDOMNotSupported();
  33485. }
  33486. }
  33487. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33488. Gamepads.gamepadDOMInfo = document.createElement("div");
  33489. var buttonAImage = document.createElement("img");
  33490. buttonAImage.src = this.buttonADataURL;
  33491. var spanMessage = document.createElement("span");
  33492. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33493. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33494. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33495. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33496. Gamepads.gamepadDOMInfo.style.width = "100%";
  33497. Gamepads.gamepadDOMInfo.style.height = "48px";
  33498. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33499. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33500. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33501. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33502. buttonAImage.style.position = "relative";
  33503. buttonAImage.style.bottom = "8px";
  33504. spanMessage.style.position = "relative";
  33505. spanMessage.style.fontSize = "32px";
  33506. spanMessage.style.bottom = "32px";
  33507. spanMessage.style.color = "green";
  33508. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33509. };
  33510. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33511. Gamepads.gamepadDOMInfo = document.createElement("div");
  33512. var spanMessage = document.createElement("span");
  33513. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33514. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33515. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33516. Gamepads.gamepadDOMInfo.style.width = "100%";
  33517. Gamepads.gamepadDOMInfo.style.height = "40px";
  33518. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33519. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33520. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33521. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33522. spanMessage.style.position = "relative";
  33523. spanMessage.style.fontSize = "32px";
  33524. spanMessage.style.color = "red";
  33525. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33526. };
  33527. Gamepads.prototype.dispose = function () {
  33528. if (Gamepads.gamepadDOMInfo) {
  33529. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33530. }
  33531. };
  33532. Gamepads.prototype._onGamepadConnected = function (evt) {
  33533. var newGamepad = this._addNewGamepad(evt.gamepad);
  33534. if (this._callbackGamepadConnected)
  33535. this._callbackGamepadConnected(newGamepad);
  33536. this._startMonitoringGamepads();
  33537. };
  33538. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33539. if (!this.oneGamepadConnected) {
  33540. this.oneGamepadConnected = true;
  33541. if (Gamepads.gamepadDOMInfo) {
  33542. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33543. Gamepads.gamepadDOMInfo = null;
  33544. }
  33545. }
  33546. var newGamepad;
  33547. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33548. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33549. }
  33550. else {
  33551. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33552. }
  33553. this.babylonGamepads.push(newGamepad);
  33554. return newGamepad;
  33555. };
  33556. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33557. // Remove the gamepad from the list of gamepads to monitor.
  33558. for (var i in this.babylonGamepads) {
  33559. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33560. this.babylonGamepads.splice(i, 1);
  33561. break;
  33562. }
  33563. }
  33564. // If no gamepads are left, stop the polling loop.
  33565. if (this.babylonGamepads.length == 0) {
  33566. this._stopMonitoringGamepads();
  33567. }
  33568. };
  33569. Gamepads.prototype._startMonitoringGamepads = function () {
  33570. if (!this.isMonitoring) {
  33571. this.isMonitoring = true;
  33572. this._checkGamepadsStatus();
  33573. }
  33574. };
  33575. Gamepads.prototype._stopMonitoringGamepads = function () {
  33576. this.isMonitoring = false;
  33577. };
  33578. Gamepads.prototype._checkGamepadsStatus = function () {
  33579. var _this = this;
  33580. // updating gamepad objects
  33581. this._updateGamepadObjects();
  33582. for (var i in this.babylonGamepads) {
  33583. this.babylonGamepads[i].update();
  33584. }
  33585. if (this.isMonitoring) {
  33586. if (window.requestAnimationFrame) {
  33587. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33588. }
  33589. else if (window.mozRequestAnimationFrame) {
  33590. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33591. }
  33592. else if (window.webkitRequestAnimationFrame) {
  33593. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33594. }
  33595. }
  33596. };
  33597. // This function is called only on Chrome, which does not yet support
  33598. // connection/disconnection events, but requires you to monitor
  33599. // an array for changes.
  33600. Gamepads.prototype._updateGamepadObjects = function () {
  33601. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33602. for (var i = 0; i < gamepads.length; i++) {
  33603. if (gamepads[i]) {
  33604. if (!(gamepads[i].index in this.babylonGamepads)) {
  33605. var newGamepad = this._addNewGamepad(gamepads[i]);
  33606. if (this._callbackGamepadConnected) {
  33607. this._callbackGamepadConnected(newGamepad);
  33608. }
  33609. }
  33610. else {
  33611. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33612. }
  33613. }
  33614. }
  33615. };
  33616. return Gamepads;
  33617. })();
  33618. BABYLON.Gamepads = Gamepads;
  33619. var StickValues = (function () {
  33620. function StickValues(x, y) {
  33621. this.x = x;
  33622. this.y = y;
  33623. }
  33624. return StickValues;
  33625. })();
  33626. BABYLON.StickValues = StickValues;
  33627. var Gamepad = (function () {
  33628. function Gamepad(id, index, browserGamepad) {
  33629. this.id = id;
  33630. this.index = index;
  33631. this.browserGamepad = browserGamepad;
  33632. if (this.browserGamepad.axes.length >= 2) {
  33633. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33634. }
  33635. if (this.browserGamepad.axes.length >= 4) {
  33636. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33637. }
  33638. }
  33639. Gamepad.prototype.onleftstickchanged = function (callback) {
  33640. this._onleftstickchanged = callback;
  33641. };
  33642. Gamepad.prototype.onrightstickchanged = function (callback) {
  33643. this._onrightstickchanged = callback;
  33644. };
  33645. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33646. get: function () {
  33647. return this._leftStick;
  33648. },
  33649. set: function (newValues) {
  33650. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33651. this._onleftstickchanged(newValues);
  33652. }
  33653. this._leftStick = newValues;
  33654. },
  33655. enumerable: true,
  33656. configurable: true
  33657. });
  33658. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33659. get: function () {
  33660. return this._rightStick;
  33661. },
  33662. set: function (newValues) {
  33663. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33664. this._onrightstickchanged(newValues);
  33665. }
  33666. this._rightStick = newValues;
  33667. },
  33668. enumerable: true,
  33669. configurable: true
  33670. });
  33671. Gamepad.prototype.update = function () {
  33672. if (this._leftStick) {
  33673. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33674. }
  33675. if (this._rightStick) {
  33676. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33677. }
  33678. };
  33679. return Gamepad;
  33680. })();
  33681. BABYLON.Gamepad = Gamepad;
  33682. var GenericPad = (function (_super) {
  33683. __extends(GenericPad, _super);
  33684. function GenericPad(id, index, gamepad) {
  33685. _super.call(this, id, index, gamepad);
  33686. this.id = id;
  33687. this.index = index;
  33688. this.gamepad = gamepad;
  33689. this._buttons = new Array(gamepad.buttons.length);
  33690. }
  33691. GenericPad.prototype.onbuttondown = function (callback) {
  33692. this._onbuttondown = callback;
  33693. };
  33694. GenericPad.prototype.onbuttonup = function (callback) {
  33695. this._onbuttonup = callback;
  33696. };
  33697. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33698. if (newValue !== currentValue) {
  33699. if (this._onbuttondown && newValue === 1) {
  33700. this._onbuttondown(buttonIndex);
  33701. }
  33702. if (this._onbuttonup && newValue === 0) {
  33703. this._onbuttonup(buttonIndex);
  33704. }
  33705. }
  33706. return newValue;
  33707. };
  33708. GenericPad.prototype.update = function () {
  33709. _super.prototype.update.call(this);
  33710. for (var index = 0; index < this._buttons.length; index++) {
  33711. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33712. }
  33713. };
  33714. return GenericPad;
  33715. })(Gamepad);
  33716. BABYLON.GenericPad = GenericPad;
  33717. (function (Xbox360Button) {
  33718. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33719. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33720. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33721. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33722. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33723. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33724. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33725. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33726. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33727. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33728. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33729. var Xbox360Button = BABYLON.Xbox360Button;
  33730. (function (Xbox360Dpad) {
  33731. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33732. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33733. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33734. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33735. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33736. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33737. var Xbox360Pad = (function (_super) {
  33738. __extends(Xbox360Pad, _super);
  33739. function Xbox360Pad() {
  33740. _super.apply(this, arguments);
  33741. this._leftTrigger = 0;
  33742. this._rightTrigger = 0;
  33743. this._buttonA = 0;
  33744. this._buttonB = 0;
  33745. this._buttonX = 0;
  33746. this._buttonY = 0;
  33747. this._buttonBack = 0;
  33748. this._buttonStart = 0;
  33749. this._buttonLB = 0;
  33750. this._buttonRB = 0;
  33751. this._buttonLeftStick = 0;
  33752. this._buttonRightStick = 0;
  33753. this._dPadUp = 0;
  33754. this._dPadDown = 0;
  33755. this._dPadLeft = 0;
  33756. this._dPadRight = 0;
  33757. }
  33758. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33759. this._onlefttriggerchanged = callback;
  33760. };
  33761. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33762. this._onrighttriggerchanged = callback;
  33763. };
  33764. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33765. get: function () {
  33766. return this._leftTrigger;
  33767. },
  33768. set: function (newValue) {
  33769. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33770. this._onlefttriggerchanged(newValue);
  33771. }
  33772. this._leftTrigger = newValue;
  33773. },
  33774. enumerable: true,
  33775. configurable: true
  33776. });
  33777. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33778. get: function () {
  33779. return this._rightTrigger;
  33780. },
  33781. set: function (newValue) {
  33782. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33783. this._onrighttriggerchanged(newValue);
  33784. }
  33785. this._rightTrigger = newValue;
  33786. },
  33787. enumerable: true,
  33788. configurable: true
  33789. });
  33790. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33791. this._onbuttondown = callback;
  33792. };
  33793. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33794. this._onbuttonup = callback;
  33795. };
  33796. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33797. this._ondpaddown = callback;
  33798. };
  33799. Xbox360Pad.prototype.ondpadup = function (callback) {
  33800. this._ondpadup = callback;
  33801. };
  33802. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33803. if (newValue !== currentValue) {
  33804. if (this._onbuttondown && newValue === 1) {
  33805. this._onbuttondown(buttonType);
  33806. }
  33807. if (this._onbuttonup && newValue === 0) {
  33808. this._onbuttonup(buttonType);
  33809. }
  33810. }
  33811. return newValue;
  33812. };
  33813. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33814. if (newValue !== currentValue) {
  33815. if (this._ondpaddown && newValue === 1) {
  33816. this._ondpaddown(buttonType);
  33817. }
  33818. if (this._ondpadup && newValue === 0) {
  33819. this._ondpadup(buttonType);
  33820. }
  33821. }
  33822. return newValue;
  33823. };
  33824. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33825. get: function () {
  33826. return this._buttonA;
  33827. },
  33828. set: function (value) {
  33829. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33830. },
  33831. enumerable: true,
  33832. configurable: true
  33833. });
  33834. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33835. get: function () {
  33836. return this._buttonB;
  33837. },
  33838. set: function (value) {
  33839. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33840. },
  33841. enumerable: true,
  33842. configurable: true
  33843. });
  33844. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33845. get: function () {
  33846. return this._buttonX;
  33847. },
  33848. set: function (value) {
  33849. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33850. },
  33851. enumerable: true,
  33852. configurable: true
  33853. });
  33854. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33855. get: function () {
  33856. return this._buttonY;
  33857. },
  33858. set: function (value) {
  33859. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33860. },
  33861. enumerable: true,
  33862. configurable: true
  33863. });
  33864. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33865. get: function () {
  33866. return this._buttonStart;
  33867. },
  33868. set: function (value) {
  33869. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33870. },
  33871. enumerable: true,
  33872. configurable: true
  33873. });
  33874. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33875. get: function () {
  33876. return this._buttonBack;
  33877. },
  33878. set: function (value) {
  33879. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33880. },
  33881. enumerable: true,
  33882. configurable: true
  33883. });
  33884. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33885. get: function () {
  33886. return this._buttonLB;
  33887. },
  33888. set: function (value) {
  33889. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33890. },
  33891. enumerable: true,
  33892. configurable: true
  33893. });
  33894. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33895. get: function () {
  33896. return this._buttonRB;
  33897. },
  33898. set: function (value) {
  33899. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33900. },
  33901. enumerable: true,
  33902. configurable: true
  33903. });
  33904. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33905. get: function () {
  33906. return this._buttonLeftStick;
  33907. },
  33908. set: function (value) {
  33909. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33910. },
  33911. enumerable: true,
  33912. configurable: true
  33913. });
  33914. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33915. get: function () {
  33916. return this._buttonRightStick;
  33917. },
  33918. set: function (value) {
  33919. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33920. },
  33921. enumerable: true,
  33922. configurable: true
  33923. });
  33924. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33925. get: function () {
  33926. return this._dPadUp;
  33927. },
  33928. set: function (value) {
  33929. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33930. },
  33931. enumerable: true,
  33932. configurable: true
  33933. });
  33934. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33935. get: function () {
  33936. return this._dPadDown;
  33937. },
  33938. set: function (value) {
  33939. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33940. },
  33941. enumerable: true,
  33942. configurable: true
  33943. });
  33944. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33945. get: function () {
  33946. return this._dPadLeft;
  33947. },
  33948. set: function (value) {
  33949. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33950. },
  33951. enumerable: true,
  33952. configurable: true
  33953. });
  33954. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33955. get: function () {
  33956. return this._dPadRight;
  33957. },
  33958. set: function (value) {
  33959. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33960. },
  33961. enumerable: true,
  33962. configurable: true
  33963. });
  33964. Xbox360Pad.prototype.update = function () {
  33965. _super.prototype.update.call(this);
  33966. this.buttonA = this.browserGamepad.buttons[0].value;
  33967. this.buttonB = this.browserGamepad.buttons[1].value;
  33968. this.buttonX = this.browserGamepad.buttons[2].value;
  33969. this.buttonY = this.browserGamepad.buttons[3].value;
  33970. this.buttonLB = this.browserGamepad.buttons[4].value;
  33971. this.buttonRB = this.browserGamepad.buttons[5].value;
  33972. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33973. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33974. this.buttonBack = this.browserGamepad.buttons[8].value;
  33975. this.buttonStart = this.browserGamepad.buttons[9].value;
  33976. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33977. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33978. this.dPadUp = this.browserGamepad.buttons[12].value;
  33979. this.dPadDown = this.browserGamepad.buttons[13].value;
  33980. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33981. this.dPadRight = this.browserGamepad.buttons[15].value;
  33982. };
  33983. return Xbox360Pad;
  33984. })(Gamepad);
  33985. BABYLON.Xbox360Pad = Xbox360Pad;
  33986. })(BABYLON || (BABYLON = {}));
  33987. var BABYLON;
  33988. (function (BABYLON) {
  33989. // We're mainly based on the logic defined into the FreeCamera code
  33990. var GamepadCamera = (function (_super) {
  33991. __extends(GamepadCamera, _super);
  33992. function GamepadCamera(name, position, scene) {
  33993. var _this = this;
  33994. _super.call(this, name, position, scene);
  33995. this.angularSensibility = 200;
  33996. this.moveSensibility = 75;
  33997. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33998. }
  33999. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  34000. // Only the first gamepad can control the camera
  34001. if (gamepad.index === 0) {
  34002. this._gamepad = gamepad;
  34003. }
  34004. };
  34005. GamepadCamera.prototype._checkInputs = function () {
  34006. if (this._gamepad) {
  34007. var LSValues = this._gamepad.leftStick;
  34008. var normalizedLX = LSValues.x / this.moveSensibility;
  34009. var normalizedLY = LSValues.y / this.moveSensibility;
  34010. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  34011. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  34012. var RSValues = this._gamepad.rightStick;
  34013. var normalizedRX = RSValues.x / this.angularSensibility;
  34014. var normalizedRY = RSValues.y / this.angularSensibility;
  34015. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  34016. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  34017. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  34018. var speed = this._computeLocalCameraSpeed() * 50.0;
  34019. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  34020. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  34021. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  34022. }
  34023. _super.prototype._checkInputs.call(this);
  34024. };
  34025. GamepadCamera.prototype.dispose = function () {
  34026. this._gamepads.dispose();
  34027. _super.prototype.dispose.call(this);
  34028. };
  34029. return GamepadCamera;
  34030. })(BABYLON.FreeCamera);
  34031. BABYLON.GamepadCamera = GamepadCamera;
  34032. })(BABYLON || (BABYLON = {}));
  34033. var BABYLON;
  34034. (function (BABYLON) {
  34035. var Analyser = (function () {
  34036. function Analyser(scene) {
  34037. this.SMOOTHING = 0.75;
  34038. this.FFT_SIZE = 512;
  34039. this.BARGRAPHAMPLITUDE = 256;
  34040. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34041. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34042. this._scene = scene;
  34043. this._audioEngine = BABYLON.Engine.audioEngine;
  34044. if (this._audioEngine.canUseWebAudio) {
  34045. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34046. this._webAudioAnalyser.minDecibels = -140;
  34047. this._webAudioAnalyser.maxDecibels = 0;
  34048. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34049. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34050. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34051. }
  34052. }
  34053. Analyser.prototype.getFrequencyBinCount = function () {
  34054. if (this._audioEngine.canUseWebAudio) {
  34055. return this._webAudioAnalyser.frequencyBinCount;
  34056. }
  34057. else {
  34058. return 0;
  34059. }
  34060. };
  34061. Analyser.prototype.getByteFrequencyData = function () {
  34062. if (this._audioEngine.canUseWebAudio) {
  34063. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34064. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34065. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34066. }
  34067. return this._byteFreqs;
  34068. };
  34069. Analyser.prototype.getByteTimeDomainData = function () {
  34070. if (this._audioEngine.canUseWebAudio) {
  34071. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34072. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34073. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34074. }
  34075. return this._byteTime;
  34076. };
  34077. Analyser.prototype.getFloatFrequencyData = function () {
  34078. if (this._audioEngine.canUseWebAudio) {
  34079. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34080. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34081. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34082. }
  34083. return this._floatFreqs;
  34084. };
  34085. Analyser.prototype.drawDebugCanvas = function () {
  34086. var _this = this;
  34087. if (this._audioEngine.canUseWebAudio) {
  34088. if (!this._debugCanvas) {
  34089. this._debugCanvas = document.createElement("canvas");
  34090. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34091. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34092. this._debugCanvas.style.position = "absolute";
  34093. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34094. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34095. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34096. document.body.appendChild(this._debugCanvas);
  34097. this._registerFunc = function () {
  34098. _this.drawDebugCanvas();
  34099. };
  34100. this._scene.registerBeforeRender(this._registerFunc);
  34101. }
  34102. if (this._registerFunc) {
  34103. var workingArray = this.getByteFrequencyData();
  34104. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34105. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34106. // Draw the frequency domain chart.
  34107. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34108. var value = workingArray[i];
  34109. var percent = value / this.BARGRAPHAMPLITUDE;
  34110. var height = this.DEBUGCANVASSIZE.height * percent;
  34111. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34112. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34113. var hue = i / this.getFrequencyBinCount() * 360;
  34114. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34115. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34116. }
  34117. }
  34118. }
  34119. };
  34120. Analyser.prototype.stopDebugCanvas = function () {
  34121. if (this._debugCanvas) {
  34122. this._scene.unregisterBeforeRender(this._registerFunc);
  34123. this._registerFunc = null;
  34124. document.body.removeChild(this._debugCanvas);
  34125. this._debugCanvas = null;
  34126. this._debugCanvasContext = null;
  34127. }
  34128. };
  34129. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34130. if (this._audioEngine.canUseWebAudio) {
  34131. inputAudioNode.connect(this._webAudioAnalyser);
  34132. this._webAudioAnalyser.connect(outputAudioNode);
  34133. }
  34134. };
  34135. Analyser.prototype.dispose = function () {
  34136. if (this._audioEngine.canUseWebAudio) {
  34137. this._webAudioAnalyser.disconnect();
  34138. }
  34139. };
  34140. return Analyser;
  34141. })();
  34142. BABYLON.Analyser = Analyser;
  34143. })(BABYLON || (BABYLON = {}));
  34144. var BABYLON;
  34145. (function (BABYLON) {
  34146. var AudioEngine = (function () {
  34147. function AudioEngine() {
  34148. this._audioContext = null;
  34149. this._audioContextInitialized = false;
  34150. this.canUseWebAudio = false;
  34151. this.WarnedWebAudioUnsupported = false;
  34152. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34153. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34154. this.canUseWebAudio = true;
  34155. }
  34156. }
  34157. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34158. get: function () {
  34159. if (!this._audioContextInitialized) {
  34160. this._initializeAudioContext();
  34161. }
  34162. return this._audioContext;
  34163. },
  34164. enumerable: true,
  34165. configurable: true
  34166. });
  34167. AudioEngine.prototype._initializeAudioContext = function () {
  34168. try {
  34169. if (this.canUseWebAudio) {
  34170. this._audioContext = new AudioContext();
  34171. // create a global volume gain node
  34172. this.masterGain = this._audioContext.createGain();
  34173. this.masterGain.gain.value = 1;
  34174. this.masterGain.connect(this._audioContext.destination);
  34175. this._audioContextInitialized = true;
  34176. }
  34177. }
  34178. catch (e) {
  34179. this.canUseWebAudio = false;
  34180. BABYLON.Tools.Error("Web Audio: " + e.message);
  34181. }
  34182. };
  34183. AudioEngine.prototype.dispose = function () {
  34184. if (this.canUseWebAudio && this._audioContextInitialized) {
  34185. if (this._connectedAnalyser) {
  34186. this._connectedAnalyser.stopDebugCanvas();
  34187. this._connectedAnalyser.dispose();
  34188. this.masterGain.disconnect();
  34189. this.masterGain.connect(this._audioContext.destination);
  34190. this._connectedAnalyser = null;
  34191. }
  34192. this.masterGain.gain.value = 1;
  34193. }
  34194. this.WarnedWebAudioUnsupported = false;
  34195. };
  34196. AudioEngine.prototype.getGlobalVolume = function () {
  34197. if (this.canUseWebAudio && this._audioContextInitialized) {
  34198. return this.masterGain.gain.value;
  34199. }
  34200. else {
  34201. return -1;
  34202. }
  34203. };
  34204. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34205. if (this.canUseWebAudio && this._audioContextInitialized) {
  34206. this.masterGain.gain.value = newVolume;
  34207. }
  34208. };
  34209. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34210. if (this._connectedAnalyser) {
  34211. this._connectedAnalyser.stopDebugCanvas();
  34212. }
  34213. if (this.canUseWebAudio && this._audioContextInitialized) {
  34214. this._connectedAnalyser = analyser;
  34215. this.masterGain.disconnect();
  34216. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34217. }
  34218. };
  34219. return AudioEngine;
  34220. })();
  34221. BABYLON.AudioEngine = AudioEngine;
  34222. })(BABYLON || (BABYLON = {}));
  34223. var BABYLON;
  34224. (function (BABYLON) {
  34225. var Sound = (function () {
  34226. /**
  34227. * Create a sound and attach it to a scene
  34228. * @param name Name of your sound
  34229. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34230. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34231. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34232. */
  34233. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34234. var _this = this;
  34235. this.autoplay = false;
  34236. this.loop = false;
  34237. this.useCustomAttenuation = false;
  34238. this.spatialSound = false;
  34239. this.refDistance = 1;
  34240. this.rolloffFactor = 1;
  34241. this.maxDistance = 100;
  34242. this.distanceModel = "linear";
  34243. this._panningModel = "equalpower";
  34244. this._playbackRate = 1;
  34245. this._streaming = false;
  34246. this._startTime = 0;
  34247. this._startOffset = 0;
  34248. this._position = BABYLON.Vector3.Zero();
  34249. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34250. this._volume = 1;
  34251. this._isLoaded = false;
  34252. this._isReadyToPlay = false;
  34253. this.isPlaying = false;
  34254. this.isPaused = false;
  34255. this._isDirectional = false;
  34256. // Used if you'd like to create a directional sound.
  34257. // If not set, the sound will be omnidirectional
  34258. this._coneInnerAngle = 360;
  34259. this._coneOuterAngle = 360;
  34260. this._coneOuterGain = 0;
  34261. this._isOutputConnected = false;
  34262. this.name = name;
  34263. this._scene = scene;
  34264. this._readyToPlayCallback = readyToPlayCallback;
  34265. // Default custom attenuation function is a linear attenuation
  34266. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34267. if (currentDistance < maxDistance) {
  34268. return currentVolume * (1 - currentDistance / maxDistance);
  34269. }
  34270. else {
  34271. return 0;
  34272. }
  34273. };
  34274. if (options) {
  34275. this.autoplay = options.autoplay || false;
  34276. this.loop = options.loop || false;
  34277. // if volume === 0, we need another way to check this option
  34278. if (options.volume !== undefined) {
  34279. this._volume = options.volume;
  34280. }
  34281. this.spatialSound = options.spatialSound || false;
  34282. this.maxDistance = options.maxDistance || 100;
  34283. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34284. this.rolloffFactor = options.rolloffFactor || 1;
  34285. this.refDistance = options.refDistance || 1;
  34286. this.distanceModel = options.distanceModel || "linear";
  34287. this._playbackRate = options.playbackRate || 1;
  34288. this._streaming = options.streaming || false;
  34289. }
  34290. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34291. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34292. this._soundGain.gain.value = this._volume;
  34293. this._inputAudioNode = this._soundGain;
  34294. this._ouputAudioNode = this._soundGain;
  34295. if (this.spatialSound) {
  34296. this._createSpatialParameters();
  34297. }
  34298. this._scene.mainSoundTrack.AddSound(this);
  34299. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34300. if (urlOrArrayBuffer) {
  34301. // If it's an URL
  34302. if (typeof (urlOrArrayBuffer) === "string") {
  34303. // Loading sound using XHR2
  34304. if (!this._streaming) {
  34305. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  34306. }
  34307. else {
  34308. this._htmlAudioElement = new Audio();
  34309. this._htmlAudioElement.src = urlOrArrayBuffer;
  34310. this._htmlAudioElement.controls = false;
  34311. this._htmlAudioElement.loop = this.loop;
  34312. this._htmlAudioElement.crossOrigin = "anonymous";
  34313. this._isReadyToPlay = true;
  34314. document.body.appendChild(this._htmlAudioElement);
  34315. // Simulating a ready to play event for consistent behavior with non streamed audio source
  34316. if (this._readyToPlayCallback) {
  34317. window.setTimeout(function () {
  34318. _this._readyToPlayCallback();
  34319. }, 1000);
  34320. }
  34321. if (this.autoplay) {
  34322. this.play();
  34323. }
  34324. }
  34325. }
  34326. else {
  34327. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34328. if (urlOrArrayBuffer.byteLength > 0) {
  34329. this._soundLoaded(urlOrArrayBuffer);
  34330. }
  34331. }
  34332. else {
  34333. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34334. }
  34335. }
  34336. }
  34337. }
  34338. else {
  34339. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34340. this._scene.mainSoundTrack.AddSound(this);
  34341. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34342. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34343. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34344. }
  34345. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34346. if (this._readyToPlayCallback) {
  34347. window.setTimeout(function () {
  34348. _this._readyToPlayCallback();
  34349. }, 1000);
  34350. }
  34351. }
  34352. }
  34353. Sound.prototype.dispose = function () {
  34354. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34355. if (this.isPlaying) {
  34356. this.stop();
  34357. }
  34358. this._isReadyToPlay = false;
  34359. if (this.soundTrackId === -1) {
  34360. this._scene.mainSoundTrack.RemoveSound(this);
  34361. }
  34362. else {
  34363. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34364. }
  34365. if (this._soundGain) {
  34366. this._soundGain.disconnect();
  34367. this._soundGain = null;
  34368. }
  34369. if (this._soundPanner) {
  34370. this._soundPanner.disconnect();
  34371. this._soundPanner = null;
  34372. }
  34373. if (this._soundSource) {
  34374. this._soundSource.disconnect();
  34375. this._soundSource = null;
  34376. }
  34377. this._audioBuffer = null;
  34378. if (this._htmlAudioElement) {
  34379. this._htmlAudioElement.pause();
  34380. this._htmlAudioElement.src = "";
  34381. document.body.removeChild(this._htmlAudioElement);
  34382. }
  34383. if (this._connectedMesh) {
  34384. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34385. this._connectedMesh = null;
  34386. }
  34387. }
  34388. };
  34389. Sound.prototype._soundLoaded = function (audioData) {
  34390. var _this = this;
  34391. this._isLoaded = true;
  34392. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34393. _this._audioBuffer = buffer;
  34394. _this._isReadyToPlay = true;
  34395. if (_this.autoplay) {
  34396. _this.play();
  34397. }
  34398. if (_this._readyToPlayCallback) {
  34399. _this._readyToPlayCallback();
  34400. }
  34401. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34402. };
  34403. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34404. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34405. this._audioBuffer = audioBuffer;
  34406. this._isReadyToPlay = true;
  34407. }
  34408. };
  34409. Sound.prototype.updateOptions = function (options) {
  34410. if (options) {
  34411. this.loop = options.loop || this.loop;
  34412. this.maxDistance = options.maxDistance || this.maxDistance;
  34413. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34414. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34415. this.refDistance = options.refDistance || this.refDistance;
  34416. this.distanceModel = options.distanceModel || this.distanceModel;
  34417. this._playbackRate = options.playbackRate || this._playbackRate;
  34418. this._updateSpatialParameters();
  34419. if (this.isPlaying) {
  34420. if (this._streaming) {
  34421. this._htmlAudioElement.playbackRate = this._playbackRate;
  34422. }
  34423. else {
  34424. this._soundSource.playbackRate.value = this._playbackRate;
  34425. }
  34426. }
  34427. }
  34428. };
  34429. Sound.prototype._createSpatialParameters = function () {
  34430. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34431. if (this._scene.headphone) {
  34432. this._panningModel = "HRTF";
  34433. }
  34434. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34435. this._updateSpatialParameters();
  34436. this._soundPanner.connect(this._ouputAudioNode);
  34437. this._inputAudioNode = this._soundPanner;
  34438. }
  34439. };
  34440. Sound.prototype._updateSpatialParameters = function () {
  34441. if (this.spatialSound) {
  34442. if (this.useCustomAttenuation) {
  34443. // Tricks to disable in a way embedded Web Audio attenuation
  34444. this._soundPanner.distanceModel = "linear";
  34445. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34446. this._soundPanner.refDistance = 1;
  34447. this._soundPanner.rolloffFactor = 1;
  34448. this._soundPanner.panningModel = this._panningModel;
  34449. }
  34450. else {
  34451. this._soundPanner.distanceModel = this.distanceModel;
  34452. this._soundPanner.maxDistance = this.maxDistance;
  34453. this._soundPanner.refDistance = this.refDistance;
  34454. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34455. this._soundPanner.panningModel = this._panningModel;
  34456. }
  34457. }
  34458. };
  34459. Sound.prototype.switchPanningModelToHRTF = function () {
  34460. this._panningModel = "HRTF";
  34461. this._switchPanningModel();
  34462. };
  34463. Sound.prototype.switchPanningModelToEqualPower = function () {
  34464. this._panningModel = "equalpower";
  34465. this._switchPanningModel();
  34466. };
  34467. Sound.prototype._switchPanningModel = function () {
  34468. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34469. this._soundPanner.panningModel = this._panningModel;
  34470. }
  34471. };
  34472. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34473. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34474. if (this._isOutputConnected) {
  34475. this._ouputAudioNode.disconnect();
  34476. }
  34477. this._ouputAudioNode.connect(soundTrackAudioNode);
  34478. this._isOutputConnected = true;
  34479. }
  34480. };
  34481. /**
  34482. * Transform this sound into a directional source
  34483. * @param coneInnerAngle Size of the inner cone in degree
  34484. * @param coneOuterAngle Size of the outer cone in degree
  34485. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34486. */
  34487. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34488. if (coneOuterAngle < coneInnerAngle) {
  34489. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34490. return;
  34491. }
  34492. this._coneInnerAngle = coneInnerAngle;
  34493. this._coneOuterAngle = coneOuterAngle;
  34494. this._coneOuterGain = coneOuterGain;
  34495. this._isDirectional = true;
  34496. if (this.isPlaying && this.loop) {
  34497. this.stop();
  34498. this.play();
  34499. }
  34500. };
  34501. Sound.prototype.setPosition = function (newPosition) {
  34502. this._position = newPosition;
  34503. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34504. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34505. }
  34506. };
  34507. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34508. this._localDirection = newLocalDirection;
  34509. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34510. this._updateDirection();
  34511. }
  34512. };
  34513. Sound.prototype._updateDirection = function () {
  34514. var mat = this._connectedMesh.getWorldMatrix();
  34515. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34516. direction.normalize();
  34517. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34518. };
  34519. Sound.prototype.updateDistanceFromListener = function () {
  34520. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34521. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34522. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34523. }
  34524. };
  34525. Sound.prototype.setAttenuationFunction = function (callback) {
  34526. this._customAttenuationFunction = callback;
  34527. };
  34528. /**
  34529. * Play the sound
  34530. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34531. */
  34532. Sound.prototype.play = function (time) {
  34533. var _this = this;
  34534. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34535. try {
  34536. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34537. if (!this._soundSource || !this._streamingSource) {
  34538. if (this.spatialSound) {
  34539. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34540. if (this._isDirectional) {
  34541. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34542. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34543. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34544. if (this._connectedMesh) {
  34545. this._updateDirection();
  34546. }
  34547. else {
  34548. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34549. }
  34550. }
  34551. }
  34552. }
  34553. if (this._streaming) {
  34554. if (!this._streamingSource) {
  34555. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34556. this._htmlAudioElement.onended = function () { _this._onended(); };
  34557. this._htmlAudioElement.playbackRate = this._playbackRate;
  34558. }
  34559. this._streamingSource.disconnect();
  34560. this._streamingSource.connect(this._inputAudioNode);
  34561. this._htmlAudioElement.play();
  34562. }
  34563. else {
  34564. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34565. this._soundSource.buffer = this._audioBuffer;
  34566. this._soundSource.connect(this._inputAudioNode);
  34567. this._soundSource.loop = this.loop;
  34568. this._soundSource.playbackRate.value = this._playbackRate;
  34569. this._soundSource.onended = function () { _this._onended(); };
  34570. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34571. }
  34572. this._startTime = startTime;
  34573. this.isPlaying = true;
  34574. this.isPaused = false;
  34575. }
  34576. catch (ex) {
  34577. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34578. }
  34579. }
  34580. };
  34581. Sound.prototype._onended = function () {
  34582. this.isPlaying = false;
  34583. if (this.onended) {
  34584. this.onended();
  34585. }
  34586. };
  34587. /**
  34588. * Stop the sound
  34589. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34590. */
  34591. Sound.prototype.stop = function (time) {
  34592. if (this.isPlaying) {
  34593. if (this._streaming) {
  34594. this._htmlAudioElement.pause();
  34595. // Test needed for Firefox or it will generate an Invalid State Error
  34596. if (this._htmlAudioElement.currentTime > 0) {
  34597. this._htmlAudioElement.currentTime = 0;
  34598. }
  34599. }
  34600. else {
  34601. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34602. this._soundSource.stop(stopTime);
  34603. }
  34604. this.isPlaying = false;
  34605. }
  34606. };
  34607. Sound.prototype.pause = function () {
  34608. if (this.isPlaying) {
  34609. if (this._streaming) {
  34610. this._htmlAudioElement.pause();
  34611. }
  34612. else {
  34613. this.stop(0);
  34614. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34615. }
  34616. this.isPaused = true;
  34617. }
  34618. };
  34619. Sound.prototype.setVolume = function (newVolume, time) {
  34620. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34621. if (time) {
  34622. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34623. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  34624. }
  34625. else {
  34626. this._soundGain.gain.value = newVolume;
  34627. }
  34628. }
  34629. this._volume = newVolume;
  34630. };
  34631. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34632. this._playbackRate = newPlaybackRate;
  34633. if (this.isPlaying) {
  34634. if (this._streaming) {
  34635. this._htmlAudioElement.playbackRate = this._playbackRate;
  34636. }
  34637. else {
  34638. this._soundSource.playbackRate.value = this._playbackRate;
  34639. }
  34640. }
  34641. };
  34642. Sound.prototype.getVolume = function () {
  34643. return this._volume;
  34644. };
  34645. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34646. var _this = this;
  34647. if (this._connectedMesh) {
  34648. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34649. this._registerFunc = null;
  34650. }
  34651. this._connectedMesh = meshToConnectTo;
  34652. if (!this.spatialSound) {
  34653. this.spatialSound = true;
  34654. this._createSpatialParameters();
  34655. if (this.isPlaying && this.loop) {
  34656. this.stop();
  34657. this.play();
  34658. }
  34659. }
  34660. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34661. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34662. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34663. };
  34664. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34665. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34666. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34667. this._updateDirection();
  34668. }
  34669. };
  34670. Sound.prototype.clone = function () {
  34671. var _this = this;
  34672. if (!this._streaming) {
  34673. var setBufferAndRun = function () {
  34674. if (_this._isReadyToPlay) {
  34675. clonedSound._audioBuffer = _this.getAudioBuffer();
  34676. clonedSound._isReadyToPlay = true;
  34677. if (clonedSound.autoplay) {
  34678. clonedSound.play();
  34679. }
  34680. }
  34681. else {
  34682. window.setTimeout(setBufferAndRun, 300);
  34683. }
  34684. };
  34685. var currentOptions = {
  34686. autoplay: this.autoplay, loop: this.loop,
  34687. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34688. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34689. refDistance: this.refDistance, distanceModel: this.distanceModel
  34690. };
  34691. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34692. if (this.useCustomAttenuation) {
  34693. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34694. }
  34695. clonedSound.setPosition(this._position);
  34696. clonedSound.setPlaybackRate(this._playbackRate);
  34697. setBufferAndRun();
  34698. return clonedSound;
  34699. }
  34700. else {
  34701. return null;
  34702. }
  34703. };
  34704. Sound.prototype.getAudioBuffer = function () {
  34705. return this._audioBuffer;
  34706. };
  34707. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34708. var soundName = parsedSound.name;
  34709. var soundUrl;
  34710. if (parsedSound.url) {
  34711. soundUrl = rootUrl + parsedSound.url;
  34712. }
  34713. else {
  34714. soundUrl = rootUrl + soundName;
  34715. }
  34716. var options = {
  34717. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34718. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34719. rolloffFactor: parsedSound.rolloffFactor,
  34720. refDistance: parsedSound.refDistance,
  34721. distanceModel: parsedSound.distanceModel,
  34722. playbackRate: parsedSound.playbackRate
  34723. };
  34724. var newSound;
  34725. if (!sourceSound) {
  34726. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34727. scene._addPendingData(newSound);
  34728. }
  34729. else {
  34730. var setBufferAndRun = function () {
  34731. if (sourceSound._isReadyToPlay) {
  34732. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34733. newSound._isReadyToPlay = true;
  34734. if (newSound.autoplay) {
  34735. newSound.play();
  34736. }
  34737. }
  34738. else {
  34739. window.setTimeout(setBufferAndRun, 300);
  34740. }
  34741. };
  34742. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34743. setBufferAndRun();
  34744. }
  34745. if (parsedSound.position) {
  34746. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34747. newSound.setPosition(soundPosition);
  34748. }
  34749. if (parsedSound.isDirectional) {
  34750. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34751. if (parsedSound.localDirectionToMesh) {
  34752. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34753. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34754. }
  34755. }
  34756. if (parsedSound.connectedMeshId) {
  34757. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34758. if (connectedMesh) {
  34759. newSound.attachToMesh(connectedMesh);
  34760. }
  34761. }
  34762. return newSound;
  34763. };
  34764. return Sound;
  34765. })();
  34766. BABYLON.Sound = Sound;
  34767. })(BABYLON || (BABYLON = {}));
  34768. var BABYLON;
  34769. (function (BABYLON) {
  34770. var SoundTrack = (function () {
  34771. function SoundTrack(scene, options) {
  34772. this.id = -1;
  34773. this._isMainTrack = false;
  34774. this._isInitialized = false;
  34775. this._scene = scene;
  34776. this.soundCollection = new Array();
  34777. this._options = options;
  34778. if (!this._isMainTrack) {
  34779. this._scene.soundTracks.push(this);
  34780. this.id = this._scene.soundTracks.length - 1;
  34781. }
  34782. }
  34783. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34784. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34785. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34786. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34787. if (this._options) {
  34788. if (this._options.volume) {
  34789. this._outputAudioNode.gain.value = this._options.volume;
  34790. }
  34791. if (this._options.mainTrack) {
  34792. this._isMainTrack = this._options.mainTrack;
  34793. }
  34794. }
  34795. this._isInitialized = true;
  34796. }
  34797. };
  34798. SoundTrack.prototype.dispose = function () {
  34799. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34800. if (this._connectedAnalyser) {
  34801. this._connectedAnalyser.stopDebugCanvas();
  34802. }
  34803. while (this.soundCollection.length) {
  34804. this.soundCollection[0].dispose();
  34805. }
  34806. if (this._outputAudioNode) {
  34807. this._outputAudioNode.disconnect();
  34808. }
  34809. this._outputAudioNode = null;
  34810. }
  34811. };
  34812. SoundTrack.prototype.AddSound = function (sound) {
  34813. if (!this._isInitialized) {
  34814. this._initializeSoundTrackAudioGraph();
  34815. }
  34816. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34817. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34818. }
  34819. if (sound.soundTrackId) {
  34820. if (sound.soundTrackId === -1) {
  34821. this._scene.mainSoundTrack.RemoveSound(sound);
  34822. }
  34823. else {
  34824. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34825. }
  34826. }
  34827. this.soundCollection.push(sound);
  34828. sound.soundTrackId = this.id;
  34829. };
  34830. SoundTrack.prototype.RemoveSound = function (sound) {
  34831. var index = this.soundCollection.indexOf(sound);
  34832. if (index !== -1) {
  34833. this.soundCollection.splice(index, 1);
  34834. }
  34835. };
  34836. SoundTrack.prototype.setVolume = function (newVolume) {
  34837. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34838. this._outputAudioNode.gain.value = newVolume;
  34839. }
  34840. };
  34841. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34842. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34843. for (var i = 0; i < this.soundCollection.length; i++) {
  34844. this.soundCollection[i].switchPanningModelToHRTF();
  34845. }
  34846. }
  34847. };
  34848. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34850. for (var i = 0; i < this.soundCollection.length; i++) {
  34851. this.soundCollection[i].switchPanningModelToEqualPower();
  34852. }
  34853. }
  34854. };
  34855. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34856. if (this._connectedAnalyser) {
  34857. this._connectedAnalyser.stopDebugCanvas();
  34858. }
  34859. this._connectedAnalyser = analyser;
  34860. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34861. this._outputAudioNode.disconnect();
  34862. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34863. }
  34864. };
  34865. return SoundTrack;
  34866. })();
  34867. BABYLON.SoundTrack = SoundTrack;
  34868. })(BABYLON || (BABYLON = {}));
  34869. var BABYLON;
  34870. (function (BABYLON) {
  34871. var DepthRenderer = (function () {
  34872. function DepthRenderer(scene, type) {
  34873. var _this = this;
  34874. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34875. this._viewMatrix = BABYLON.Matrix.Zero();
  34876. this._projectionMatrix = BABYLON.Matrix.Zero();
  34877. this._transformMatrix = BABYLON.Matrix.Zero();
  34878. this._worldViewProjection = BABYLON.Matrix.Zero();
  34879. this._scene = scene;
  34880. var engine = scene.getEngine();
  34881. // Render target
  34882. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34883. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34884. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34885. this._depthMap.refreshRate = 1;
  34886. this._depthMap.renderParticles = false;
  34887. this._depthMap.renderList = null;
  34888. // set default depth value to 1.0 (far away)
  34889. this._depthMap.onClear = function (engine) {
  34890. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34891. };
  34892. // Custom render function
  34893. var renderSubMesh = function (subMesh) {
  34894. var mesh = subMesh.getRenderingMesh();
  34895. var scene = _this._scene;
  34896. var engine = scene.getEngine();
  34897. // Culling
  34898. engine.setState(subMesh.getMaterial().backFaceCulling);
  34899. // Managing instances
  34900. var batch = mesh._getInstancesRenderList(subMesh._id);
  34901. if (batch.mustReturn) {
  34902. return;
  34903. }
  34904. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34905. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34906. engine.enableEffect(_this._effect);
  34907. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34908. var material = subMesh.getMaterial();
  34909. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34910. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34911. // Alpha test
  34912. if (material && material.needAlphaTesting()) {
  34913. var alphaTexture = material.getAlphaTestTexture();
  34914. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34915. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34916. }
  34917. // Bones
  34918. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34919. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34920. }
  34921. // Draw
  34922. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34923. }
  34924. };
  34925. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34926. var index;
  34927. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34928. renderSubMesh(opaqueSubMeshes.data[index]);
  34929. }
  34930. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34931. renderSubMesh(alphaTestSubMeshes.data[index]);
  34932. }
  34933. };
  34934. }
  34935. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34936. var defines = [];
  34937. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34938. var mesh = subMesh.getMesh();
  34939. var scene = mesh.getScene();
  34940. var material = subMesh.getMaterial();
  34941. // Alpha test
  34942. if (material && material.needAlphaTesting()) {
  34943. defines.push("#define ALPHATEST");
  34944. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34945. attribs.push(BABYLON.VertexBuffer.UVKind);
  34946. defines.push("#define UV1");
  34947. }
  34948. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34949. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34950. defines.push("#define UV2");
  34951. }
  34952. }
  34953. // Bones
  34954. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34957. if (mesh.numBoneInfluencers > 4) {
  34958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34960. }
  34961. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34962. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34963. }
  34964. else {
  34965. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34966. }
  34967. // Instances
  34968. if (useInstances) {
  34969. defines.push("#define INSTANCES");
  34970. attribs.push("world0");
  34971. attribs.push("world1");
  34972. attribs.push("world2");
  34973. attribs.push("world3");
  34974. }
  34975. // Get correct effect
  34976. var join = defines.join("\n");
  34977. if (this._cachedDefines !== join) {
  34978. this._cachedDefines = join;
  34979. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34980. }
  34981. return this._effect.isReady();
  34982. };
  34983. DepthRenderer.prototype.getDepthMap = function () {
  34984. return this._depthMap;
  34985. };
  34986. // Methods
  34987. DepthRenderer.prototype.dispose = function () {
  34988. this._depthMap.dispose();
  34989. };
  34990. return DepthRenderer;
  34991. })();
  34992. BABYLON.DepthRenderer = DepthRenderer;
  34993. })(BABYLON || (BABYLON = {}));
  34994. var BABYLON;
  34995. (function (BABYLON) {
  34996. var SSAORenderingPipeline = (function (_super) {
  34997. __extends(SSAORenderingPipeline, _super);
  34998. /**
  34999. * @constructor
  35000. * @param {string} name - The rendering pipeline name
  35001. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35002. * @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 }
  35003. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35004. */
  35005. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35006. var _this = this;
  35007. _super.call(this, scene.getEngine(), name);
  35008. // Members
  35009. /**
  35010. * The PassPostProcess id in the pipeline that contains the original scene color
  35011. * @type {string}
  35012. */
  35013. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35014. /**
  35015. * The SSAO PostProcess id in the pipeline
  35016. * @type {string}
  35017. */
  35018. this.SSAORenderEffect = "SSAORenderEffect";
  35019. /**
  35020. * The horizontal blur PostProcess id in the pipeline
  35021. * @type {string}
  35022. */
  35023. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35024. /**
  35025. * The vertical blur PostProcess id in the pipeline
  35026. * @type {string}
  35027. */
  35028. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35029. /**
  35030. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35031. * @type {string}
  35032. */
  35033. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35034. /**
  35035. * The output strength of the SSAO post-process. Default value is 1.0.
  35036. * @type {number}
  35037. */
  35038. this.totalStrength = 1.0;
  35039. /**
  35040. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35041. * @type {number}
  35042. */
  35043. this.radius = 0.0001;
  35044. /**
  35045. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35046. * Must not be equal to fallOff and superior to fallOff.
  35047. * Default value is 0.975
  35048. * @type {number}
  35049. */
  35050. this.area = 0.0075;
  35051. /**
  35052. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35053. * Must not be equal to area and inferior to area.
  35054. * Default value is 0.0
  35055. * @type {number}
  35056. */
  35057. this.fallOff = 0.000001;
  35058. /**
  35059. * The base color of the SSAO post-process
  35060. * The final result is "base + ssao" between [0, 1]
  35061. * @type {number}
  35062. */
  35063. this.base = 0.5;
  35064. this._firstUpdate = true;
  35065. this._scene = scene;
  35066. // Set up assets
  35067. this._createRandomTexture();
  35068. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35069. var ssaoRatio = ratio.ssaoRatio || ratio;
  35070. var combineRatio = ratio.combineRatio || ratio;
  35071. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35072. this._createSSAOPostProcess(ssaoRatio);
  35073. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35074. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35075. this._createSSAOCombinePostProcess(combineRatio);
  35076. // Set up pipeline
  35077. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35082. // Finish
  35083. scene.postProcessRenderPipelineManager.addPipeline(this);
  35084. if (cameras)
  35085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35086. }
  35087. // Public Methods
  35088. /**
  35089. * Returns the horizontal blur PostProcess
  35090. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35091. */
  35092. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35093. return this._blurHPostProcess;
  35094. };
  35095. /**
  35096. * Returns the vertical blur PostProcess
  35097. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35098. */
  35099. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35100. return this._blurVPostProcess;
  35101. };
  35102. /**
  35103. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35104. */
  35105. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35106. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35107. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35108. this._originalColorPostProcess = undefined;
  35109. this._ssaoPostProcess = undefined;
  35110. this._blurHPostProcess = undefined;
  35111. this._blurVPostProcess = undefined;
  35112. this._ssaoCombinePostProcess = undefined;
  35113. this._randomTexture.dispose();
  35114. if (disableDepthRender)
  35115. this._scene.disableDepthRenderer();
  35116. };
  35117. // Private Methods
  35118. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35119. var _this = this;
  35120. var numSamples = 16;
  35121. var sampleSphere = [
  35122. 0.5381, 0.1856, -0.4319,
  35123. 0.1379, 0.2486, 0.4430,
  35124. 0.3371, 0.5679, -0.0057,
  35125. -0.6999, -0.0451, -0.0019,
  35126. 0.0689, -0.1598, -0.8547,
  35127. 0.0560, 0.0069, -0.1843,
  35128. -0.0146, 0.1402, 0.0762,
  35129. 0.0100, -0.1924, -0.0344,
  35130. -0.3577, -0.5301, -0.4358,
  35131. -0.3169, 0.1063, 0.0158,
  35132. 0.0103, -0.5869, 0.0046,
  35133. -0.0897, -0.4940, 0.3287,
  35134. 0.7119, -0.0154, -0.0918,
  35135. -0.0533, 0.0596, -0.5411,
  35136. 0.0352, -0.0631, 0.5460,
  35137. -0.4776, 0.2847, -0.0271
  35138. ];
  35139. var samplesFactor = 1.0 / numSamples;
  35140. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35141. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35142. "area", "fallOff", "base"
  35143. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35144. this._ssaoPostProcess.onApply = function (effect) {
  35145. if (_this._firstUpdate) {
  35146. effect.setArray3("sampleSphere", sampleSphere);
  35147. effect.setFloat("samplesFactor", samplesFactor);
  35148. effect.setFloat("randTextureTiles", 4.0);
  35149. _this._firstUpdate = false;
  35150. }
  35151. effect.setFloat("totalStrength", _this.totalStrength);
  35152. effect.setFloat("radius", _this.radius);
  35153. effect.setFloat("area", _this.area);
  35154. effect.setFloat("fallOff", _this.fallOff);
  35155. effect.setFloat("base", _this.base);
  35156. effect.setTexture("textureSampler", _this._depthTexture);
  35157. effect.setTexture("randomSampler", _this._randomTexture);
  35158. };
  35159. };
  35160. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35161. var _this = this;
  35162. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35163. this._ssaoCombinePostProcess.onApply = function (effect) {
  35164. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35165. };
  35166. };
  35167. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35168. var size = 512;
  35169. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35170. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35171. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35172. var context = this._randomTexture.getContext();
  35173. var rand = function (min, max) {
  35174. return Math.random() * (max - min) + min;
  35175. };
  35176. var randVector = BABYLON.Vector3.Zero();
  35177. for (var x = 0; x < size; x++) {
  35178. for (var y = 0; y < size; y++) {
  35179. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35180. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35181. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35182. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35183. context.fillRect(x, y, 1, 1);
  35184. }
  35185. }
  35186. this._randomTexture.update(false);
  35187. };
  35188. return SSAORenderingPipeline;
  35189. })(BABYLON.PostProcessRenderPipeline);
  35190. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35191. })(BABYLON || (BABYLON = {}));
  35192. var BABYLON;
  35193. (function (BABYLON) {
  35194. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35195. var VolumetricLightScatteringPostProcess = (function (_super) {
  35196. __extends(VolumetricLightScatteringPostProcess, _super);
  35197. /**
  35198. * @constructor
  35199. * @param {string} name - The post-process name
  35200. * @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)
  35201. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35202. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35203. * @param {number} samples - The post-process quality, default 100
  35204. * @param {number} samplingMode - The post-process filtering mode
  35205. * @param {BABYLON.Engine} engine - The babylon engine
  35206. * @param {boolean} reusable - If the post-process is reusable
  35207. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35208. */
  35209. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35210. var _this = this;
  35211. if (samples === void 0) { samples = 100; }
  35212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35213. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35214. this._screenCoordinates = BABYLON.Vector2.Zero();
  35215. /**
  35216. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35217. * @type {boolean}
  35218. */
  35219. this.useCustomMeshPosition = false;
  35220. /**
  35221. * If the post-process should inverse the light scattering direction
  35222. * @type {boolean}
  35223. */
  35224. this.invert = true;
  35225. /**
  35226. * Set to true to use the diffuseColor instead of the diffuseTexture
  35227. * @type {boolean}
  35228. */
  35229. this.useDiffuseColor = false;
  35230. /**
  35231. * Array containing the excluded meshes not rendered in the internal pass
  35232. */
  35233. this.excludedMeshes = new Array();
  35234. /**
  35235. * Controls the overall intensity of the post-process
  35236. * @type {number}
  35237. */
  35238. this.exposure = 0.3;
  35239. /**
  35240. * Dissipates each sample's contribution in range [0, 1]
  35241. * @type {number}
  35242. */
  35243. this.decay = 0.96815;
  35244. /**
  35245. * Controls the overall intensity of each sample
  35246. * @type {number}
  35247. */
  35248. this.weight = 0.58767;
  35249. /**
  35250. * Controls the density of each sample
  35251. * @type {number}
  35252. */
  35253. this.density = 0.926;
  35254. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35255. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35256. // Configure mesh
  35257. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35258. // Configure
  35259. this._createPass(scene, ratio.passRatio || ratio);
  35260. this.onActivate = function (camera) {
  35261. if (!_this.isSupported) {
  35262. _this.dispose(camera);
  35263. }
  35264. _this.onActivate = null;
  35265. };
  35266. this.onApply = function (effect) {
  35267. _this._updateMeshScreenCoordinates(scene);
  35268. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35269. effect.setFloat("exposure", _this.exposure);
  35270. effect.setFloat("decay", _this.decay);
  35271. effect.setFloat("weight", _this.weight);
  35272. effect.setFloat("density", _this.density);
  35273. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35274. };
  35275. }
  35276. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35277. var mesh = subMesh.getMesh();
  35278. var defines = [];
  35279. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35280. var material = subMesh.getMaterial();
  35281. var needUV = false;
  35282. // Render this.mesh as default
  35283. if (mesh === this.mesh) {
  35284. if (this.useDiffuseColor) {
  35285. defines.push("#define DIFFUSE_COLOR_RENDER");
  35286. }
  35287. else if (material) {
  35288. if (material.diffuseTexture !== undefined) {
  35289. defines.push("#define BASIC_RENDER");
  35290. }
  35291. else {
  35292. defines.push("#define DIFFUSE_COLOR_RENDER");
  35293. }
  35294. }
  35295. defines.push("#define NEED_UV");
  35296. needUV = true;
  35297. }
  35298. // Alpha test
  35299. if (material) {
  35300. if (material.needAlphaTesting()) {
  35301. defines.push("#define ALPHATEST");
  35302. }
  35303. if (material.opacityTexture !== undefined) {
  35304. defines.push("#define OPACITY");
  35305. if (material.opacityTexture.getAlphaFromRGB) {
  35306. defines.push("#define OPACITYRGB");
  35307. }
  35308. if (!needUV) {
  35309. defines.push("#define NEED_UV");
  35310. }
  35311. }
  35312. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35313. attribs.push(BABYLON.VertexBuffer.UVKind);
  35314. defines.push("#define UV1");
  35315. }
  35316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35317. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35318. defines.push("#define UV2");
  35319. }
  35320. }
  35321. // Bones
  35322. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35323. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35324. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35325. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35326. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35327. }
  35328. else {
  35329. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35330. }
  35331. // Instances
  35332. if (useInstances) {
  35333. defines.push("#define INSTANCES");
  35334. attribs.push("world0");
  35335. attribs.push("world1");
  35336. attribs.push("world2");
  35337. attribs.push("world3");
  35338. }
  35339. // Get correct effect
  35340. var join = defines.join("\n");
  35341. if (this._cachedDefines !== join) {
  35342. this._cachedDefines = join;
  35343. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35344. }
  35345. return this._volumetricLightScatteringPass.isReady();
  35346. };
  35347. /**
  35348. * Sets the new light position for light scattering effect
  35349. * @param {BABYLON.Vector3} The new custom light position
  35350. */
  35351. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35352. this._customMeshPosition = position;
  35353. };
  35354. /**
  35355. * Returns the light position for light scattering effect
  35356. * @return {BABYLON.Vector3} The custom light position
  35357. */
  35358. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35359. return this._customMeshPosition;
  35360. };
  35361. /**
  35362. * Disposes the internal assets and detaches the post-process from the camera
  35363. */
  35364. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35365. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35366. if (rttIndex !== -1) {
  35367. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35368. }
  35369. this._volumetricLightScatteringRTT.dispose();
  35370. _super.prototype.dispose.call(this, camera);
  35371. };
  35372. /**
  35373. * Returns the render target texture used by the post-process
  35374. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35375. */
  35376. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35377. return this._volumetricLightScatteringRTT;
  35378. };
  35379. // Private methods
  35380. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35381. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35382. return true;
  35383. }
  35384. return false;
  35385. };
  35386. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35387. var _this = this;
  35388. var engine = scene.getEngine();
  35389. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35390. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35391. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35392. this._volumetricLightScatteringRTT.renderList = null;
  35393. this._volumetricLightScatteringRTT.renderParticles = false;
  35394. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35395. // Custom render function for submeshes
  35396. var renderSubMesh = function (subMesh) {
  35397. var mesh = subMesh.getRenderingMesh();
  35398. if (_this._meshExcluded(mesh)) {
  35399. return;
  35400. }
  35401. var scene = mesh.getScene();
  35402. var engine = scene.getEngine();
  35403. // Culling
  35404. engine.setState(subMesh.getMaterial().backFaceCulling);
  35405. // Managing instances
  35406. var batch = mesh._getInstancesRenderList(subMesh._id);
  35407. if (batch.mustReturn) {
  35408. return;
  35409. }
  35410. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35411. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35412. engine.enableEffect(_this._volumetricLightScatteringPass);
  35413. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35414. var material = subMesh.getMaterial();
  35415. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35416. // Alpha test
  35417. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35418. var alphaTexture = material.getAlphaTestTexture();
  35419. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35420. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35421. }
  35422. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35423. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35424. if (alphaTexture) {
  35425. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35426. }
  35427. }
  35428. if (material.opacityTexture !== undefined) {
  35429. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35430. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35431. }
  35432. }
  35433. // Bones
  35434. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35435. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35436. }
  35437. // Draw
  35438. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35439. }
  35440. };
  35441. // Render target texture callbacks
  35442. var savedSceneClearColor;
  35443. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35444. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35445. savedSceneClearColor = scene.clearColor;
  35446. scene.clearColor = sceneClearColor;
  35447. };
  35448. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35449. scene.clearColor = savedSceneClearColor;
  35450. };
  35451. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35452. var engine = scene.getEngine();
  35453. var index;
  35454. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35455. renderSubMesh(opaqueSubMeshes.data[index]);
  35456. }
  35457. engine.setAlphaTesting(true);
  35458. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35459. renderSubMesh(alphaTestSubMeshes.data[index]);
  35460. }
  35461. engine.setAlphaTesting(false);
  35462. if (transparentSubMeshes.length) {
  35463. // Sort sub meshes
  35464. for (index = 0; index < transparentSubMeshes.length; index++) {
  35465. var submesh = transparentSubMeshes.data[index];
  35466. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35467. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35468. }
  35469. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35470. sortedArray.sort(function (a, b) {
  35471. // Alpha index first
  35472. if (a._alphaIndex > b._alphaIndex) {
  35473. return 1;
  35474. }
  35475. if (a._alphaIndex < b._alphaIndex) {
  35476. return -1;
  35477. }
  35478. // Then distance to camera
  35479. if (a._distanceToCamera < b._distanceToCamera) {
  35480. return 1;
  35481. }
  35482. if (a._distanceToCamera > b._distanceToCamera) {
  35483. return -1;
  35484. }
  35485. return 0;
  35486. });
  35487. // Render sub meshes
  35488. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35489. for (index = 0; index < sortedArray.length; index++) {
  35490. renderSubMesh(sortedArray[index]);
  35491. }
  35492. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35493. }
  35494. };
  35495. };
  35496. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35497. var transform = scene.getTransformMatrix();
  35498. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35499. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35500. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35501. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35502. if (this.invert)
  35503. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35504. };
  35505. // Static methods
  35506. /**
  35507. * Creates a default mesh for the Volumeric Light Scattering post-process
  35508. * @param {string} The mesh name
  35509. * @param {BABYLON.Scene} The scene where to create the mesh
  35510. * @return {BABYLON.Mesh} the default mesh
  35511. */
  35512. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35513. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35514. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35515. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35516. return mesh;
  35517. };
  35518. return VolumetricLightScatteringPostProcess;
  35519. })(BABYLON.PostProcess);
  35520. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35521. })(BABYLON || (BABYLON = {}));
  35522. // BABYLON.JS Chromatic Aberration GLSL Shader
  35523. // Author: Olivier Guyot
  35524. // Separates very slightly R, G and B colors on the edges of the screen
  35525. // Inspired by Francois Tarlier & Martins Upitis
  35526. var BABYLON;
  35527. (function (BABYLON) {
  35528. var LensRenderingPipeline = (function (_super) {
  35529. __extends(LensRenderingPipeline, _super);
  35530. /**
  35531. * @constructor
  35532. *
  35533. * Effect parameters are as follow:
  35534. * {
  35535. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35536. * edge_blur: number; // from 0 to x (1 for realism)
  35537. * distortion: number; // from 0 to x (1 for realism)
  35538. * grain_amount: number; // from 0 to 1
  35539. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35540. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35541. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35542. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35543. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35544. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35545. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35546. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35547. * }
  35548. * Note: if an effect parameter is unset, effect is disabled
  35549. *
  35550. * @param {string} name - The rendering pipeline name
  35551. * @param {object} parameters - An object containing all parameters (see above)
  35552. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35553. * @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)
  35554. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35555. */
  35556. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35557. var _this = this;
  35558. if (ratio === void 0) { ratio = 1.0; }
  35559. _super.call(this, scene.getEngine(), name);
  35560. // Lens effects can be of the following:
  35561. // - chromatic aberration (slight shift of RGB colors)
  35562. // - blur on the edge of the lens
  35563. // - lens distortion
  35564. // - depth-of-field blur & highlights enhancing
  35565. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35566. // - grain effect (noise or custom texture)
  35567. // Two additional texture samplers are needed:
  35568. // - depth map (for depth-of-field)
  35569. // - grain texture
  35570. /**
  35571. * The chromatic aberration PostProcess id in the pipeline
  35572. * @type {string}
  35573. */
  35574. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35575. /**
  35576. * The highlights enhancing PostProcess id in the pipeline
  35577. * @type {string}
  35578. */
  35579. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35580. /**
  35581. * The depth-of-field PostProcess id in the pipeline
  35582. * @type {string}
  35583. */
  35584. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35585. this._scene = scene;
  35586. // Fetch texture samplers
  35587. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35588. if (parameters.grain_texture) {
  35589. this._grainTexture = parameters.grain_texture;
  35590. }
  35591. else {
  35592. this._createGrainTexture();
  35593. }
  35594. // save parameters
  35595. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35596. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35597. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35598. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35599. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35600. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35601. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35602. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35603. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35604. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35605. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35606. // Create effects
  35607. this._createChromaticAberrationPostProcess(ratio);
  35608. this._createHighlightsPostProcess(ratio);
  35609. this._createDepthOfFieldPostProcess(ratio / 4);
  35610. // Set up pipeline
  35611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35614. if (this._highlightsGain === -1) {
  35615. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35616. }
  35617. // Finish
  35618. scene.postProcessRenderPipelineManager.addPipeline(this);
  35619. if (cameras) {
  35620. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35621. }
  35622. }
  35623. // public methods (self explanatory)
  35624. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35625. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35626. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35627. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35628. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35629. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35630. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35631. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35632. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35633. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35634. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35635. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35636. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35637. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35638. };
  35639. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35640. this._highlightsPostProcess.updateEffect();
  35641. };
  35642. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35643. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35644. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35645. this._highlightsGain = amount;
  35646. };
  35647. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35648. if (this._highlightsGain === -1) {
  35649. this._highlightsGain = 1.0;
  35650. }
  35651. this._highlightsThreshold = amount;
  35652. };
  35653. LensRenderingPipeline.prototype.disableHighlights = function () {
  35654. this._highlightsGain = -1;
  35655. };
  35656. /**
  35657. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35658. */
  35659. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35660. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35661. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35662. this._chromaticAberrationPostProcess = undefined;
  35663. this._highlightsPostProcess = undefined;
  35664. this._depthOfFieldPostProcess = undefined;
  35665. this._grainTexture.dispose();
  35666. if (disableDepthRender)
  35667. this._scene.disableDepthRenderer();
  35668. };
  35669. // colors shifting and distortion
  35670. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35671. var _this = this;
  35672. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35673. [], // samplers
  35674. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35675. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35676. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35677. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35678. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35679. };
  35680. };
  35681. // highlights enhancing
  35682. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35683. var _this = this;
  35684. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35685. [], // samplers
  35686. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35687. this._highlightsPostProcess.onApply = function (effect) {
  35688. effect.setFloat('gain', _this._highlightsGain);
  35689. effect.setFloat('threshold', _this._highlightsThreshold);
  35690. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35693. };
  35694. };
  35695. // colors shifting and distortion
  35696. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35697. var _this = this;
  35698. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35699. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35700. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35701. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35702. this._depthOfFieldPostProcess.onApply = function (effect) {
  35703. effect.setTexture("depthSampler", _this._depthTexture);
  35704. effect.setTexture("grainSampler", _this._grainTexture);
  35705. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35706. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35707. effect.setFloat('grain_amount', _this._grainAmount);
  35708. effect.setBool('blur_noise', _this._blurNoise);
  35709. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35710. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35711. effect.setFloat('distortion', _this._distortion);
  35712. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35713. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35714. effect.setFloat('aperture', _this._dofAperture);
  35715. effect.setFloat('darken', _this._dofDarken);
  35716. effect.setFloat('edge_blur', _this._edgeBlur);
  35717. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35718. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35719. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35720. };
  35721. };
  35722. // creates a black and white random noise texture, 512x512
  35723. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35724. var size = 512;
  35725. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35726. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35727. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35728. var context = this._grainTexture.getContext();
  35729. var rand = function (min, max) {
  35730. return Math.random() * (max - min) + min;
  35731. };
  35732. var value;
  35733. for (var x = 0; x < size; x++) {
  35734. for (var y = 0; y < size; y++) {
  35735. value = Math.floor(rand(0.42, 0.58) * 255);
  35736. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35737. context.fillRect(x, y, 1, 1);
  35738. }
  35739. }
  35740. this._grainTexture.update(false);
  35741. };
  35742. return LensRenderingPipeline;
  35743. })(BABYLON.PostProcessRenderPipeline);
  35744. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35745. })(BABYLON || (BABYLON = {}));
  35746. //
  35747. // This post-process allows the modification of rendered colors by using
  35748. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35749. //
  35750. // The object needs to be provided an url to a texture containing the color
  35751. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35752. // Use an image editing software to tweak the LUT to match your needs.
  35753. //
  35754. // For an example of a color LUT, see here:
  35755. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35756. // For explanations on color grading, see here:
  35757. // http://udn.epicgames.com/Three/ColorGrading.html
  35758. //
  35759. var BABYLON;
  35760. (function (BABYLON) {
  35761. var ColorCorrectionPostProcess = (function (_super) {
  35762. __extends(ColorCorrectionPostProcess, _super);
  35763. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35764. var _this = this;
  35765. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35766. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35767. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35768. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35769. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35770. this.onApply = function (effect) {
  35771. effect.setTexture("colorTable", _this._colorTableTexture);
  35772. };
  35773. }
  35774. return ColorCorrectionPostProcess;
  35775. })(BABYLON.PostProcess);
  35776. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35777. })(BABYLON || (BABYLON = {}));
  35778. var BABYLON;
  35779. (function (BABYLON) {
  35780. var AnaglyphFreeCamera = (function (_super) {
  35781. __extends(AnaglyphFreeCamera, _super);
  35782. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35783. _super.call(this, name, position, scene);
  35784. this.interaxialDistance = interaxialDistance;
  35785. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35786. }
  35787. return AnaglyphFreeCamera;
  35788. })(BABYLON.FreeCamera);
  35789. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35790. var AnaglyphArcRotateCamera = (function (_super) {
  35791. __extends(AnaglyphArcRotateCamera, _super);
  35792. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35793. _super.call(this, name, alpha, beta, radius, target, scene);
  35794. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35795. }
  35796. return AnaglyphArcRotateCamera;
  35797. })(BABYLON.ArcRotateCamera);
  35798. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35799. var AnaglyphGamepadCamera = (function (_super) {
  35800. __extends(AnaglyphGamepadCamera, _super);
  35801. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35802. _super.call(this, name, position, scene);
  35803. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35804. }
  35805. return AnaglyphGamepadCamera;
  35806. })(BABYLON.GamepadCamera);
  35807. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35808. var StereoscopicFreeCamera = (function (_super) {
  35809. __extends(StereoscopicFreeCamera, _super);
  35810. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35811. _super.call(this, name, position, scene);
  35812. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35813. }
  35814. return StereoscopicFreeCamera;
  35815. })(BABYLON.FreeCamera);
  35816. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35817. var StereoscopicArcRotateCamera = (function (_super) {
  35818. __extends(StereoscopicArcRotateCamera, _super);
  35819. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35820. _super.call(this, name, alpha, beta, radius, target, scene);
  35821. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35822. }
  35823. return StereoscopicArcRotateCamera;
  35824. })(BABYLON.ArcRotateCamera);
  35825. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35826. var StereoscopicGamepadCamera = (function (_super) {
  35827. __extends(StereoscopicGamepadCamera, _super);
  35828. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35829. _super.call(this, name, position, scene);
  35830. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35831. }
  35832. return StereoscopicGamepadCamera;
  35833. })(BABYLON.GamepadCamera);
  35834. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35835. })(BABYLON || (BABYLON = {}));
  35836. var BABYLON;
  35837. (function (BABYLON) {
  35838. var HDRRenderingPipeline = (function (_super) {
  35839. __extends(HDRRenderingPipeline, _super);
  35840. /**
  35841. * @constructor
  35842. * @param {string} name - The rendering pipeline name
  35843. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35844. * @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)
  35845. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35846. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35847. */
  35848. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35849. var _this = this;
  35850. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35851. _super.call(this, scene.getEngine(), name);
  35852. /**
  35853. * Public members
  35854. */
  35855. // Gaussian Blur
  35856. /**
  35857. * Gaussian blur coefficient
  35858. * @type {number}
  35859. */
  35860. this.gaussCoeff = 0.3;
  35861. /**
  35862. * Gaussian blur mean
  35863. * @type {number}
  35864. */
  35865. this.gaussMean = 1.0;
  35866. /**
  35867. * Gaussian blur standard deviation
  35868. * @type {number}
  35869. */
  35870. this.gaussStandDev = 0.8;
  35871. /**
  35872. * Gaussian blur multiplier. Multiplies the blur effect
  35873. * @type {number}
  35874. */
  35875. this.gaussMultiplier = 4.0;
  35876. // HDR
  35877. /**
  35878. * Exposure, controls the overall intensity of the pipeline
  35879. * @type {number}
  35880. */
  35881. this.exposure = 1.0;
  35882. /**
  35883. * Minimum luminance that the post-process can output. Luminance is >= 0
  35884. * @type {number}
  35885. */
  35886. this.minimumLuminance = 1.0;
  35887. /**
  35888. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35889. * @type {number}
  35890. */
  35891. this.maximumLuminance = 1e20;
  35892. /**
  35893. * Increase rate for luminance: eye adaptation speed to dark
  35894. * @type {number}
  35895. */
  35896. this.luminanceIncreaserate = 0.5;
  35897. /**
  35898. * Decrease rate for luminance: eye adaptation speed to bright
  35899. * @type {number}
  35900. */
  35901. this.luminanceDecreaseRate = 0.5;
  35902. // Bright pass
  35903. /**
  35904. * Minimum luminance needed to compute HDR
  35905. * @type {number}
  35906. */
  35907. this.brightThreshold = 0.8;
  35908. this._needUpdate = true;
  35909. this._scene = scene;
  35910. // Bright pass
  35911. this._createBrightPassPostProcess(scene, ratio);
  35912. // Down sample X4
  35913. this._createDownSampleX4PostProcess(scene, ratio);
  35914. // Create gaussian blur post-processes
  35915. this._createGaussianBlurPostProcess(scene, ratio);
  35916. // Texture adder
  35917. this._createTextureAdderPostProcess(scene, ratio);
  35918. // Luminance generator
  35919. this._createLuminanceGeneratorPostProcess(scene);
  35920. // HDR
  35921. this._createHDRPostProcess(scene, ratio);
  35922. // Pass postprocess
  35923. if (originalPostProcess === null) {
  35924. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35925. }
  35926. else {
  35927. this._originalPostProcess = originalPostProcess;
  35928. }
  35929. // Configure pipeline
  35930. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35931. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35934. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35935. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35936. var addDownSamplerPostProcess = function (id) {
  35937. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35938. };
  35939. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35940. addDownSamplerPostProcess(i);
  35941. }
  35942. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35943. // Finish
  35944. scene.postProcessRenderPipelineManager.addPipeline(this);
  35945. if (cameras !== null) {
  35946. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35947. }
  35948. this.update();
  35949. }
  35950. /**
  35951. * Tells the pipeline to update its post-processes
  35952. */
  35953. HDRRenderingPipeline.prototype.update = function () {
  35954. this._needUpdate = true;
  35955. };
  35956. /**
  35957. * Returns the current calculated luminance
  35958. */
  35959. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35960. return this._hdrCurrentLuminance;
  35961. };
  35962. /**
  35963. * Returns the currently drawn luminance
  35964. */
  35965. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35966. return this._hdrOutputLuminance;
  35967. };
  35968. /**
  35969. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35970. */
  35971. HDRRenderingPipeline.prototype.dispose = function () {
  35972. this._originalPostProcess = undefined;
  35973. this._brightPassPostProcess = undefined;
  35974. this._downSampleX4PostProcess = undefined;
  35975. this._guassianBlurHPostProcess = undefined;
  35976. this._guassianBlurVPostProcess = undefined;
  35977. this._textureAdderPostProcess = undefined;
  35978. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35979. this._downSamplePostProcesses[i] = undefined;
  35980. }
  35981. this._hdrPostProcess = undefined;
  35982. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35983. };
  35984. /**
  35985. * Creates the HDR post-process and computes the luminance adaptation
  35986. */
  35987. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35988. var _this = this;
  35989. var hdrLastLuminance = 0.0;
  35990. this._hdrOutputLuminance = -1.0;
  35991. this._hdrCurrentLuminance = 1.0;
  35992. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35993. this._hdrPostProcess.onApply = function (effect) {
  35994. if (_this._hdrOutputLuminance < 0.0) {
  35995. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35996. }
  35997. else {
  35998. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35999. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36000. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36001. }
  36002. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36003. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36004. }
  36005. else {
  36006. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36007. }
  36008. }
  36009. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36010. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36011. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36012. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36013. effect.setFloat("exposure", _this.exposure);
  36014. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36015. _this._needUpdate = false;
  36016. };
  36017. };
  36018. /**
  36019. * Texture Adder post-process
  36020. */
  36021. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36022. var _this = this;
  36023. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36024. this._textureAdderPostProcess.onApply = function (effect) {
  36025. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36026. };
  36027. };
  36028. /**
  36029. * Down sample X4 post-process
  36030. */
  36031. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36032. var _this = this;
  36033. var downSampleX4Offsets = new Array(32);
  36034. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36035. this._downSampleX4PostProcess.onApply = function (effect) {
  36036. if (_this._needUpdate) {
  36037. var id = 0;
  36038. for (var i = -2; i < 2; i++) {
  36039. for (var j = -2; j < 2; j++) {
  36040. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36041. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36042. id += 2;
  36043. }
  36044. }
  36045. }
  36046. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36047. };
  36048. };
  36049. /**
  36050. * Bright pass post-process
  36051. */
  36052. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36053. var _this = this;
  36054. var brightOffsets = new Array(8);
  36055. var brightPassCallback = function (effect) {
  36056. if (_this._needUpdate) {
  36057. var sU = (1.0 / _this._brightPassPostProcess.width);
  36058. var sV = (1.0 / _this._brightPassPostProcess.height);
  36059. brightOffsets[0] = -0.5 * sU;
  36060. brightOffsets[1] = 0.5 * sV;
  36061. brightOffsets[2] = 0.5 * sU;
  36062. brightOffsets[3] = 0.5 * sV;
  36063. brightOffsets[4] = -0.5 * sU;
  36064. brightOffsets[5] = -0.5 * sV;
  36065. brightOffsets[6] = 0.5 * sU;
  36066. brightOffsets[7] = -0.5 * sV;
  36067. }
  36068. effect.setArray2("dsOffsets", brightOffsets);
  36069. effect.setFloat("brightThreshold", _this.brightThreshold);
  36070. };
  36071. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36072. this._brightPassPostProcess.onApply = brightPassCallback;
  36073. };
  36074. /**
  36075. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36076. */
  36077. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36078. var _this = this;
  36079. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36080. var luminanceOffsets = new Array(8);
  36081. var downSampleOffsets = new Array(18);
  36082. var halfDestPixelSize;
  36083. this._downSamplePostProcesses = new Array(lumSteps);
  36084. // Utils for luminance
  36085. var luminanceUpdateSourceOffsets = function (width, height) {
  36086. var sU = (1.0 / width);
  36087. var sV = (1.0 / height);
  36088. luminanceOffsets[0] = -0.5 * sU;
  36089. luminanceOffsets[1] = 0.5 * sV;
  36090. luminanceOffsets[2] = 0.5 * sU;
  36091. luminanceOffsets[3] = 0.5 * sV;
  36092. luminanceOffsets[4] = -0.5 * sU;
  36093. luminanceOffsets[5] = -0.5 * sV;
  36094. luminanceOffsets[6] = 0.5 * sU;
  36095. luminanceOffsets[7] = -0.5 * sV;
  36096. };
  36097. var luminanceUpdateDestOffsets = function (width, height) {
  36098. var id = 0;
  36099. for (var x = -1; x < 2; x++) {
  36100. for (var y = -1; y < 2; y++) {
  36101. downSampleOffsets[id] = (x) / width;
  36102. downSampleOffsets[id + 1] = (y) / height;
  36103. id += 2;
  36104. }
  36105. }
  36106. };
  36107. // Luminance callback
  36108. var luminanceCallback = function (effect) {
  36109. if (_this._needUpdate) {
  36110. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36111. }
  36112. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36113. effect.setArray2("lumOffsets", luminanceOffsets);
  36114. };
  36115. // Down sample callbacks
  36116. var downSampleCallback = function (indice) {
  36117. var i = indice;
  36118. return function (effect) {
  36119. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36120. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36121. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36122. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36123. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36124. effect.setArray2("dsOffsets", downSampleOffsets);
  36125. };
  36126. };
  36127. var downSampleAfterRenderCallback = function (effect) {
  36128. // Unpack result
  36129. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36130. 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);
  36131. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36132. };
  36133. // Create luminance post-process
  36134. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36135. 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);
  36136. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36137. // Create down sample post-processes
  36138. for (var i = lumSteps - 2; i >= 0; i--) {
  36139. var length = Math.pow(3, i);
  36140. ratio = { width: length, height: length };
  36141. var defines = "#define DOWN_SAMPLE\n";
  36142. if (i === 0) {
  36143. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36144. }
  36145. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36146. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36147. if (i === 0) {
  36148. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36149. }
  36150. }
  36151. };
  36152. /**
  36153. * Gaussian blur post-processes. Horizontal and Vertical
  36154. */
  36155. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36156. var _this = this;
  36157. var blurOffsetsW = new Array(9);
  36158. var blurOffsetsH = new Array(9);
  36159. var blurWeights = new Array(9);
  36160. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36161. // Utils for gaussian blur
  36162. var calculateBlurOffsets = function (height) {
  36163. var lastOutputDimensions = {
  36164. width: scene.getEngine().getRenderWidth(),
  36165. height: scene.getEngine().getRenderHeight()
  36166. };
  36167. for (var i = 0; i < 9; i++) {
  36168. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36169. if (height) {
  36170. blurOffsetsH[i] = value;
  36171. }
  36172. else {
  36173. blurOffsetsW[i] = value;
  36174. }
  36175. }
  36176. };
  36177. var calculateWeights = function () {
  36178. var x = 0.0;
  36179. for (var i = 0; i < 9; i++) {
  36180. x = (i - 4.0) / 4.0;
  36181. 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));
  36182. }
  36183. };
  36184. // Callback
  36185. var gaussianBlurCallback = function (height) {
  36186. return function (effect) {
  36187. if (_this._needUpdate) {
  36188. calculateWeights();
  36189. calculateBlurOffsets(height);
  36190. }
  36191. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36192. effect.setArray("blurWeights", blurWeights);
  36193. effect.setFloat("multiplier", _this.gaussMultiplier);
  36194. };
  36195. };
  36196. // Create horizontal gaussian blur post-processes
  36197. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36198. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36199. // Create vertical gaussian blur post-process
  36200. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36201. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36202. };
  36203. // Luminance generator
  36204. HDRRenderingPipeline.LUM_STEPS = 6;
  36205. return HDRRenderingPipeline;
  36206. })(BABYLON.PostProcessRenderPipeline);
  36207. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36208. })(BABYLON || (BABYLON = {}));
  36209. var BABYLON;
  36210. (function (BABYLON) {
  36211. var FaceAdjacencies = (function () {
  36212. function FaceAdjacencies() {
  36213. this.edges = new Array();
  36214. this.edgesConnectedCount = 0;
  36215. }
  36216. return FaceAdjacencies;
  36217. })();
  36218. var EdgesRenderer = (function () {
  36219. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36220. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36221. if (epsilon === void 0) { epsilon = 0.95; }
  36222. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36223. this.edgesWidthScalerForOrthographic = 1000.0;
  36224. this.edgesWidthScalerForPerspective = 50.0;
  36225. this._linesPositions = new Array();
  36226. this._linesNormals = new Array();
  36227. this._linesIndices = new Array();
  36228. this._buffers = new Array();
  36229. this._checkVerticesInsteadOfIndices = false;
  36230. this._source = source;
  36231. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36232. this._epsilon = epsilon;
  36233. this._prepareRessources();
  36234. this._generateEdgesLines();
  36235. }
  36236. EdgesRenderer.prototype._prepareRessources = function () {
  36237. if (this._lineShader) {
  36238. return;
  36239. }
  36240. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36241. attributes: ["position", "normal"],
  36242. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36243. });
  36244. this._lineShader.disableDepthWrite = true;
  36245. this._lineShader.backFaceCulling = false;
  36246. };
  36247. EdgesRenderer.prototype.dispose = function () {
  36248. this._vb0.dispose();
  36249. this._vb1.dispose();
  36250. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36251. this._lineShader.dispose();
  36252. };
  36253. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36254. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36255. return 0;
  36256. }
  36257. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36258. return 1;
  36259. }
  36260. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36261. return 2;
  36262. }
  36263. return -1;
  36264. };
  36265. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36266. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36267. return 0;
  36268. }
  36269. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36270. return 1;
  36271. }
  36272. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36273. return 2;
  36274. }
  36275. return -1;
  36276. };
  36277. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36278. var needToCreateLine;
  36279. if (edge === undefined) {
  36280. needToCreateLine = true;
  36281. }
  36282. else {
  36283. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36284. needToCreateLine = dotProduct < this._epsilon;
  36285. }
  36286. if (needToCreateLine) {
  36287. var offset = this._linesPositions.length / 3;
  36288. var normal = p0.subtract(p1);
  36289. normal.normalize();
  36290. // Positions
  36291. this._linesPositions.push(p0.x);
  36292. this._linesPositions.push(p0.y);
  36293. this._linesPositions.push(p0.z);
  36294. this._linesPositions.push(p0.x);
  36295. this._linesPositions.push(p0.y);
  36296. this._linesPositions.push(p0.z);
  36297. this._linesPositions.push(p1.x);
  36298. this._linesPositions.push(p1.y);
  36299. this._linesPositions.push(p1.z);
  36300. this._linesPositions.push(p1.x);
  36301. this._linesPositions.push(p1.y);
  36302. this._linesPositions.push(p1.z);
  36303. // Normals
  36304. this._linesNormals.push(p1.x);
  36305. this._linesNormals.push(p1.y);
  36306. this._linesNormals.push(p1.z);
  36307. this._linesNormals.push(-1);
  36308. this._linesNormals.push(p1.x);
  36309. this._linesNormals.push(p1.y);
  36310. this._linesNormals.push(p1.z);
  36311. this._linesNormals.push(1);
  36312. this._linesNormals.push(p0.x);
  36313. this._linesNormals.push(p0.y);
  36314. this._linesNormals.push(p0.z);
  36315. this._linesNormals.push(-1);
  36316. this._linesNormals.push(p0.x);
  36317. this._linesNormals.push(p0.y);
  36318. this._linesNormals.push(p0.z);
  36319. this._linesNormals.push(1);
  36320. // Indices
  36321. this._linesIndices.push(offset);
  36322. this._linesIndices.push(offset + 1);
  36323. this._linesIndices.push(offset + 2);
  36324. this._linesIndices.push(offset);
  36325. this._linesIndices.push(offset + 2);
  36326. this._linesIndices.push(offset + 3);
  36327. }
  36328. };
  36329. EdgesRenderer.prototype._generateEdgesLines = function () {
  36330. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36331. var indices = this._source.getIndices();
  36332. // First let's find adjacencies
  36333. var adjacencies = new Array();
  36334. var faceNormals = new Array();
  36335. var index;
  36336. var faceAdjacencies;
  36337. // Prepare faces
  36338. for (index = 0; index < indices.length; index += 3) {
  36339. faceAdjacencies = new FaceAdjacencies();
  36340. var p0Index = indices[index];
  36341. var p1Index = indices[index + 1];
  36342. var p2Index = indices[index + 2];
  36343. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36344. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36345. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36346. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36347. faceNormal.normalize();
  36348. faceNormals.push(faceNormal);
  36349. adjacencies.push(faceAdjacencies);
  36350. }
  36351. // Scan
  36352. for (index = 0; index < adjacencies.length; index++) {
  36353. faceAdjacencies = adjacencies[index];
  36354. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36355. var otherFaceAdjacencies = adjacencies[otherIndex];
  36356. if (faceAdjacencies.edgesConnectedCount === 3) {
  36357. break;
  36358. }
  36359. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36360. continue;
  36361. }
  36362. var otherP0 = indices[otherIndex * 3];
  36363. var otherP1 = indices[otherIndex * 3 + 1];
  36364. var otherP2 = indices[otherIndex * 3 + 2];
  36365. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36366. var otherEdgeIndex;
  36367. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36368. continue;
  36369. }
  36370. switch (edgeIndex) {
  36371. case 0:
  36372. if (this._checkVerticesInsteadOfIndices) {
  36373. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36374. }
  36375. else {
  36376. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36377. }
  36378. break;
  36379. case 1:
  36380. if (this._checkVerticesInsteadOfIndices) {
  36381. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36382. }
  36383. else {
  36384. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36385. }
  36386. break;
  36387. case 2:
  36388. if (this._checkVerticesInsteadOfIndices) {
  36389. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36390. }
  36391. else {
  36392. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36393. }
  36394. break;
  36395. }
  36396. if (otherEdgeIndex === -1) {
  36397. continue;
  36398. }
  36399. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36400. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36401. faceAdjacencies.edgesConnectedCount++;
  36402. otherFaceAdjacencies.edgesConnectedCount++;
  36403. if (faceAdjacencies.edgesConnectedCount === 3) {
  36404. break;
  36405. }
  36406. }
  36407. }
  36408. }
  36409. // Create lines
  36410. for (index = 0; index < adjacencies.length; index++) {
  36411. // 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
  36412. var current = adjacencies[index];
  36413. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36414. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36415. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36416. }
  36417. // Merge into a single mesh
  36418. var engine = this._source.getScene().getEngine();
  36419. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36420. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36421. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36422. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36423. this._ib = engine.createIndexBuffer(this._linesIndices);
  36424. this._indicesCount = this._linesIndices.length;
  36425. };
  36426. EdgesRenderer.prototype.render = function () {
  36427. if (!this._lineShader.isReady()) {
  36428. return;
  36429. }
  36430. var scene = this._source.getScene();
  36431. var engine = scene.getEngine();
  36432. this._lineShader._preBind();
  36433. // VBOs
  36434. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36435. scene.resetCachedMaterial();
  36436. this._lineShader.setColor4("color", this._source.edgesColor);
  36437. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36438. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36439. }
  36440. else {
  36441. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36442. }
  36443. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36444. this._lineShader.bind(this._source.getWorldMatrix());
  36445. // Draw order
  36446. engine.draw(true, 0, this._indicesCount);
  36447. this._lineShader.unbind();
  36448. engine.setDepthWrite(true);
  36449. };
  36450. return EdgesRenderer;
  36451. })();
  36452. BABYLON.EdgesRenderer = EdgesRenderer;
  36453. })(BABYLON || (BABYLON = {}));
  36454. var BABYLON;
  36455. (function (BABYLON) {
  36456. (function (TonemappingOperator) {
  36457. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36458. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36459. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36460. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36461. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36462. var TonemappingOperator = BABYLON.TonemappingOperator;
  36463. ;
  36464. var TonemapPostProcess = (function (_super) {
  36465. __extends(TonemapPostProcess, _super);
  36466. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36467. var _this = this;
  36468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36469. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36470. this._operator = operator;
  36471. this._exposureAdjustment = exposureAdjustment;
  36472. var params = ["_ExposureAdjustment"];
  36473. var defines = "#define ";
  36474. if (operator === TonemappingOperator.Hable)
  36475. defines += "HABLE_TONEMAPPING";
  36476. else if (operator === TonemappingOperator.Reinhard)
  36477. defines += "REINHARD_TONEMAPPING";
  36478. else if (operator === TonemappingOperator.HejiDawson)
  36479. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36480. else if (operator === TonemappingOperator.Photographic)
  36481. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36482. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36483. this.onApply = function (effect) {
  36484. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  36485. };
  36486. }
  36487. return TonemapPostProcess;
  36488. })(BABYLON.PostProcess);
  36489. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36490. })(BABYLON || (BABYLON = {}));
  36491. var BABYLON;
  36492. (function (BABYLON) {
  36493. var ReflectionProbe = (function () {
  36494. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36495. var _this = this;
  36496. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36497. this.name = name;
  36498. this._viewMatrix = BABYLON.Matrix.Identity();
  36499. this._target = BABYLON.Vector3.Zero();
  36500. this._add = BABYLON.Vector3.Zero();
  36501. this.position = BABYLON.Vector3.Zero();
  36502. this._scene = scene;
  36503. this._scene.reflectionProbes.push(this);
  36504. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36505. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36506. switch (faceIndex) {
  36507. case 0:
  36508. _this._add.copyFromFloats(1, 0, 0);
  36509. break;
  36510. case 1:
  36511. _this._add.copyFromFloats(-1, 0, 0);
  36512. break;
  36513. case 2:
  36514. _this._add.copyFromFloats(0, -1, 0);
  36515. break;
  36516. case 3:
  36517. _this._add.copyFromFloats(0, 1, 0);
  36518. break;
  36519. case 4:
  36520. _this._add.copyFromFloats(0, 0, 1);
  36521. break;
  36522. case 5:
  36523. _this._add.copyFromFloats(0, 0, -1);
  36524. break;
  36525. }
  36526. if (_this._attachedMesh) {
  36527. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36528. }
  36529. _this.position.addToRef(_this._add, _this._target);
  36530. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36531. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36532. };
  36533. this._renderTargetTexture.onAfterUnbind = function () {
  36534. scene.updateTransformMatrix(true);
  36535. };
  36536. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36537. }
  36538. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36539. get: function () {
  36540. return this._renderTargetTexture.refreshRate;
  36541. },
  36542. set: function (value) {
  36543. this._renderTargetTexture.refreshRate = value;
  36544. },
  36545. enumerable: true,
  36546. configurable: true
  36547. });
  36548. ReflectionProbe.prototype.getScene = function () {
  36549. return this._scene;
  36550. };
  36551. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36552. get: function () {
  36553. return this._renderTargetTexture;
  36554. },
  36555. enumerable: true,
  36556. configurable: true
  36557. });
  36558. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36559. get: function () {
  36560. return this._renderTargetTexture.renderList;
  36561. },
  36562. enumerable: true,
  36563. configurable: true
  36564. });
  36565. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36566. this._attachedMesh = mesh;
  36567. };
  36568. ReflectionProbe.prototype.dispose = function () {
  36569. var index = this._scene.reflectionProbes.indexOf(this);
  36570. if (index !== -1) {
  36571. // Remove from the scene if found
  36572. this._scene.reflectionProbes.splice(index, 1);
  36573. }
  36574. if (this._renderTargetTexture) {
  36575. this._renderTargetTexture.dispose();
  36576. this._renderTargetTexture = null;
  36577. }
  36578. };
  36579. return ReflectionProbe;
  36580. })();
  36581. BABYLON.ReflectionProbe = ReflectionProbe;
  36582. })(BABYLON || (BABYLON = {}));
  36583. var BABYLON;
  36584. (function (BABYLON) {
  36585. var SolidParticle = (function () {
  36586. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36587. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36588. this.position = BABYLON.Vector3.Zero(); // position
  36589. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36590. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36591. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36592. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36593. this.alive = true; // alive
  36594. this.idx = particleIndex;
  36595. this._pos = positionIndex;
  36596. this._model = model;
  36597. this.shapeId = shapeId;
  36598. this.idxInShape = idxInShape;
  36599. }
  36600. return SolidParticle;
  36601. })();
  36602. BABYLON.SolidParticle = SolidParticle;
  36603. var ModelShape = (function () {
  36604. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36605. this.shapeID = id;
  36606. this._shape = shape;
  36607. this._shapeUV = shapeUV;
  36608. this._positionFunction = posFunction;
  36609. this._vertexFunction = vtxFunction;
  36610. }
  36611. return ModelShape;
  36612. })();
  36613. BABYLON.ModelShape = ModelShape;
  36614. })(BABYLON || (BABYLON = {}));
  36615. var BABYLON;
  36616. (function (BABYLON) {
  36617. /**
  36618. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36619. */
  36620. var SolidParticleSystem = (function () {
  36621. /**
  36622. * Creates a SPS (Solid Particle System) object.
  36623. * @param name the SPS name, this will be the underlying mesh name
  36624. * @param updatable (default true) if the SPS must be updatable or immutable
  36625. * @param isPickable (default false) if the solid particles must be pickable
  36626. */
  36627. function SolidParticleSystem(name, scene, options) {
  36628. // public members
  36629. this.particles = new Array();
  36630. this.nbParticles = 0;
  36631. this.billboard = false;
  36632. this.counter = 0;
  36633. this.vars = {};
  36634. this._positions = new Array();
  36635. this._indices = new Array();
  36636. this._normals = new Array();
  36637. this._colors = new Array();
  36638. this._uvs = new Array();
  36639. this._index = 0; // indices index
  36640. this._updatable = true;
  36641. this._pickable = false;
  36642. this._alwaysVisible = false;
  36643. this._shapeCounter = 0;
  36644. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36645. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36646. this._computeParticleColor = true;
  36647. this._computeParticleTexture = true;
  36648. this._computeParticleRotation = true;
  36649. this._computeParticleVertex = false;
  36650. this._cam_axisZ = BABYLON.Vector3.Zero();
  36651. this._cam_axisY = BABYLON.Vector3.Zero();
  36652. this._cam_axisX = BABYLON.Vector3.Zero();
  36653. this._axisX = BABYLON.Axis.X;
  36654. this._axisY = BABYLON.Axis.Y;
  36655. this._axisZ = BABYLON.Axis.Z;
  36656. this._fakeCamPos = BABYLON.Vector3.Zero();
  36657. this._rotMatrix = new BABYLON.Matrix();
  36658. this._invertMatrix = new BABYLON.Matrix();
  36659. this._rotated = BABYLON.Vector3.Zero();
  36660. this._quaternion = new BABYLON.Quaternion();
  36661. this._vertex = BABYLON.Vector3.Zero();
  36662. this._normal = BABYLON.Vector3.Zero();
  36663. this._yaw = 0.0;
  36664. this._pitch = 0.0;
  36665. this._roll = 0.0;
  36666. this._halfroll = 0.0;
  36667. this._halfpitch = 0.0;
  36668. this._halfyaw = 0.0;
  36669. this._sinRoll = 0.0;
  36670. this._cosRoll = 0.0;
  36671. this._sinPitch = 0.0;
  36672. this._cosPitch = 0.0;
  36673. this._sinYaw = 0.0;
  36674. this._cosYaw = 0.0;
  36675. this._w = 0.0;
  36676. this.name = name;
  36677. this._scene = scene;
  36678. this._camera = scene.activeCamera;
  36679. this._pickable = options ? options.isPickable : false;
  36680. if (options && options.updatable) {
  36681. this._updatable = options.updatable;
  36682. }
  36683. else {
  36684. this._updatable = true;
  36685. }
  36686. if (this._pickable) {
  36687. this.pickedParticles = [];
  36688. }
  36689. }
  36690. /**
  36691. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36692. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36693. */
  36694. SolidParticleSystem.prototype.buildMesh = function () {
  36695. if (this.nbParticles === 0) {
  36696. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36697. this.addShape(triangle, 1);
  36698. triangle.dispose();
  36699. }
  36700. this._positions32 = new Float32Array(this._positions);
  36701. this._uvs32 = new Float32Array(this._uvs);
  36702. this._colors32 = new Float32Array(this._colors);
  36703. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36704. this._normals32 = new Float32Array(this._normals);
  36705. this._fixedNormal32 = new Float32Array(this._normals);
  36706. var vertexData = new BABYLON.VertexData();
  36707. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36708. vertexData.indices = this._indices;
  36709. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36710. if (this._uvs32) {
  36711. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36712. ;
  36713. }
  36714. if (this._colors32) {
  36715. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36716. }
  36717. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36718. vertexData.applyToMesh(mesh, this._updatable);
  36719. this.mesh = mesh;
  36720. this.mesh.isPickable = this._pickable;
  36721. // free memory
  36722. this._positions = null;
  36723. this._normals = null;
  36724. this._uvs = null;
  36725. this._colors = null;
  36726. if (!this._updatable) {
  36727. this.particles.length = 0;
  36728. }
  36729. return mesh;
  36730. };
  36731. //reset copy
  36732. SolidParticleSystem.prototype._resetCopy = function () {
  36733. this._copy.position.x = 0;
  36734. this._copy.position.y = 0;
  36735. this._copy.position.z = 0;
  36736. this._copy.rotation.x = 0;
  36737. this._copy.rotation.y = 0;
  36738. this._copy.rotation.z = 0;
  36739. this._copy.quaternion = null;
  36740. this._copy.scale.x = 1;
  36741. this._copy.scale.y = 1;
  36742. this._copy.scale.z = 1;
  36743. this._copy.uvs.x = 0;
  36744. this._copy.uvs.y = 0;
  36745. this._copy.uvs.z = 1;
  36746. this._copy.uvs.w = 1;
  36747. this._copy.color = null;
  36748. };
  36749. // _meshBuilder : inserts the shape model in the global SPS mesh
  36750. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36751. var i;
  36752. var u = 0;
  36753. var c = 0;
  36754. this._resetCopy();
  36755. if (options && options.positionFunction) {
  36756. options.positionFunction(this._copy, idx, idxInShape);
  36757. }
  36758. if (this._copy.quaternion) {
  36759. this._quaternion.x = this._copy.quaternion.x;
  36760. this._quaternion.y = this._copy.quaternion.y;
  36761. this._quaternion.z = this._copy.quaternion.z;
  36762. this._quaternion.w = this._copy.quaternion.w;
  36763. }
  36764. else {
  36765. this._yaw = this._copy.rotation.y;
  36766. this._pitch = this._copy.rotation.x;
  36767. this._roll = this._copy.rotation.z;
  36768. this._quaternionRotationYPR();
  36769. }
  36770. this._quaternionToRotationMatrix();
  36771. for (i = 0; i < shape.length; i++) {
  36772. this._vertex.x = shape[i].x;
  36773. this._vertex.y = shape[i].y;
  36774. this._vertex.z = shape[i].z;
  36775. if (options && options.vertexFunction) {
  36776. options.vertexFunction(this._copy, this._vertex, i);
  36777. }
  36778. this._vertex.x *= this._copy.scale.x;
  36779. this._vertex.y *= this._copy.scale.y;
  36780. this._vertex.z *= this._copy.scale.z;
  36781. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36782. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36783. if (meshUV) {
  36784. 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);
  36785. u += 2;
  36786. }
  36787. if (this._copy.color) {
  36788. this._color = this._copy.color;
  36789. }
  36790. else if (meshCol && meshCol[c]) {
  36791. this._color.r = meshCol[c];
  36792. this._color.g = meshCol[c + 1];
  36793. this._color.b = meshCol[c + 2];
  36794. this._color.a = meshCol[c + 3];
  36795. }
  36796. else {
  36797. this._color.r = 1;
  36798. this._color.g = 1;
  36799. this._color.b = 1;
  36800. this._color.a = 1;
  36801. }
  36802. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36803. c += 4;
  36804. }
  36805. for (i = 0; i < meshInd.length; i++) {
  36806. indices.push(p + meshInd[i]);
  36807. }
  36808. if (this._pickable) {
  36809. var nbfaces = meshInd.length / 3;
  36810. for (i = 0; i < nbfaces; i++) {
  36811. this.pickedParticles.push({ idx: idx, faceId: i });
  36812. }
  36813. }
  36814. };
  36815. // returns a shape array from positions array
  36816. SolidParticleSystem.prototype._posToShape = function (positions) {
  36817. var shape = [];
  36818. for (var i = 0; i < positions.length; i += 3) {
  36819. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36820. }
  36821. return shape;
  36822. };
  36823. // returns a shapeUV array from a Vector4 uvs
  36824. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36825. var shapeUV = [];
  36826. if (uvs) {
  36827. for (var i = 0; i < uvs.length; i++)
  36828. shapeUV.push(uvs[i]);
  36829. }
  36830. return shapeUV;
  36831. };
  36832. // adds a new particle object in the particles array
  36833. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36834. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36835. };
  36836. /**
  36837. * Adds some particles to the SPS from the model shape.
  36838. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  36839. * @param mesh any Mesh object that will be used as a model for the solid particles.
  36840. * @param nb the number of particles to be created from this model
  36841. * @param positionFunction an optional javascript function to called for each particle on SPS creation
  36842. * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  36843. */
  36844. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36845. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36846. var meshInd = mesh.getIndices();
  36847. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36848. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36849. var shape = this._posToShape(meshPos);
  36850. var shapeUV = this._uvsToShapeUV(meshUV);
  36851. var posfunc = options ? options.positionFunction : null;
  36852. var vtxfunc = options ? options.vertexFunction : null;
  36853. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36854. // particles
  36855. var idx = this.nbParticles;
  36856. for (var i = 0; i < nb; i++) {
  36857. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36858. if (this._updatable) {
  36859. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36860. }
  36861. this._index += shape.length;
  36862. idx++;
  36863. }
  36864. this.nbParticles += nb;
  36865. this._shapeCounter++;
  36866. return this._shapeCounter;
  36867. };
  36868. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36869. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36870. this._resetCopy();
  36871. if (particle._model._positionFunction) {
  36872. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36873. }
  36874. if (this._copy.quaternion) {
  36875. this._quaternion.x = this._copy.quaternion.x;
  36876. this._quaternion.y = this._copy.quaternion.y;
  36877. this._quaternion.z = this._copy.quaternion.z;
  36878. this._quaternion.w = this._copy.quaternion.w;
  36879. }
  36880. else {
  36881. this._yaw = this._copy.rotation.y;
  36882. this._pitch = this._copy.rotation.x;
  36883. this._roll = this._copy.rotation.z;
  36884. this._quaternionRotationYPR();
  36885. }
  36886. this._quaternionToRotationMatrix();
  36887. this._shape = particle._model._shape;
  36888. for (var pt = 0; pt < this._shape.length; pt++) {
  36889. this._vertex.x = this._shape[pt].x;
  36890. this._vertex.y = this._shape[pt].y;
  36891. this._vertex.z = this._shape[pt].z;
  36892. if (particle._model._vertexFunction) {
  36893. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36894. }
  36895. this._vertex.x *= this._copy.scale.x;
  36896. this._vertex.y *= this._copy.scale.y;
  36897. this._vertex.z *= this._copy.scale.z;
  36898. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36899. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36900. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36901. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36902. }
  36903. particle.position.x = 0;
  36904. particle.position.y = 0;
  36905. particle.position.z = 0;
  36906. particle.rotation.x = 0;
  36907. particle.rotation.y = 0;
  36908. particle.rotation.z = 0;
  36909. particle.quaternion = null;
  36910. particle.scale.x = 1;
  36911. particle.scale.y = 1;
  36912. particle.scale.z = 1;
  36913. };
  36914. /**
  36915. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  36916. */
  36917. SolidParticleSystem.prototype.rebuildMesh = function () {
  36918. for (var p = 0; p < this.particles.length; p++) {
  36919. this._rebuildParticle(this.particles[p]);
  36920. }
  36921. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36922. };
  36923. /**
  36924. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  36925. * This method calls updateParticle() for each particles of the SPS.
  36926. * For an animated SPS, it is usually called within the render loop.
  36927. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  36928. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  36929. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  36930. */
  36931. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36932. if (start === void 0) { start = 0; }
  36933. if (end === void 0) { end = this.nbParticles - 1; }
  36934. if (update === void 0) { update = true; }
  36935. if (!this._updatable) {
  36936. return;
  36937. }
  36938. // custom beforeUpdate
  36939. this.beforeUpdateParticles(start, end, update);
  36940. this._cam_axisX.x = 1;
  36941. this._cam_axisX.y = 0;
  36942. this._cam_axisX.z = 0;
  36943. this._cam_axisY.x = 0;
  36944. this._cam_axisY.y = 1;
  36945. this._cam_axisY.z = 0;
  36946. this._cam_axisZ.x = 0;
  36947. this._cam_axisZ.y = 0;
  36948. this._cam_axisZ.z = 1;
  36949. // if the particles will always face the camera
  36950. if (this.billboard) {
  36951. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36952. this._yaw = this.mesh.rotation.y;
  36953. this._pitch = this.mesh.rotation.x;
  36954. this._roll = this.mesh.rotation.z;
  36955. this._quaternionRotationYPR();
  36956. this._quaternionToRotationMatrix();
  36957. this._rotMatrix.invertToRef(this._invertMatrix);
  36958. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36959. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36960. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36961. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36962. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36963. this._cam_axisY.normalize();
  36964. this._cam_axisX.normalize();
  36965. this._cam_axisZ.normalize();
  36966. }
  36967. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36968. var idx = 0;
  36969. var index = 0;
  36970. var colidx = 0;
  36971. var colorIndex = 0;
  36972. var uvidx = 0;
  36973. var uvIndex = 0;
  36974. // particle loop
  36975. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36976. for (var p = start; p <= end; p++) {
  36977. this._particle = this.particles[p];
  36978. this._shape = this._particle._model._shape;
  36979. this._shapeUV = this._particle._model._shapeUV;
  36980. // call to custom user function to update the particle properties
  36981. this.updateParticle(this._particle);
  36982. // particle rotation matrix
  36983. if (this.billboard) {
  36984. this._particle.rotation.x = 0.0;
  36985. this._particle.rotation.y = 0.0;
  36986. }
  36987. if (this._computeParticleRotation) {
  36988. if (this._particle.quaternion) {
  36989. this._quaternion.x = this._particle.quaternion.x;
  36990. this._quaternion.y = this._particle.quaternion.y;
  36991. this._quaternion.z = this._particle.quaternion.z;
  36992. this._quaternion.w = this._particle.quaternion.w;
  36993. }
  36994. else {
  36995. this._yaw = this._particle.rotation.y;
  36996. this._pitch = this._particle.rotation.x;
  36997. this._roll = this._particle.rotation.z;
  36998. this._quaternionRotationYPR();
  36999. }
  37000. this._quaternionToRotationMatrix();
  37001. }
  37002. for (var pt = 0; pt < this._shape.length; pt++) {
  37003. idx = index + pt * 3;
  37004. colidx = colorIndex + pt * 4;
  37005. uvidx = uvIndex + pt * 2;
  37006. this._vertex.x = this._shape[pt].x;
  37007. this._vertex.y = this._shape[pt].y;
  37008. this._vertex.z = this._shape[pt].z;
  37009. if (this._computeParticleVertex) {
  37010. this.updateParticleVertex(this._particle, this._vertex, pt);
  37011. }
  37012. // positions
  37013. this._vertex.x *= this._particle.scale.x;
  37014. this._vertex.y *= this._particle.scale.y;
  37015. this._vertex.z *= this._particle.scale.z;
  37016. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  37017. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  37018. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  37019. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  37020. 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;
  37021. 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;
  37022. 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;
  37023. // normals : if the particles can't be morphed then just rotate the normals
  37024. if (!this._computeParticleVertex && !this.billboard) {
  37025. this._normal.x = this._fixedNormal32[idx];
  37026. this._normal.y = this._fixedNormal32[idx + 1];
  37027. this._normal.z = this._fixedNormal32[idx + 2];
  37028. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  37029. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  37030. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  37031. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  37032. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37033. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  37034. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  37035. }
  37036. if (this._computeParticleColor) {
  37037. this._colors32[colidx] = this._particle.color.r;
  37038. this._colors32[colidx + 1] = this._particle.color.g;
  37039. this._colors32[colidx + 2] = this._particle.color.b;
  37040. this._colors32[colidx + 3] = this._particle.color.a;
  37041. }
  37042. if (this._computeParticleTexture) {
  37043. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37044. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37045. }
  37046. }
  37047. index = idx + 3;
  37048. colorIndex = colidx + 4;
  37049. uvIndex = uvidx + 2;
  37050. }
  37051. if (update) {
  37052. if (this._computeParticleColor) {
  37053. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37054. }
  37055. if (this._computeParticleTexture) {
  37056. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37057. }
  37058. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37059. if (!this.mesh.areNormalsFrozen) {
  37060. if (this._computeParticleVertex || this.billboard) {
  37061. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37062. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37063. for (var i = 0; i < this._normals32.length; i++) {
  37064. this._fixedNormal32[i] = this._normals32[i];
  37065. }
  37066. }
  37067. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37068. }
  37069. }
  37070. this.afterUpdateParticles(start, end, update);
  37071. };
  37072. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37073. this._halfroll = this._roll * 0.5;
  37074. this._halfpitch = this._pitch * 0.5;
  37075. this._halfyaw = this._yaw * 0.5;
  37076. this._sinRoll = Math.sin(this._halfroll);
  37077. this._cosRoll = Math.cos(this._halfroll);
  37078. this._sinPitch = Math.sin(this._halfpitch);
  37079. this._cosPitch = Math.cos(this._halfpitch);
  37080. this._sinYaw = Math.sin(this._halfyaw);
  37081. this._cosYaw = Math.cos(this._halfyaw);
  37082. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37083. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37084. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37085. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37086. };
  37087. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37088. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37089. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37090. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37091. this._rotMatrix.m[3] = 0;
  37092. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37093. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37094. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37095. this._rotMatrix.m[7] = 0;
  37096. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37097. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37098. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37099. this._rotMatrix.m[11] = 0;
  37100. this._rotMatrix.m[12] = 0;
  37101. this._rotMatrix.m[13] = 0;
  37102. this._rotMatrix.m[14] = 0;
  37103. this._rotMatrix.m[15] = 1.0;
  37104. };
  37105. /**
  37106. * Disposes the SPS
  37107. */
  37108. SolidParticleSystem.prototype.dispose = function () {
  37109. this.mesh.dispose();
  37110. this.vars = null;
  37111. // drop references to internal big arrays for the GC
  37112. this._positions = null;
  37113. this._indices = null;
  37114. this._normals = null;
  37115. this._uvs = null;
  37116. this._colors = null;
  37117. this._positions32 = null;
  37118. this._normals32 = null;
  37119. this._fixedNormal32 = null;
  37120. this._uvs32 = null;
  37121. this._colors32 = null;
  37122. this.pickedParticles = null;
  37123. };
  37124. /**
  37125. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37126. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37127. */
  37128. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37129. this.mesh.refreshBoundingInfo();
  37130. };
  37131. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37132. // getter and setter
  37133. /**
  37134. * True if the SPS is set as always visible
  37135. */
  37136. get: function () {
  37137. return this._alwaysVisible;
  37138. },
  37139. /**
  37140. * Sets the SPS as always visible or not
  37141. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37142. */
  37143. set: function (val) {
  37144. this._alwaysVisible = val;
  37145. this.mesh.alwaysSelectAsActiveMesh = val;
  37146. },
  37147. enumerable: true,
  37148. configurable: true
  37149. });
  37150. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37151. // getters
  37152. get: function () {
  37153. return this._computeParticleRotation;
  37154. },
  37155. // Optimizer setters
  37156. /**
  37157. * Tells to setParticle() to compute the particle rotations or not.
  37158. * Default value : true. The SPS is faster when it's set to false.
  37159. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37160. */
  37161. set: function (val) {
  37162. this._computeParticleRotation = val;
  37163. },
  37164. enumerable: true,
  37165. configurable: true
  37166. });
  37167. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37168. get: function () {
  37169. return this._computeParticleColor;
  37170. },
  37171. /**
  37172. * Tells to setParticle() to compute the particle colors or not.
  37173. * Default value : true. The SPS is faster when it's set to false.
  37174. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37175. */
  37176. set: function (val) {
  37177. this._computeParticleColor = val;
  37178. },
  37179. enumerable: true,
  37180. configurable: true
  37181. });
  37182. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37183. get: function () {
  37184. return this._computeParticleTexture;
  37185. },
  37186. /**
  37187. * Tells to setParticle() to compute the particle textures or not.
  37188. * Default value : true. The SPS is faster when it's set to false.
  37189. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37190. */
  37191. set: function (val) {
  37192. this._computeParticleTexture = val;
  37193. },
  37194. enumerable: true,
  37195. configurable: true
  37196. });
  37197. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37198. get: function () {
  37199. return this._computeParticleVertex;
  37200. },
  37201. /**
  37202. * Tells to setParticle() to call the vertex function for each vertex of each particle, or not.
  37203. * Default value : false. The SPS is faster when it's set to false.
  37204. * Note : the particle custom vertex positions aren't stored values.
  37205. */
  37206. set: function (val) {
  37207. this._computeParticleVertex = val;
  37208. },
  37209. enumerable: true,
  37210. configurable: true
  37211. });
  37212. // =======================================================================
  37213. // Particle behavior logic
  37214. // these following methods may be overwritten by the user to fit his needs
  37215. /**
  37216. * This function does nothing. It may be overwritten to set all the particles first values.
  37217. * The SPS doesn't call this function, you may have to call it by your own.
  37218. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37219. */
  37220. SolidParticleSystem.prototype.initParticles = function () {
  37221. };
  37222. /**
  37223. * This function does nothing. It may be overwritten to recycle a particle.
  37224. * The SPS doesn't call this function, you may have to call it by your own.
  37225. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37226. */
  37227. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37228. return particle;
  37229. };
  37230. /**
  37231. * Updates a particle : this function should be overwritten by the user.
  37232. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37233. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37234. * ex : just set a particle position or velocity and recycle conditions
  37235. */
  37236. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37237. return particle;
  37238. };
  37239. /**
  37240. * Updates a vertex of a particle : it can be overwritten by the user.
  37241. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37242. * @param particle the current particle
  37243. * @param vertex the current index of the current particle
  37244. * @param pt the index of the current vertex in the particle shape
  37245. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37246. * ex : just set a vertex particle position
  37247. */
  37248. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37249. return vertex;
  37250. };
  37251. /**
  37252. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37253. * This does nothing and may be overwritten by the user.
  37254. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37255. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37256. * @param update the boolean update value actually passed to setParticles()
  37257. */
  37258. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37259. };
  37260. /**
  37261. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37262. * This will be passed three parameters.
  37263. * This does nothing and may be overwritten by the user.
  37264. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37265. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37266. * @param update the boolean update value actually passed to setParticles()
  37267. */
  37268. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37269. };
  37270. return SolidParticleSystem;
  37271. })();
  37272. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37273. })(BABYLON || (BABYLON = {}));
  37274. 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}","chromaticAberrationPixelShader":"precision 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}","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":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\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_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.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\nuniform vec2 depthValues;\r\n\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\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < 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\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#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\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\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * 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 * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\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\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef 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_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\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\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","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}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","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}","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\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\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\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\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}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  37275. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h=n.normalize(),a=o.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,l=0,x=0,z=0,w=0,v=-1,g=0,d=i.Zero(),T=0;t.Tools.WithinEpsilon(a.z,0,t.Engine.Epsilon)?z=1:t.Tools.WithinEpsilon(a.x,0,t.Engine.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),e=new i(l,x,z),e.normalize(),i.CrossToRef(h,e,d),d.normalize(),i.Dot(a,d)<0&&(v=1),T=i.Dot(h,e),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,i.Dot(e,u)<0&&(p=Math.PI+p,e=e.scaleInPlace(-1),g++);var R,_;l=0,x=0,z=0,v=-1,t.Tools.WithinEpsilon(a.z,0,t.Engine.Epsilon)?l=1:(w=e.z/e.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R=new i(l,x,z),R.normalize(),_=i.Cross(R,e),_.normalize(),i.CrossToRef(a,R,d),d.normalize(),i.Dot(e,d)<0&&(v=1),T=i.Dot(a,R),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,i.Dot(_,m)<0&&(c=Math.PI+c,g++),v=-1,i.CrossToRef(u,e,d),d.normalize(),i.Dot(d,m)<0&&(v=1),T=i.Dot(e,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>g&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,Z=s*l-h*p,E=s*f-e*p,L=h*c-a*y,q=e*c-a*m,S=e*y-h*m,D=s*c-a*u,W=s*y-h*u,V=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*Z)*b,t.m[10]=(i*P-n*I+o*E)*b,t.m[14]=-(i*C-n*Z+r*E)*b,t.m[3]=-(n*L-r*q+o*S)*b,t.m[7]=(i*L-r*D+o*W)*b,t.m[11]=-(i*q-n*D+o*V)*b,t.m[15]=(i*S-n*W+r*V)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],Z=t.m[13],E=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*Z,i[n+2]=r*d+o*M+s*P+e*E,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*Z,i[n+6]=h*d+a*M+u*P+m*E,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*Z,i[n+10]=y*d+c*M+p*P+f*E,i[n+11]=y*T+c*F+p*C+f*L,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*Z,i[n+14]=l*d+x*M+z*P+w*E,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,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,\nn.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){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Int=[0,0,0,0,0,0],t.Float=[0,0,0,0,0,0],t.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  37276. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  37277. module.exports = BABYLON;
  37278. };